fix(admin): 修复新增管理员无角色后不可见
This commit is contained in:
@@ -25,9 +25,10 @@ type PaginatedResult struct {
|
||||
}
|
||||
|
||||
type CreateAdminRequest struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Nickname string `json:"nickname"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Nickname string `json:"nickname"`
|
||||
RoleIDs []uint64 `json:"role_ids"`
|
||||
}
|
||||
|
||||
type UpdateAdminRequest struct {
|
||||
|
||||
@@ -175,6 +175,14 @@ func writeError(c *gin.Context, err error) {
|
||||
response.BadRequest(c, "原密码错误")
|
||||
case errors.Is(err, ErrWeakPassword):
|
||||
response.BadRequest(c, "密码至少 8 位且需包含字母和数字")
|
||||
case errors.Is(err, ErrUsernameRequired):
|
||||
response.BadRequest(c, "用户名不能为空")
|
||||
case errors.Is(err, ErrRolesRequired):
|
||||
response.BadRequest(c, "请至少选择一个角色")
|
||||
case errors.Is(err, ErrRoleOutsideTenant):
|
||||
response.BadRequest(c, "角色不属于当前站点")
|
||||
case errors.Is(err, ErrUsernameExists):
|
||||
response.Error(c, http.StatusConflict, "username_exists", "用户名已存在,请更换用户名")
|
||||
case IsNotFound(err):
|
||||
response.Error(c, http.StatusNotFound, "not_found", "管理员不存在")
|
||||
default:
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/auditlog"
|
||||
"hfb_sys/backend/internal/logging"
|
||||
@@ -74,6 +75,28 @@ func (r *Repository) FindByID(ctx context.Context, id uint64) (*AdminUserDTO, er
|
||||
}
|
||||
|
||||
func (r *Repository) Create(ctx context.Context, req CreateAdminRequest) (*AdminUserDTO, error) {
|
||||
req.Username = strings.TrimSpace(req.Username)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
roleIDs, err := r.validateTenantRoleIDs(ctx, req.RoleIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(roleIDs) == 0 {
|
||||
return nil, ErrRolesRequired
|
||||
}
|
||||
if req.Username == "" {
|
||||
return nil, ErrUsernameRequired
|
||||
}
|
||||
var existing int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.AdminUser{}).
|
||||
Where("username = ?", req.Username).
|
||||
Count(&existing).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existing > 0 {
|
||||
return nil, ErrUsernameExists
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -87,19 +110,29 @@ func (r *Repository) Create(ctx context.Context, req CreateAdminRequest) (*Admin
|
||||
TokenVersion: 1,
|
||||
PasswordMustChange: false,
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Create(&admin).Error; err != nil {
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(&admin).Error; err != nil {
|
||||
if isDuplicateAdminUsername(err) {
|
||||
return ErrUsernameExists
|
||||
}
|
||||
return err
|
||||
}
|
||||
for _, roleID := range roleIDs {
|
||||
assignment := model.AdminUserRole{
|
||||
AdminID: admin.ID,
|
||||
RoleID: roleID,
|
||||
TenantID: tenantID,
|
||||
}
|
||||
if err := tx.Create(&assignment).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &AdminUserDTO{
|
||||
ID: admin.ID,
|
||||
Username: admin.Username,
|
||||
Nickname: admin.Nickname,
|
||||
Status: admin.Status,
|
||||
Roles: []adminrole.RoleDTO{},
|
||||
LastLoginAt: admin.LastLoginAt,
|
||||
CreatedAt: admin.CreatedAt,
|
||||
UpdatedAt: admin.UpdatedAt,
|
||||
}, nil
|
||||
return r.FindByID(ctx, admin.ID)
|
||||
}
|
||||
|
||||
func (r *Repository) Update(ctx context.Context, id uint64, req UpdateAdminRequest) (*AdminUserDTO, error) {
|
||||
@@ -427,6 +460,17 @@ var (
|
||||
ErrRoleOutsideTenant = errors.New("role is not available in current tenant")
|
||||
)
|
||||
|
||||
func isDuplicateAdminUsername(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, gorm.ErrDuplicatedKey) {
|
||||
return true
|
||||
}
|
||||
text := strings.ToLower(err.Error())
|
||||
return strings.Contains(text, "1062") && strings.Contains(text, "uk_admin_users_username")
|
||||
}
|
||||
|
||||
func IsNotFound(err error) bool {
|
||||
return errors.Is(err, gorm.ErrRecordNotFound)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ import (
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("dependency unavailable")
|
||||
ErrWeakPassword = errors.New("weak password")
|
||||
ErrUsernameRequired = errors.New("username is required")
|
||||
ErrUsernameExists = errors.New("username already exists")
|
||||
ErrRolesRequired = errors.New("at least one role is required")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
|
||||
@@ -72,3 +72,62 @@ func TestAdminListIsScopedByTenantAndKeepsPlatformSuperAdmin(t *testing.T) {
|
||||
t.Fatalf("assign platform super role in tenant error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAdminWithTenantRoleRemainsVisible(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
role := model.Role{Code: "cs", Name: "客服"}
|
||||
if err := db.Create(&role).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
repo := NewRepository(db, nil)
|
||||
created, err := repo.Create(adminMgrTenantContext(202), CreateAdminRequest{
|
||||
Username: "jieyou-cs",
|
||||
Password: "password123",
|
||||
Nickname: "解忧客服",
|
||||
RoleIDs: []uint64{role.ID},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create tenant admin: %v", err)
|
||||
}
|
||||
if len(created.Roles) != 1 || created.Roles[0].Code != "cs" {
|
||||
t.Fatalf("created admin roles = %+v", created.Roles)
|
||||
}
|
||||
|
||||
result, err := repo.List(adminMgrTenantContext(202), 1, 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Total != 1 || result.Items[0].ID != created.ID {
|
||||
t.Fatalf("tenant admin list = %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAdminRequiresTenantRoleAndRejectsDuplicateUsername(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
role := model.Role{Code: "cs", Name: "客服"}
|
||||
if err := db.Create(&role).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db, nil)
|
||||
ctx := adminMgrTenantContext(202)
|
||||
|
||||
if _, err := repo.Create(ctx, CreateAdminRequest{
|
||||
Username: "jieyou-cs",
|
||||
Password: "password123",
|
||||
}); !errors.Is(err, ErrRolesRequired) {
|
||||
t.Fatalf("create without roles error = %v", err)
|
||||
}
|
||||
|
||||
req := CreateAdminRequest{
|
||||
Username: "jieyou-cs",
|
||||
Password: "password123",
|
||||
RoleIDs: []uint64{role.ID},
|
||||
}
|
||||
if _, err := repo.Create(ctx, req); err != nil {
|
||||
t.Fatalf("first create: %v", err)
|
||||
}
|
||||
if _, err := repo.Create(ctx, req); !errors.Is(err, ErrUsernameExists) {
|
||||
t.Fatalf("duplicate create error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user