feat(server): 新增 passwd 子命令,可重置用户密码并作废会话
This commit is contained in:
1 parent
e47251658b
commit
ad2322d558
3 files changed
+98
No files matched your search
@@ -169,6 +169,39 @@ func (s *Service) EnsureDefaultAdmin(ctx context.Context) (username, password st
|
||||
return username, password, true, nil
|
||||
}
|
||||
|
||||
// RandomPassword 生成 n 位随机密码,供首次初始化和 CLI 重置使用。
|
||||
func RandomPassword(n int) (string, error) { return randomPassword(n) }
|
||||
|
||||
// SetPassword 重置用户密码并作废其全部会话;mustChange 表示下次登录后强制改密。
|
||||
func (s *Service) SetPassword(ctx context.Context, username, password string, mustChange bool) error {
|
||||
if password == "" {
|
||||
return fmt.Errorf("密码不能为空")
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), s.bcryptCost)
|
||||
if err != nil {
|
||||
return fmt.Errorf("生成密码哈希: %w", err)
|
||||
}
|
||||
must := 0
|
||||
if mustChange {
|
||||
must = 1
|
||||
}
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`UPDATE users SET password_hash = ?, must_change_password = ?, updated_at = datetime('now') WHERE username = ?`,
|
||||
string(hash), must, username)
|
||||
if err != nil {
|
||||
return fmt.Errorf("更新密码: %w", err)
|
||||
}
|
||||
if n, err := res.RowsAffected(); err == nil && n == 0 {
|
||||
return fmt.Errorf("用户 %s 不存在", username)
|
||||
}
|
||||
|
||||
var id int64
|
||||
if err := s.db.QueryRowContext(ctx, `SELECT id FROM users WHERE username = ?`, username).Scan(&id); err != nil {
|
||||
return fmt.Errorf("查询用户: %w", err)
|
||||
}
|
||||
return s.RevokeUserSessions(ctx, id)
|
||||
}
|
||||
|
||||
// Authenticate 校验用户名密码并创建会话,返回用户与不落库的明文 token。
|
||||
func (s *Service) Authenticate(ctx context.Context, username, password, ip, userAgent string) (*User, string, error) {
|
||||
if !s.AllowLogin(ip) {
|
||||
|
||||
Reference in new issue
Block a user