添加默认系统管理员账号并限制唯一
This commit is contained in:
@@ -161,6 +161,10 @@ func (h *AdminHandler) UpdateUser(c *gin.Context) {
|
||||
}
|
||||
|
||||
if req.Status != "" {
|
||||
if target.Role.NameEnum() == models.RoleSystemAdmin && req.Status != "active" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"success": false, "error": "不能禁用系统管理员账号"})
|
||||
return
|
||||
}
|
||||
updates["status"] = req.Status
|
||||
}
|
||||
|
||||
@@ -170,6 +174,10 @@ func (h *AdminHandler) UpdateUser(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "无效的角色"})
|
||||
return
|
||||
}
|
||||
if target.Role.NameEnum() == models.RoleSystemAdmin && newRole != models.RoleSystemAdmin {
|
||||
c.JSON(http.StatusForbidden, gin.H{"success": false, "error": "不能修改系统管理员账号的角色"})
|
||||
return
|
||||
}
|
||||
if !containsRole(allowedRolesForCreation(current.Role), newRole) || !current.Role.CanManage(newRole) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"success": false, "error": "权限不足"})
|
||||
return
|
||||
@@ -211,6 +219,11 @@ func (h *AdminHandler) DeleteUser(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if target.Role.NameEnum() == models.RoleSystemAdmin {
|
||||
c.JSON(http.StatusForbidden, gin.H{"success": false, "error": "不能删除系统管理员账号"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.DB.Delete(&target).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "internal server error"})
|
||||
return
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -118,6 +119,33 @@ func SeedRoles(db *gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SeedSystemAdmin 在没有 system_admin 用户时创建默认系统管理员账号。
|
||||
func SeedSystemAdmin(db *gorm.DB) error {
|
||||
var existing User
|
||||
if err := db.Where("username = ?", "system_admin").First(&existing).Error; err == nil {
|
||||
return nil
|
||||
} else if err != gorm.ErrRecordNotFound {
|
||||
return err
|
||||
}
|
||||
|
||||
var role Role
|
||||
if err := db.Where("name = ?", RoleSystemAdmin).First(&role).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("system_admin"), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return db.Create(&User{
|
||||
Username: "system_admin",
|
||||
PasswordHash: string(hash),
|
||||
RoleID: role.ID,
|
||||
Status: "active",
|
||||
}).Error
|
||||
}
|
||||
|
||||
func strPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user