Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(auth): add self-service change password in user profile

jiahao6635ec4bc8b9a4be
diff --git a/frontend/src/api/auth/index.ts b/frontend/src/api/auth/index.ts
index 44a5871a2..e8e0a2f19 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 ae5b8dcf4..b61efbb5f 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 73cc05033..e9634f70e 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 a2b1c18a1..5fa388ccc 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 4b887d866..e809cc88d 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 63d569aaa..ce41afa89 100644
--- a/frontend/src/views/settings/UserProfile.vue
+++ b/frontend/src/views/settings/UserProfile.vue
@@ -65,21 +65,124 @@
<span class="info-value">{{ formatDate(userInfo?.created_at) }}</span>
</div>
</div>
+
+ <!-- 修改密码 -->
+ <div class="setting-row password-row">
+ <div class="setting-info">
+ <label>{{ $t('userProfile.changePassword.label') }}</label>
+ <p class="desc">{{ $t('userProfile.changePassword.description') }}</p>
+ </div>
+ <div class="setting-control password-control">
+ <t-form
+ ref="passwordFormRef"
+ :data="passwordForm"
+ :rules="passwordRules"
+ label-align="top"
+ class="password-form"
+ @submit.prevent
+ >
+ <t-form-item :label="$t('userProfile.changePassword.currentLabel')" name="oldPassword">
+ <t-input
+ v-model="passwordForm.oldPassword"
+ type="password"
+ autocomplete="current-password"
+ :disabled="passwordSubmitting"
+ :placeholder="$t('userProfile.changePassword.currentPlaceholder')"
+ >
+ <template #prefix-icon><t-icon name="lock-on" /></template>
+ </t-input>
+ </t-form-item>
+ <t-form-item :label="$t('userProfile.changePassword.newLabel')" name="newPassword">
+ <t-input
+ v-model="passwordForm.newPassword"
+ type="password"
+ autocomplete="new-password"
+ :disabled="passwordSubmitting"
+ :placeholder="$t('userProfile.changePassword.newPlaceholder')"
+ >
+ <template #prefix-icon><t-icon name="lock-on" /></template>
+ </t-input>
+ </t-form-item>
+ <t-form-item :label="$t('userProfile.changePassword.confirmLabel')" name="confirmPassword">
+ <t-input
+ v-model="passwordForm.confirmPassword"
+ type="password"
+ autocomplete="new-password"
+ :disabled="passwordSubmitting"
+ :placeholder="$t('userProfile.changePassword.confirmPlaceholder')"
+ @enter="submitPasswordChange"
+ >
+ <template #prefix-icon><t-icon name="lock-on" /></template>
+ </t-input>
+ </t-form-item>
+ <div class="password-actions">
+ <t-button
+ theme="primary"
+ :loading="passwordSubmitting"
+ :disabled="passwordSubmitting"
+ @click="submitPasswordChange"
+ >
+ {{ $t('userProfile.changePassword.submit') }}
+ </t-button>
+ </div>
+ </t-form>
+ </div>
+ </div>
</div>
</div>
</template>
<script setup lang="ts">
-import { ref, onMounted } from 'vue'
-import { getCurrentUser, type UserInfo } from '@/api/auth'
+import { ref, reactive, computed, onMounted } from 'vue'
+import { useRouter } from 'vue-router'
+import { MessagePlugin } from 'tdesign-vue-next'
+import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next'
+import {
+ getCurrentUser,
+ changePassword,
+ logout as logoutApi,
+ type UserInfo,
+} from '@/api/auth'
+import { useAuthStore } from '@/stores/auth'
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
+const router = useRouter()
+const authStore = useAuthStore()
const userInfo = ref<UserInfo | null>(null)
const loading = ref(true)
const error = ref('')
+const passwordFormRef = ref<FormInstanceFunctions | null>(null)
+const passwordSubmitting = ref(false)
+const passwordForm = reactive({
+ oldPassword: '',
+ newPassword: '',
+ confirmPassword: '',
+})
+
+const passwordRules = computed<Record<string, FormRule[]>>(() => ({
+ oldPassword: [
+ { required: true, message: t('userProfile.changePassword.currentRequired'), type: 'error' },
+ ],
+ newPassword: [
+ { required: true, message: t('auth.passwordRequired'), type: 'error' },
+ { min: 8, message: t('auth.passwordMinLength'), type: 'error' },
+ { max: 32, message: t('auth.passwordMaxLength'), type: 'error' },
+ { pattern: /[a-zA-Z]/, message: t('auth.passwordMustContainLetter'), type: 'error' },
+ { pattern: /\d/, message: t('auth.passwordMustContainNumber'), type: 'error' },
+ ],
+ confirmPassword: [
+ { required: true, message: t('auth.confirmPasswordRequired'), type: 'error' },
+ {
+ validator: (val: string) => val === passwordForm.newPassword,
+ message: t('auth.passwordMismatch'),
+ type: 'error',
+ },
+ ],
+}))
+
const loadInfo = async () => {
try {
loading.value = true
@@ -114,6 +217,48 @@ const formatDate = (dateStr: string | undefined) => {
}
}
+const resetPasswordForm = () => {
+ passwordForm.oldPassword = ''
+ passwordForm.newPassword = ''
+ passwordForm.confirmPassword = ''
+ passwordFormRef.value?.clearValidate?.()
+}
+
+const submitPasswordChange = async () => {
+ if (passwordSubmitting.value) return
+ const result = await passwordFormRef.value?.validate?.()
+ if (result !== true) return
+
+ passwordSubmitting.value = true
+ try {
+ const resp = await changePassword({
+ old_password: passwordForm.oldPassword,
+ new_password: passwordForm.newPassword,
+ })
+ if (!resp.success) {
+ MessagePlugin.error(resp.message || t('userProfile.changePassword.failed'))
+ return
+ }
+
+ MessagePlugin.success(t('userProfile.changePassword.success'))
+ resetPasswordForm()
+
+ // Backend revokes all sessions on success; mirror that locally and
+ // force a fresh login with the new credential.
+ try {
+ await logoutApi()
+ } catch {
+ /* ignore — local cleanup still proceeds */
+ }
+ authStore.logout()
+ router.push('/login')
+ } catch (err: any) {
+ MessagePlugin.error(err?.message || t('userProfile.changePassword.failed'))
+ } finally {
+ passwordSubmitting.value = false
+ }
+}
+
onMounted(loadInfo)
</script>
@@ -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;
+}
</style>
diff --git a/internal/application/service/user.go b/internal/application/service/user.go
index d7fb38ed4..4882c47ca 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 87d98e3ce..bfffca85d 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 ed2c112ba..8548aa52a 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)