修复:管理员默认商户与账户设置

This commit is contained in:
yml2213
2026-08-13 14:12:25 +08:00
parent 6dae7fafa8
commit 538be52636
7 changed files with 181 additions and 23 deletions
+68
View File
@@ -26,6 +26,13 @@ type LoginResult struct {
User *model.User `json:"user"`
}
type UpdateCurrentAccountInput struct {
CurrentPassword string
Username string
Nickname string
NewPassword string
}
func (s *AuthService) Login(username, password string) (*LoginResult, error) {
var user model.User
if err := s.db.Where("username = ?", username).First(&user).Error; err != nil {
@@ -86,6 +93,67 @@ func (s *AuthService) ChangePassword(userID uint, currentPassword, newPassword s
return s.db.Model(&user).Update("password_hash", string(hash)).Error
}
// UpdateCurrentAccount lets a user maintain their own login identity. The
// current password is always required before username, nickname, or password
// changes are accepted.
func (s *AuthService) UpdateCurrentAccount(userID uint, in UpdateCurrentAccountInput) (*model.User, error) {
if userID == 0 {
return nil, errors.New("无效的用户身份")
}
in.Username = strings.TrimSpace(in.Username)
if len(in.Username) < 3 || len(in.Username) > 64 {
return nil, errors.New("用户名长度需为 3 至 64 位")
}
if len(in.Nickname) > 64 {
return nil, errors.New("昵称不能超过 64 位")
}
if in.NewPassword != "" && len(in.NewPassword) < 8 {
return nil, errors.New("新密码至少 8 位")
}
updated := &model.User{}
err := s.db.Transaction(func(tx *gorm.DB) error {
var user model.User
if err := tx.First(&user, userID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.New("用户不存在")
}
return err
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(in.CurrentPassword)); err != nil {
return errors.New("当前密码错误")
}
if in.Username != user.Username {
var count int64
if err := tx.Model(&model.User{}).Where("username = ? AND id <> ?", in.Username, user.ID).Count(&count).Error; err != nil {
return err
}
if count > 0 {
return errors.New("用户名已存在")
}
}
updates := map[string]interface{}{"username": in.Username, "nickname": in.Nickname}
if in.NewPassword != "" {
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(in.NewPassword)); err == nil {
return errors.New("新密码不能与当前密码相同")
}
hash, err := bcrypt.GenerateFromPassword([]byte(in.NewPassword), bcrypt.DefaultCost)
if err != nil {
return err
}
updates["password_hash"] = string(hash)
}
if err := tx.Model(&user).Updates(updates).Error; err != nil {
return err
}
return tx.First(updated, user.ID).Error
})
if err != nil {
return nil, err
}
return updated, nil
}
// EnsureAdmin creates the first platform administrator for an empty database.
// Existing administrator accounts are never changed by environment variables.
func (s *AuthService) EnsureAdmin(username, password string) error {