feat: 支持管理员自助修改密码 (#57)
This commit is contained in:
+36
-4
@@ -32,7 +32,10 @@ var (
|
||||
dummyPasswordHash, _ = bcrypt.GenerateFromPassword([]byte("not-a-real-password"), bcrypt.DefaultCost)
|
||||
)
|
||||
|
||||
type validationError struct{ message string }
|
||||
type validationError struct {
|
||||
field string
|
||||
message string
|
||||
}
|
||||
|
||||
func (e *validationError) Error() string { return e.message }
|
||||
|
||||
@@ -42,10 +45,23 @@ func IsValidationError(err error) bool {
|
||||
return errors.As(err, &target)
|
||||
}
|
||||
|
||||
// ValidationField 返回表单错误对应的字段名,供页面把焦点放到需要修正的位置。
|
||||
func ValidationField(err error) string {
|
||||
var target *validationError
|
||||
if errors.As(err, &target) {
|
||||
return target.field
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func invalidInput(message string, args ...any) error {
|
||||
return &validationError{message: fmt.Sprintf(message, args...)}
|
||||
}
|
||||
|
||||
func invalidFieldInput(field, message string, args ...any) error {
|
||||
return &validationError{field: field, message: fmt.Sprintf(message, args...)}
|
||||
}
|
||||
|
||||
// HasUsers 判断首次初始化入口是否已经永久关闭。
|
||||
func HasUsers(db *sql.DB) (bool, error) {
|
||||
count, err := repository.CountUsers(db)
|
||||
@@ -86,15 +102,15 @@ func validateUsername(username string) error {
|
||||
|
||||
func hashConfirmedPassword(password, confirmation string) ([]byte, error) {
|
||||
if len([]rune(password)) < minimumPasswordLen {
|
||||
return nil, invalidInput("密码至少需要 %d 个字符", minimumPasswordLen)
|
||||
return nil, invalidFieldInput("new_password", "密码至少需要 %d 个字符", minimumPasswordLen)
|
||||
}
|
||||
// bcrypt 最多接受 72 字节。中文等字符可能占多个字节,因此不能只靠
|
||||
// HTML 的 maxlength;服务端需要在哈希前给出可理解的校验错误。
|
||||
if len([]byte(password)) > 72 {
|
||||
return nil, invalidInput("密码不能超过 72 个字节")
|
||||
return nil, invalidFieldInput("new_password", "密码不能超过 72 个字节")
|
||||
}
|
||||
if password != confirmation {
|
||||
return nil, invalidInput("两次输入的密码不一致")
|
||||
return nil, invalidFieldInput("password_confirm", "两次输入的密码不一致")
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
@@ -103,6 +119,22 @@ func hashConfirmedPassword(password, confirmation string) ([]byte, error) {
|
||||
return hash, nil
|
||||
}
|
||||
|
||||
// ChangeAdminPassword 校验当前管理员密码,更新新密码并撤销该账号全部 Session。
|
||||
func ChangeAdminPassword(db *sql.DB, actor *model.User, currentPassword, newPassword, confirmation string, now time.Time) error {
|
||||
if actor == nil || !actor.IsAdmin() {
|
||||
return ErrAdminRequired
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(actor.PasswordHash), []byte(currentPassword)) != nil {
|
||||
return invalidFieldInput("current_password", "当前密码错误,请重新输入")
|
||||
}
|
||||
hash, err := hashConfirmedPassword(newPassword, confirmation)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return repository.ChangePasswordAndRevokeSessions(
|
||||
db, actor.UserID, actor.PasswordHash, string(hash), now.UTC().Format(model.TimeLayout))
|
||||
}
|
||||
|
||||
// Login 校验统一凭据并创建一个固定 12 小时有效的 Session。
|
||||
// 返回的 token 原文只交给 Cookie,数据库仅保存 SHA-256。
|
||||
func Login(db *sql.DB, username, password string, now time.Time) (token string, user *model.User, expiresAt time.Time, err error) {
|
||||
|
||||
@@ -169,3 +169,71 @@ func TestAuthenticate_过期Session被删除(t *testing.T) {
|
||||
t.Fatalf("过期 Session 应被清理,实际剩 %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeAdminPassword_校验当前密码并撤销全部Session(t *testing.T) {
|
||||
db := newSyncTestDB(t)
|
||||
now := time.Date(2026, 8, 9, 8, 0, 0, 0, time.UTC)
|
||||
if err := SetupInitialAdmin(db, "admin", "old-password", "old-password", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tokenA, actor, _, err := Login(db, "admin", "old-password", now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tokenB, _, _, err := Login(db, "admin", "old-password", now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = ChangeAdminPassword(db, actor, "wrong-password", "new-password", "new-password", now.Add(time.Minute))
|
||||
if err == nil || ValidationField(err) != "current_password" || !strings.Contains(err.Error(), "当前密码错误") {
|
||||
t.Fatalf("错误当前密码应定位到 current_password,实际 %v", err)
|
||||
}
|
||||
if _, err := Authenticate(db, tokenA, now.Add(2*time.Minute)); err != nil {
|
||||
t.Fatalf("失败改密不应撤销原 Session: %v", err)
|
||||
}
|
||||
|
||||
if err := ChangeAdminPassword(db, actor, "old-password", "new-password", "new-password", now.Add(3*time.Minute)); err != nil {
|
||||
t.Fatalf("修改管理员密码失败: %v", err)
|
||||
}
|
||||
for _, token := range []string{tokenA, tokenB} {
|
||||
if _, err := Authenticate(db, token, now.Add(4*time.Minute)); !errors.Is(err, ErrUnauthenticated) {
|
||||
t.Fatalf("改密后全部旧 Session 都应失效,实际 %v", err)
|
||||
}
|
||||
}
|
||||
if _, _, _, err := Login(db, "admin", "old-password", now.Add(5*time.Minute)); !errors.Is(err, ErrInvalidCredentials) {
|
||||
t.Fatalf("改密后旧密码不应登录,实际 %v", err)
|
||||
}
|
||||
if _, _, _, err := Login(db, "admin", "new-password", now.Add(5*time.Minute)); err != nil {
|
||||
t.Fatalf("改密后新密码应可登录: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeAdminPassword_新密码字段校验与权限(t *testing.T) {
|
||||
db := newSyncTestDB(t)
|
||||
now := time.Now()
|
||||
if err := SetupInitialAdmin(db, "admin", "old-password", "old-password", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
admin, _ := repository.FindUserByUsername(db, "admin")
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
password string
|
||||
confirmation string
|
||||
field string
|
||||
}{
|
||||
{"少于六个字符", "12345", "12345", "new_password"},
|
||||
{"超过七十二字节", strings.Repeat("密", 25), strings.Repeat("密", 25), "new_password"},
|
||||
{"确认不一致", "123456", "654321", "password_confirm"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := ChangeAdminPassword(db, admin, "old-password", test.password, test.confirmation, now)
|
||||
if err == nil || ValidationField(err) != test.field {
|
||||
t.Fatalf("校验错误 = %v,期望字段 %s", err, test.field)
|
||||
}
|
||||
})
|
||||
}
|
||||
if err := ChangeAdminPassword(db, nil, "old-password", "123456", "123456", now); !errors.Is(err, ErrAdminRequired) {
|
||||
t.Fatalf("非管理员应被拒绝,实际 %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user