refactor(auth): delegate access control to be-system

Remove Agent Desk users, roles, login sessions, tokens, and local permission persistence. Expose the backend as an embeddable ai-agent module with host-provided subject lookup and operation authorization callbacks, and complete the frontend/backend repository split.
This commit is contained in:
t
2026-08-21 00:41:07 +08:00
parent 3d47227fbd
commit 2bbf42b741
447 changed files with 1901 additions and 8920 deletions
+57 -276
View File
@@ -1,299 +1,80 @@
package services
import (
"agent-desk/internal/models"
"agent-desk/internal/pkg/dto"
"agent-desk/internal/pkg/dto/request"
"agent-desk/internal/pkg/enums"
"agent-desk/internal/pkg/errorsx"
"agent-desk/internal/pkg/utils"
"agent-desk/internal/repositories"
"slices"
"strings"
"time"
"context"
"agent-desk/internal/pkg/httpx/params"
"github.com/mlogclub/simple/sqls"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"code.tczkiot.com/wlw/ai-agent/identity"
"code.tczkiot.com/wlw/ai-agent/internal/pkg/enums"
)
var UserService = newUserService()
func newUserService() *userService {
return &userService{}
// ExternalUser is a non-persistent display adapter for a system identity owned
// by be-system.
type ExternalUser struct {
ID int64
SubjectType identity.SubjectType
Username string
Nickname string
Avatar string
Status enums.Status
}
type userService struct {
}
var UserService = &externalUserService{}
func (s *userService) Get(id int64) *models.User {
return repositories.UserRepository.Get(sqls.DB(), id)
}
type externalUserService struct{}
func (s *userService) Take(where ...interface{}) *models.User {
return repositories.UserRepository.Take(sqls.DB(), where...)
}
func (s *userService) Find(cnd *sqls.Cnd) []models.User {
return repositories.UserRepository.Find(sqls.DB(), cnd)
}
func (s *userService) FindOne(cnd *sqls.Cnd) *models.User {
return repositories.UserRepository.FindOne(sqls.DB(), cnd)
}
func (s *userService) FindPageByParams(params *params.QueryParams) (list []models.User, paging *sqls.Paging) {
return repositories.UserRepository.FindPageByParams(sqls.DB(), params)
}
func (s *userService) FindPageByCnd(cnd *sqls.Cnd) (list []models.User, paging *sqls.Paging) {
return repositories.UserRepository.FindPageByCnd(sqls.DB(), cnd)
}
func (s *userService) Count(cnd *sqls.Cnd) int64 {
return repositories.UserRepository.Count(sqls.DB(), cnd)
}
func (s *userService) FindByIds(ids []int64) []models.User {
return repositories.UserRepository.FindByIds(sqls.DB(), ids)
}
func (s *userService) Create(t *models.User) error {
return repositories.UserRepository.Create(sqls.DB(), t)
}
func (s *userService) Update(t *models.User) error {
return repositories.UserRepository.Update(sqls.DB(), t)
}
func (s *userService) Updates(id int64, columns map[string]interface{}) error {
return repositories.UserRepository.Updates(sqls.DB(), id, columns)
}
func (s *userService) UpdateColumn(id int64, name string, value interface{}) error {
return repositories.UserRepository.UpdateColumn(sqls.DB(), id, name, value)
}
func (s *userService) GetByUsername(username string) *models.User {
return repositories.UserRepository.GetByUsername(sqls.DB(), username)
}
func (s *userService) GetByMobile(mobile string) *models.User {
return repositories.UserRepository.GetByMobile(sqls.DB(), mobile)
}
func (s *userService) GetByEmail(email string) *models.User {
return repositories.UserRepository.GetByEmail(sqls.DB(), email)
}
func (s *userService) CreateUser(req request.CreateUserRequest, operator *dto.AuthPrincipal) (*models.User, string, error) {
username := strings.TrimSpace(req.Username)
if username == "" {
return nil, "", errorsx.InvalidParamI18n("error.e0257")
}
if s.GetByUsername(username) != nil {
return nil, "", errorsx.InvalidParamI18n("error.e0259")
func (s *externalUserService) Get(id int64) *ExternalUser {
items := s.FindByIds([]int64{id})
if len(items) == 0 {
return nil
}
return &items[0]
}
mobile := utils.NormalizeNullableString(req.Mobile)
email := utils.NormalizeNullableString(req.Email)
if mobile != nil && s.GetByMobile(*mobile) != nil {
return nil, "", errorsx.InvalidParamI18n("error.e0206")
func (s *externalUserService) FindByIds(ids []int64) []ExternalUser {
if len(ids) == 0 {
return nil
}
if email != nil && s.GetByEmail(*email) != nil {
return nil, "", errorsx.InvalidParamI18n("error.e0338")
}
plain, err := utils.GenerateRandomPassword(12)
if err != nil {
return nil, "", err
}
passwordHash, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)
if err != nil {
return nil, "", err
}
user := &models.User{
Username: username,
Nickname: strings.TrimSpace(req.Nickname),
Password: string(passwordHash),
Avatar: strings.TrimSpace(req.Avatar),
Mobile: mobile,
Email: email,
Status: enums.StatusOk,
Remark: strings.TrimSpace(req.Remark),
PasswordSalt: "",
AuditFields: utils.BuildAuditFields(operator),
}
if user.Nickname == "" {
user.Nickname = username
}
err = sqls.WithTransaction(func(ctx *sqls.TxContext) error {
if err := repositories.UserRepository.Create(ctx.Tx, user); err != nil {
return err
}
return s.replaceUserRolesDB(ctx.Tx, user.ID, req.RoleIDs, operator)
subjects, err := SubjectService.Query(context.Background(), identity.Query{
Types: []identity.SubjectType{identity.SubjectAgent},
IDs: ids,
EnabledOnly: true,
})
if err != nil {
return nil, "", err
return nil
}
return user, plain, nil
users := make([]ExternalUser, 0, len(subjects))
for _, subject := range subjects {
status := enums.StatusDisabled
if subject.Enabled {
status = enums.StatusOk
}
users = append(users, ExternalUser{
ID: subject.ID,
SubjectType: subject.Type,
Username: subject.Username,
Nickname: subject.Name,
Avatar: subject.Avatar,
Status: status,
})
}
return users
}
func (s *userService) UpdateUser(req request.UpdateUserRequest, operator *dto.AuthPrincipal) error {
user := s.Get(req.ID)
if user == nil || user.DeletedAt != nil {
return errorsx.InvalidParamI18n("error.e0255")
}
mobile := utils.NormalizeNullableString(req.Mobile)
email := utils.NormalizeNullableString(req.Email)
if mobile != nil {
if existed := s.GetByMobile(*mobile); existed != nil && existed.ID != req.ID {
return errorsx.InvalidParamI18n("error.e0206")
}
}
if email != nil {
if existed := s.GetByEmail(*email); existed != nil && existed.ID != req.ID {
return errorsx.InvalidParamI18n("error.e0338")
}
}
return s.Updates(req.ID, map[string]any{
"nickname": strings.TrimSpace(req.Nickname),
"avatar": strings.TrimSpace(req.Avatar),
"mobile": mobile,
"email": email,
"remark": strings.TrimSpace(req.Remark),
"update_user_id": operator.UserID,
"update_user_name": operator.Username,
"updated_at": time.Now(),
func (s *externalUserService) Find(keyword string) []ExternalUser {
subjects, err := SubjectService.Query(context.Background(), identity.Query{
Types: []identity.SubjectType{identity.SubjectAgent},
Keyword: keyword,
EnabledOnly: true,
})
}
func (s *userService) DeleteUser(id int64, operator *dto.AuthPrincipal) error {
user := s.Get(id)
if user == nil {
return errorsx.InvalidParamI18n("error.e0255")
}
if err := s.Updates(id, map[string]any{
"status": enums.StatusDisabled,
"deleted_at": time.Now(),
"update_user_id": operator.UserID,
"update_user_name": operator.Username,
"updated_at": time.Now(),
}); err != nil {
return err
}
return LoginSessionService.RevokeByUser(id, operator.UserID, operator.Username)
}
func (s *userService) UpdateStatus(id int64, status int, operator *dto.AuthPrincipal) error {
user := s.Get(id)
if user == nil {
return errorsx.InvalidParamI18n("error.e0255")
}
if !slices.Contains(enums.StatusValues, enums.Status(status)) {
return errorsx.InvalidParamI18n("error.e0254")
}
if err := s.Updates(id, map[string]any{
"status": status,
"update_user_id": operator.UserID,
"update_user_name": operator.Username,
"updated_at": time.Now(),
}); err != nil {
return err
}
if status == int(enums.StatusDisabled) || status == int(enums.StatusDeleted) {
return LoginSessionService.RevokeByUser(id, operator.UserID, operator.Username)
}
return nil
}
func (s *userService) ResetPassword(userID int64, operator *dto.AuthPrincipal) (string, error) {
password, err := utils.GenerateRandomPassword(12)
if err != nil {
return "", err
return nil
}
if err = s.changePassword(userID, password, operator); err != nil {
return "", err
users := make([]ExternalUser, 0, len(subjects))
for _, subject := range subjects {
users = append(users, ExternalUser{
ID: subject.ID, SubjectType: subject.Type, Username: subject.Username,
Nickname: subject.Name, Avatar: subject.Avatar, Status: enums.StatusOk,
})
}
return password, nil
}
func (s *userService) ChangeOwnPassword(password string, operator *dto.AuthPrincipal) error {
if operator == nil || operator.UserID <= 0 {
return errorsx.UnauthorizedI18n("error.auth.expired")
}
return s.changePassword(operator.UserID, password, operator)
}
func (s *userService) AssignRoles(userID int64, roleIDs []int64, operator *dto.AuthPrincipal) error {
user := s.Get(userID)
if user == nil || user.DeletedAt != nil {
return errorsx.InvalidParamI18n("error.e0255")
}
if err := s.replaceUserRoles(userID, roleIDs, operator); err != nil {
return err
}
return LoginSessionService.RevokeByUser(userID, operator.UserID, operator.Username)
}
func (s *userService) replaceUserRoles(userID int64, roleIDs []int64, operator *dto.AuthPrincipal) error {
return sqls.WithTransaction(func(ctx *sqls.TxContext) error {
return s.replaceUserRolesDB(ctx.Tx, userID, roleIDs, operator)
})
}
func (s *userService) replaceUserRolesDB(db *gorm.DB, userID int64, roleIDs []int64, operator *dto.AuthPrincipal) error {
if err := db.Where("user_id = ?", userID).Delete(&models.UserRole{}).Error; err != nil {
return err
}
for _, roleID := range roleIDs {
role := RoleService.Get(roleID)
if role == nil {
return errorsx.InvalidParamI18n("error.e0305")
}
if role.Status != enums.StatusOk {
return errorsx.InvalidParamI18n("error.e0291")
}
relation := &models.UserRole{
UserID: userID,
RoleID: roleID,
AuditFields: utils.BuildAuditFields(operator),
}
if err := db.Create(relation).Error; err != nil {
return err
}
}
return nil
}
func (s *userService) changePassword(userID int64, password string, operator *dto.AuthPrincipal) error {
user := s.Get(userID)
if user == nil || user.DeletedAt != nil {
return errorsx.InvalidParamI18n("error.e0255")
}
if strings.TrimSpace(password) == "" {
return errorsx.InvalidParamI18n("error.e0220")
}
passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
now := time.Now()
if err = s.Updates(userID, map[string]any{
"password": string(passwordHash),
"update_user_id": operator.UserID,
"update_user_name": operator.Username,
"updated_at": now,
}); err != nil {
return err
}
return LoginSessionService.RevokeByUser(userID, operator.UserID, operator.Username)
return users
}