diff --git a/frontend/src/api/auth/index.ts b/frontend/src/api/auth/index.ts
index 44a5871a..e8e0a2f1 100644
--- a/frontend/src/api/auth/index.ts
+++ b/frontend/src/api/auth/index.ts
@@ -414,6 +414,30 @@ export async function logout(): Promise<{ success: boolean; message?: string }>
}
}
+export interface ChangePasswordRequest {
+ old_password: string
+ new_password: string
+}
+
+/**
+ * Self-service password rotation. On success the backend revokes every
+ * outstanding session for the caller, so the client should clear local
+ * auth state and send the user back to /login.
+ */
+export async function changePassword(
+ data: ChangePasswordRequest,
+): Promise<{ success: boolean; message?: string }> {
+ try {
+ const response = await post('/api/v1/auth/change-password', data)
+ return response as unknown as { success: boolean; message?: string }
+ } catch (error: any) {
+ return {
+ success: false,
+ message: error.message || t('userProfile.changePassword.failed'),
+ }
+ }
+}
+
/**
* 验证Token有效性
*/
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index ae5b8dcf..b61efbb5 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -5674,7 +5674,21 @@ export default {
},
userProfile: {
title: 'User Profile',
- description: 'View your account info (user ID, username, email, registration time).'
+ description: 'View your account info (user ID, username, email, registration time) and change your password.',
+ changePassword: {
+ label: 'Change password',
+ description: 'Verify your current password, then set a new one. All signed-in sessions will be revoked and you will need to sign in again.',
+ currentLabel: 'Current password',
+ currentPlaceholder: 'Enter your current password',
+ currentRequired: 'Enter your current password',
+ newLabel: 'New password',
+ newPlaceholder: '8-32 characters, include letters and numbers',
+ confirmLabel: 'Confirm new password',
+ confirmPlaceholder: 'Enter the new password again',
+ submit: 'Update password',
+ success: 'Password updated. Please sign in with your new password.',
+ failed: 'Failed to change password. Check that your current password is correct.',
+ },
},
tenantMember: {
title: 'Members',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 73cc0503..e9634f70 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -226,7 +226,21 @@ export default {
},
userProfile: {
title: '사용자 정보',
- description: '계정 기본 정보(사용자 ID, 사용자 이름, 이메일, 가입 시각)를 확인합니다.'
+ description: '계정 기본 정보(사용자 ID, 사용자 이름, 이메일, 가입 시각)를 확인하고 비밀번호를 변경할 수 있습니다.',
+ changePassword: {
+ label: '비밀번호 변경',
+ description: '현재 비밀번호를 확인한 뒤 새 비밀번호를 설정합니다. 성공 시 모든 세션이 만료되어 다시 로그인해야 합니다.',
+ currentLabel: '현재 비밀번호',
+ currentPlaceholder: '현재 비밀번호를 입력하세요',
+ currentRequired: '현재 비밀번호를 입력하세요',
+ newLabel: '새 비밀번호',
+ newPlaceholder: '8-32자, 문자와 숫자 포함',
+ confirmLabel: '새 비밀번호 확인',
+ confirmPlaceholder: '새 비밀번호를 다시 입력하세요',
+ submit: '비밀번호 업데이트',
+ success: '비밀번호가 변경되었습니다. 새 비밀번호로 다시 로그인해 주세요.',
+ failed: '비밀번호 변경에 실패했습니다. 현재 비밀번호를 확인해 주세요.',
+ },
},
credential: {
configured: '구성됨',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index a2b1c18a..5fa388cc 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -226,7 +226,21 @@ export default {
},
userProfile: {
title: 'Информация о пользователе',
- description: 'Просмотр базовых данных аккаунта (ID пользователя, имя, email, дата регистрации).'
+ description: 'Просмотр базовых данных аккаунта (ID пользователя, имя, email, дата регистрации) и смена пароля.',
+ changePassword: {
+ label: 'Сменить пароль',
+ description: 'Подтвердите текущий пароль и задайте новый. После успешной смены все сессии будут отозваны, потребуется повторный вход.',
+ currentLabel: 'Текущий пароль',
+ currentPlaceholder: 'Введите текущий пароль',
+ currentRequired: 'Введите текущий пароль',
+ newLabel: 'Новый пароль',
+ newPlaceholder: '8–32 символа, буквы и цифры',
+ confirmLabel: 'Подтвердите новый пароль',
+ confirmPlaceholder: 'Введите новый пароль ещё раз',
+ submit: 'Обновить пароль',
+ success: 'Пароль обновлён. Войдите снова с новым паролем.',
+ failed: 'Не удалось сменить пароль. Проверьте текущий пароль.',
+ },
},
credential: {
configured: 'Настроено',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 4b887d86..e809cc88 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -226,7 +226,21 @@ export default {
},
userProfile: {
title: '用户信息',
- description: '查看您的账户基础信息(用户 ID、用户名、邮箱、注册时间)'
+ description: '查看您的账户基础信息(用户 ID、用户名、邮箱、注册时间),并可修改登录密码',
+ changePassword: {
+ label: '修改密码',
+ description: '使用当前密码验证后设置新密码。修改成功后所有设备上的登录状态将失效,需要重新登录。',
+ currentLabel: '当前密码',
+ currentPlaceholder: '请输入当前密码',
+ currentRequired: '请输入当前密码',
+ newLabel: '新密码',
+ newPlaceholder: '8-32 个字符,需包含字母和数字',
+ confirmLabel: '确认新密码',
+ confirmPlaceholder: '再次输入新密码',
+ submit: '更新密码',
+ success: '密码已更新,请使用新密码重新登录',
+ failed: '修改密码失败,请检查当前密码是否正确',
+ },
},
credential: {
configured: '已配置',
diff --git a/frontend/src/views/settings/UserProfile.vue b/frontend/src/views/settings/UserProfile.vue
index 63d569aa..ce41afa8 100644
--- a/frontend/src/views/settings/UserProfile.vue
+++ b/frontend/src/views/settings/UserProfile.vue
@@ -65,21 +65,124 @@
{{ formatDate(userInfo?.created_at) }}
+
+
+
+
+
+
{{ $t('userProfile.changePassword.description') }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ $t('userProfile.changePassword.submit') }}
+
+
+
+
+
@@ -207,4 +352,29 @@ onMounted(loadInfo)
word-break: break-word;
}
}
+
+.password-row {
+ align-items: flex-start;
+}
+
+.password-control {
+ min-width: 320px;
+ max-width: 360px;
+ flex-direction: column;
+ align-items: stretch;
+}
+
+.password-form {
+ width: 100%;
+
+ :deep(.t-form__item) {
+ margin-bottom: 16px;
+ }
+}
+
+.password-actions {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 4px;
+}
diff --git a/internal/application/service/user.go b/internal/application/service/user.go
index d7fb38ed..4882c47c 100644
--- a/internal/application/service/user.go
+++ b/internal/application/service/user.go
@@ -37,6 +37,11 @@ var (
// It is exported so HTTP handlers can translate the failure to a 400
// without exposing bcrypt or persistence errors.
ErrPasswordPolicy = errors.New("password must be 8-32 characters and contain at least one letter and one number")
+
+ // ErrInvalidOldPassword is returned by ChangePassword when the supplied
+ // current password does not match the stored hash. Handlers map this to
+ // a 400 so callers can prompt the user without treating it as a 500.
+ ErrInvalidOldPassword = errors.New("invalid old password")
)
// ValidatePasswordPolicy keeps administrative password resets aligned with
@@ -632,17 +637,24 @@ func (s *userService) DeleteUser(ctx context.Context, id string) error {
return s.userRepo.DeleteUser(ctx, id)
}
-// ChangePassword changes user password
+// ChangePassword changes user password after verifying the current
+// credential. The new password must satisfy ValidatePasswordPolicy so
+// self-service rotation cannot introduce weaker passwords than
+// registration / admin reset allow. On success every outstanding session
+// is revoked so a stolen token cannot survive the rotation.
func (s *userService) ChangePassword(ctx context.Context, userID string, oldPassword, newPassword string) error {
+ if err := ValidatePasswordPolicy(newPassword); err != nil {
+ return err
+ }
+
user, err := s.userRepo.GetUserByID(ctx, userID)
if err != nil {
return err
}
// Verify old password
- err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(oldPassword))
- if err != nil {
- return errors.New("invalid old password")
+ if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(oldPassword)); err != nil {
+ return ErrInvalidOldPassword
}
// Hash new password
diff --git a/internal/application/service/user_auth_token_test.go b/internal/application/service/user_auth_token_test.go
index 87d98e3c..bfffca85 100644
--- a/internal/application/service/user_auth_token_test.go
+++ b/internal/application/service/user_auth_token_test.go
@@ -220,6 +220,40 @@ func TestAdminResetPasswordRejectsWeakPasswordBeforeWrite(t *testing.T) {
}
}
+func TestChangePasswordRequiresPolicyAndRevokesSessions(t *testing.T) {
+ ctx := context.Background()
+ tokenRepo := &stubAuthTokenRepo{tokens: map[string]*types.AuthToken{}}
+ svc := newAuthTestUserService(tokenRepo)
+ repo := svc.userRepo.(*stubUserRepoForAuth)
+
+ hashed, err := bcrypt.GenerateFromPassword([]byte("OldSecure9"), bcrypt.DefaultCost)
+ if err != nil {
+ t.Fatalf("hash old password: %v", err)
+ }
+ repo.users["user-1"].PasswordHash = string(hashed)
+
+ if err := svc.ChangePassword(ctx, "user-1", "OldSecure9", "weak"); !errors.Is(err, ErrPasswordPolicy) {
+ t.Fatalf("ChangePassword(weak) err = %v, want ErrPasswordPolicy", err)
+ }
+ if repo.updateCalls != 0 || len(tokenRepo.revokedUserIDs) != 0 {
+ t.Fatalf("weak password caused side effects: updates=%d revocations=%v", repo.updateCalls, tokenRepo.revokedUserIDs)
+ }
+
+ if err := svc.ChangePassword(ctx, "user-1", "wrong-pass", "NewSecure9"); !errors.Is(err, ErrInvalidOldPassword) {
+ t.Fatalf("ChangePassword(wrong old) err = %v, want ErrInvalidOldPassword", err)
+ }
+
+ if err := svc.ChangePassword(ctx, "user-1", "OldSecure9", "NewSecure9"); err != nil {
+ t.Fatalf("ChangePassword() err = %v", err)
+ }
+ if err := bcrypt.CompareHashAndPassword([]byte(repo.users["user-1"].PasswordHash), []byte("NewSecure9")); err != nil {
+ t.Fatalf("stored hash does not match new password: %v", err)
+ }
+ if len(tokenRepo.revokedUserIDs) != 1 || tokenRepo.revokedUserIDs[0] != "user-1" {
+ t.Fatalf("revoked users = %v, want [user-1]", tokenRepo.revokedUserIDs)
+ }
+}
+
func TestUserIDFromSignedTokenAcceptsExpiredToken(t *testing.T) {
expired := signTestJWT(jwt.MapClaims{
"user_id": "user-1",
diff --git a/internal/handler/auth.go b/internal/handler/auth.go
index ed2c112b..8548aa52 100644
--- a/internal/handler/auth.go
+++ b/internal/handler/auth.go
@@ -5,12 +5,14 @@ import (
"crypto/rand"
"encoding/base64"
"encoding/json"
+ stderrors "errors"
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
+ "github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/handler/dto"
@@ -645,7 +647,7 @@ func (h *AuthHandler) UpdateMyPreferences(c *gin.Context) {
// ChangePassword godoc
// @Summary 修改密码
-// @Description 修改当前用户的登录密码
+// @Description 修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;成功后所有会话被撤销,需重新登录。
// @Tags 认证
// @Accept json
// @Produce json
@@ -661,7 +663,7 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {
var req struct {
OldPassword string `json:"old_password" binding:"required"`
- NewPassword string `json:"new_password" binding:"required,min=6"`
+ NewPassword string `json:"new_password" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
@@ -683,10 +685,21 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {
// Change password
err = h.userService.ChangePassword(ctx, user.ID, req.OldPassword, req.NewPassword)
if err != nil {
- logger.Errorf(ctx, "Failed to change password: %v", err)
- appErr := errors.NewBadRequestError("Password change failed").WithDetails(err.Error())
- c.Error(appErr)
- return
+ switch {
+ case stderrors.Is(err, service.ErrPasswordPolicy):
+ appErr := errors.NewValidationError(err.Error())
+ c.Error(appErr)
+ return
+ case stderrors.Is(err, service.ErrInvalidOldPassword):
+ appErr := errors.NewBadRequestError("Current password is incorrect")
+ c.Error(appErr)
+ return
+ default:
+ logger.Errorf(ctx, "Failed to change password: %v", err)
+ appErr := errors.NewBadRequestError("Password change failed").WithDetails(err.Error())
+ c.Error(appErr)
+ return
+ }
}
logger.Infof(ctx, "Password changed successfully for user: %s", user.Email)