fix(auth): harden self-service change password after #2591
Address post-merge review: verify old password before policy checks, reject same-password rotations, mark OIDC-provisioned users in preferences and hide the self-service form with guidance, map API error details to i18n, sync docs/api, Swagger, and the Go client SDK.main
parent
ec4bc8b9a4
commit
5494e669bc
|
|
@ -163,3 +163,30 @@ func (c *Client) RefreshToken(ctx context.Context, refreshToken string) (*Refres
|
|||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// ChangePasswordRequest is the body for POST /api/v1/auth/change-password.
|
||||
type ChangePasswordRequest struct {
|
||||
OldPassword string `json:"old_password"`
|
||||
NewPassword string `json:"new_password"`
|
||||
}
|
||||
|
||||
// ChangePasswordResponse is returned on successful password rotation.
|
||||
type ChangePasswordResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// ChangePassword rotates the caller's password. On success every outstanding
|
||||
// session is revoked server-side; callers should discard local tokens.
|
||||
// Maps to POST /api/v1/auth/change-password.
|
||||
func (c *Client) ChangePassword(ctx context.Context, req ChangePasswordRequest) (*ChangePasswordResponse, error) {
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/auth/change-password", req, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("change password: %w", err)
|
||||
}
|
||||
var out ChangePasswordResponse
|
||||
if err := parseResponse(resp, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -293,12 +293,14 @@ curl --location 'http://localhost:8080/api/v1/auth/me' \
|
|||
|
||||
## POST `/auth/change-password` - 修改密码
|
||||
|
||||
修改当前用户的登录密码。新密码须满足 **8–32 位**且**同时包含字母与数字**;不能与当前密码相同。成功后**所有会话被撤销**,需使用新密码重新登录。
|
||||
|
||||
**参数说明(请求体)**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 校验 | 说明 |
|
||||
| ------------- | ------ | ---- | ------- | --------- |
|
||||
| old_password | string | 是 | | 旧密码 |
|
||||
| new_password | string | 是 | 最少 6 位 | 新密码 |
|
||||
| old_password | string | 是 | | 当前密码 |
|
||||
| new_password | string | 是 | 8–32 位,须含字母与数字,且不同于旧密码 | 新密码 |
|
||||
|
||||
**请求**:
|
||||
|
||||
|
|
@ -314,4 +316,10 @@ curl --location 'http://localhost:8080/api/v1/auth/change-password' \
|
|||
|
||||
**响应**: `{ "success": true, "message": "Password changed successfully" }`
|
||||
|
||||
**错误**: 旧密码不匹配或新密码不满足校验 → 400。
|
||||
**错误**(400):
|
||||
|
||||
| `error.details` | 含义 |
|
||||
| --------------------- | ---------------------------- |
|
||||
| `invalid_old_password` | 当前密码不正确 |
|
||||
| `password_policy` | 新密码不满足长度/复杂度要求 |
|
||||
| `same_password` | 新密码与当前密码相同 |
|
||||
|
|
|
|||
|
|
@ -825,7 +825,7 @@ const docTemplate = `{
|
|||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "修改当前用户的登录密码",
|
||||
"description": "修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;成功后所有会话被撤销,需重新登录。",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
|
|
@ -19814,6 +19814,10 @@ const docTemplate = `{
|
|||
"last_active_tenant_id": {
|
||||
"description": "LastActiveTenantID remembers the last workspace the user actively\nswitched into, so a fresh login (new device, cleared browser, new\nrefresh token) lands them back in that workspace instead of always\nbouncing to their home workspace. Login / RefreshToken validate that\nthe workspace still exists and the user still has an active membership\n(or CanAccessAllTenants) before honouring this preference; an\ninvalid pointer is best-effort cleared and the user falls back to\nhome.\n\nnil = no preference (use user.TenantID, i.e. home)\n*0 = \"clear preference\" sentinel for the partial-update endpoint\n (UpdateUserPreferences turns this into nil). Otherwise treat\n a stored *0 the same as nil.\n*N = preferred workspace id.",
|
||||
"type": "integer"
|
||||
},
|
||||
"oidc_only_login": {
|
||||
"description": "OidcOnlyLogin is set server-side when an account is auto-provisioned\nvia OIDC with a random password the user never received. The profile\nUI hides self-service password rotation until the user sets a known\npassword via ChangePassword (which clears this flag).",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -818,7 +818,7 @@
|
|||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "修改当前用户的登录密码",
|
||||
"description": "修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;成功后所有会话被撤销,需重新登录。",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
|
|
@ -19807,6 +19807,10 @@
|
|||
"last_active_tenant_id": {
|
||||
"description": "LastActiveTenantID remembers the last workspace the user actively\nswitched into, so a fresh login (new device, cleared browser, new\nrefresh token) lands them back in that workspace instead of always\nbouncing to their home workspace. Login / RefreshToken validate that\nthe workspace still exists and the user still has an active membership\n(or CanAccessAllTenants) before honouring this preference; an\ninvalid pointer is best-effort cleared and the user falls back to\nhome.\n\nnil = no preference (use user.TenantID, i.e. home)\n*0 = \"clear preference\" sentinel for the partial-update endpoint\n (UpdateUserPreferences turns this into nil). Otherwise treat\n a stored *0 the same as nil.\n*N = preferred workspace id.",
|
||||
"type": "integer"
|
||||
},
|
||||
"oidc_only_login": {
|
||||
"description": "OidcOnlyLogin is set server-side when an account is auto-provisioned\nvia OIDC with a random password the user never received. The profile\nUI hides self-service password rotation until the user sets a known\npassword via ChangePassword (which clears this flag).",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -3820,6 +3820,13 @@ definitions:
|
|||
a stored *0 the same as nil.
|
||||
*N = preferred workspace id.
|
||||
type: integer
|
||||
oidc_only_login:
|
||||
description: |-
|
||||
OidcOnlyLogin is set server-side when an account is auto-provisioned
|
||||
via OIDC with a random password the user never received. The profile
|
||||
UI hides self-service password rotation until the user sets a known
|
||||
password via ChangePassword (which clears this flag).
|
||||
type: boolean
|
||||
type: object
|
||||
github_com_Tencent_WeKnora_internal_types.VLMConfig:
|
||||
properties:
|
||||
|
|
@ -6371,7 +6378,7 @@ paths:
|
|||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: 修改当前用户的登录密码
|
||||
description: 修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;成功后所有会话被撤销,需重新登录。
|
||||
parameters:
|
||||
- description: 密码修改请求
|
||||
in: body
|
||||
|
|
|
|||
|
|
@ -99,6 +99,8 @@ export interface UserPreferences {
|
|||
// 偏好;后端在 Login / RefreshToken 时校验 membership 有效后才会沿用,
|
||||
// 否则回退到 home 并清掉这个字段。传 0 给 PATCH 表示「清除偏好」。
|
||||
last_active_tenant_id?: number | null
|
||||
// oidc_only_login 为 true 表示账号由 OIDC 自动开通且用户尚未设置已知密码。
|
||||
oidc_only_login?: boolean
|
||||
}
|
||||
|
||||
// 用户信息接口
|
||||
|
|
@ -419,6 +421,26 @@ export interface ChangePasswordRequest {
|
|||
new_password: string
|
||||
}
|
||||
|
||||
/** Map change-password API failures to localized UI strings. */
|
||||
export function resolveChangePasswordError(error: any): string {
|
||||
const details =
|
||||
typeof error?.error?.details === 'string'
|
||||
? error.error.details
|
||||
: typeof error?.details === 'string'
|
||||
? error.details
|
||||
: ''
|
||||
switch (details) {
|
||||
case 'invalid_old_password':
|
||||
return t('userProfile.changePassword.failed')
|
||||
case 'password_policy':
|
||||
return t('userProfile.changePassword.policyFailed')
|
||||
case 'same_password':
|
||||
return t('userProfile.changePassword.sameAsCurrent')
|
||||
default:
|
||||
return error?.message || t('userProfile.changePassword.failed')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Self-service password rotation. On success the backend revokes every
|
||||
* outstanding session for the caller, so the client should clear local
|
||||
|
|
@ -433,7 +455,7 @@ export async function changePassword(
|
|||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('userProfile.changePassword.failed'),
|
||||
message: resolveChangePasswordError(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5688,6 +5688,10 @@ export default {
|
|||
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.',
|
||||
policyFailed: 'New password must be 8-32 characters and include letters and numbers',
|
||||
sameAsCurrent: 'New password must differ from your current password',
|
||||
oidcOnlyDescription: 'Your account was created via OIDC sign-in and has no known local password yet.',
|
||||
oidcOnlyNotice: 'Ask a system administrator to reset your password, or keep signing in with OIDC. Self-service change requires your current password.',
|
||||
},
|
||||
},
|
||||
tenantMember: {
|
||||
|
|
|
|||
|
|
@ -240,6 +240,10 @@ export default {
|
|||
submit: '비밀번호 업데이트',
|
||||
success: '비밀번호가 변경되었습니다. 새 비밀번호로 다시 로그인해 주세요.',
|
||||
failed: '비밀번호 변경에 실패했습니다. 현재 비밀번호를 확인해 주세요.',
|
||||
policyFailed: '새 비밀번호는 8-32자이며 문자와 숫자를 포함해야 합니다',
|
||||
sameAsCurrent: '새 비밀번호는 현재 비밀번호와 같을 수 없습니다',
|
||||
oidcOnlyDescription: 'OIDC로 개설된 계정입니다. 로컬 로그인 비밀번호가 아직 설정되지 않았습니다.',
|
||||
oidcOnlyNotice: '시스템 관리자에게 비밀번호 재설정을 요청하거나 OIDC로 계속 로그인하세요. 자가 변경에는 현재 비밀번호가 필요합니다.',
|
||||
},
|
||||
},
|
||||
credential: {
|
||||
|
|
|
|||
|
|
@ -240,6 +240,10 @@ export default {
|
|||
submit: 'Обновить пароль',
|
||||
success: 'Пароль обновлён. Войдите снова с новым паролем.',
|
||||
failed: 'Не удалось сменить пароль. Проверьте текущий пароль.',
|
||||
policyFailed: 'Новый пароль: 8–32 символа, буквы и цифры',
|
||||
sameAsCurrent: 'Новый пароль не должен совпадать с текущим',
|
||||
oidcOnlyDescription: 'Аккаунт создан через OIDC; локальный пароль ещё не задан.',
|
||||
oidcOnlyNotice: 'Обратитесь к администратору для сброса пароля или продолжайте вход через OIDC. Для самостоятельной смены нужен текущий пароль.',
|
||||
},
|
||||
},
|
||||
credential: {
|
||||
|
|
|
|||
|
|
@ -240,6 +240,10 @@ export default {
|
|||
submit: '更新密码',
|
||||
success: '密码已更新,请使用新密码重新登录',
|
||||
failed: '修改密码失败,请检查当前密码是否正确',
|
||||
policyFailed: '新密码须为 8-32 个字符,且同时包含字母和数字',
|
||||
sameAsCurrent: '新密码不能与当前密码相同',
|
||||
oidcOnlyDescription: '您的账号通过 OIDC 登录开通,尚未设置本地登录密码。',
|
||||
oidcOnlyNotice: '请联系系统管理员重置密码,或继续使用 OIDC 登录。自助修改密码需要先知道当前密码。',
|
||||
},
|
||||
},
|
||||
credential: {
|
||||
|
|
|
|||
|
|
@ -70,10 +70,21 @@
|
|||
<div class="setting-row password-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('userProfile.changePassword.label') }}</label>
|
||||
<p class="desc">{{ $t('userProfile.changePassword.description') }}</p>
|
||||
<p class="desc">
|
||||
{{ oidcOnlyLogin
|
||||
? $t('userProfile.changePassword.oidcOnlyDescription')
|
||||
: $t('userProfile.changePassword.description') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="setting-control password-control">
|
||||
<t-alert
|
||||
v-if="oidcOnlyLogin"
|
||||
theme="info"
|
||||
:message="$t('userProfile.changePassword.oidcOnlyNotice')"
|
||||
class="oidc-only-notice"
|
||||
/>
|
||||
<t-form
|
||||
v-else
|
||||
ref="passwordFormRef"
|
||||
:data="passwordForm"
|
||||
:rules="passwordRules"
|
||||
|
|
@ -162,6 +173,10 @@ const passwordForm = reactive({
|
|||
confirmPassword: '',
|
||||
})
|
||||
|
||||
const oidcOnlyLogin = computed(
|
||||
() => userInfo.value?.preferences?.oidc_only_login === true,
|
||||
)
|
||||
|
||||
const passwordRules = computed<Record<string, FormRule[]>>(() => ({
|
||||
oldPassword: [
|
||||
{ required: true, message: t('userProfile.changePassword.currentRequired'), type: 'error' },
|
||||
|
|
@ -172,6 +187,11 @@ const passwordRules = computed<Record<string, FormRule[]>>(() => ({
|
|||
{ 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' },
|
||||
{
|
||||
validator: (val: string) => val !== passwordForm.oldPassword,
|
||||
message: t('userProfile.changePassword.sameAsCurrent'),
|
||||
type: 'error',
|
||||
},
|
||||
],
|
||||
confirmPassword: [
|
||||
{ required: true, message: t('auth.confirmPasswordRequired'), type: 'error' },
|
||||
|
|
@ -179,6 +199,7 @@ const passwordRules = computed<Record<string, FormRule[]>>(() => ({
|
|||
validator: (val: string) => val === passwordForm.newPassword,
|
||||
message: t('auth.passwordMismatch'),
|
||||
type: 'error',
|
||||
trigger: 'blur',
|
||||
},
|
||||
],
|
||||
}))
|
||||
|
|
@ -364,6 +385,10 @@ onMounted(loadInfo)
|
|||
align-items: stretch;
|
||||
}
|
||||
|
||||
.oidc-only-notice {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.password-form {
|
||||
width: 100%;
|
||||
|
||||
|
|
|
|||
|
|
@ -42,6 +42,18 @@ var (
|
|||
// 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")
|
||||
|
||||
// ErrSamePassword is returned when the new password equals the current
|
||||
// one so callers can reject no-op rotations that would still revoke
|
||||
// every session.
|
||||
ErrSamePassword = errors.New("new password must differ from current password")
|
||||
)
|
||||
|
||||
// Machine-readable change-password failure reasons for HTTP details fields.
|
||||
const (
|
||||
DetailInvalidOldPassword = "invalid_old_password"
|
||||
DetailPasswordPolicy = "password_policy"
|
||||
DetailSamePassword = "same_password"
|
||||
)
|
||||
|
||||
// ValidatePasswordPolicy keeps administrative password resets aligned with
|
||||
|
|
@ -643,20 +655,25 @@ func (s *userService) DeleteUser(ctx context.Context, id string) error {
|
|||
// 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
|
||||
// Verify old password before policy checks so callers with a wrong
|
||||
// current credential get a clear failure instead of a policy error.
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(oldPassword)); err != nil {
|
||||
return ErrInvalidOldPassword
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(newPassword)); err == nil {
|
||||
return ErrSamePassword
|
||||
}
|
||||
|
||||
if err := ValidatePasswordPolicy(newPassword); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Hash new password
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
|
|
@ -665,6 +682,10 @@ func (s *userService) ChangePassword(ctx context.Context, userID string, oldPass
|
|||
|
||||
user.PasswordHash = string(hashedPassword)
|
||||
user.UpdatedAt = time.Now()
|
||||
if user.Preferences.OidcOnlyLogin != nil && *user.Preferences.OidcOnlyLogin {
|
||||
cleared := false
|
||||
user.Preferences.OidcOnlyLogin = &cleared
|
||||
}
|
||||
|
||||
if err := s.userRepo.UpdateUser(ctx, user); err != nil {
|
||||
return err
|
||||
|
|
@ -1487,6 +1508,13 @@ func (s *userService) provisionOIDCUser(
|
|||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to auto-provision OIDC user: %w", err)
|
||||
}
|
||||
|
||||
oidcOnly := true
|
||||
user.Preferences.OidcOnlyLogin = &oidcOnly
|
||||
user.UpdatedAt = time.Now()
|
||||
if err := s.userRepo.UpdateUser(ctx, user); err != nil {
|
||||
return nil, fmt.Errorf("failed to mark OIDC-only login preference: %w", err)
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -254,6 +254,26 @@ func TestChangePasswordRequiresPolicyAndRevokesSessions(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestChangePasswordRejectsSamePassword(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", "OldSecure9"); !errors.Is(err, ErrSamePassword) {
|
||||
t.Fatalf("ChangePassword(same) err = %v, want ErrSamePassword", err)
|
||||
}
|
||||
if repo.updateCalls != 0 || len(tokenRepo.revokedUserIDs) != 0 {
|
||||
t.Fatalf("same password caused side effects: updates=%d revocations=%v", repo.updateCalls, tokenRepo.revokedUserIDs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserIDFromSignedTokenAcceptsExpiredToken(t *testing.T) {
|
||||
expired := signTestJWT(jwt.MapClaims{
|
||||
"user_id": "user-1",
|
||||
|
|
|
|||
|
|
@ -687,11 +687,18 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {
|
|||
if err != nil {
|
||||
switch {
|
||||
case stderrors.Is(err, service.ErrPasswordPolicy):
|
||||
appErr := errors.NewValidationError(err.Error())
|
||||
appErr := errors.NewValidationError("Password policy violation").
|
||||
WithDetails(service.DetailPasswordPolicy)
|
||||
c.Error(appErr)
|
||||
return
|
||||
case stderrors.Is(err, service.ErrInvalidOldPassword):
|
||||
appErr := errors.NewBadRequestError("Current password is incorrect")
|
||||
appErr := errors.NewBadRequestError("Current password is incorrect").
|
||||
WithDetails(service.DetailInvalidOldPassword)
|
||||
c.Error(appErr)
|
||||
return
|
||||
case stderrors.Is(err, service.ErrSamePassword):
|
||||
appErr := errors.NewValidationError("New password must differ from current password").
|
||||
WithDetails(service.DetailSamePassword)
|
||||
c.Error(appErr)
|
||||
return
|
||||
default:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,140 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
type stubChangePasswordUserService struct {
|
||||
interfaces.UserService
|
||||
getCurrentUser func(ctx context.Context) (*types.User, error)
|
||||
changePassword func(ctx context.Context, userID, oldPassword, newPassword string) error
|
||||
}
|
||||
|
||||
func (s *stubChangePasswordUserService) GetCurrentUser(ctx context.Context) (*types.User, error) {
|
||||
return s.getCurrentUser(ctx)
|
||||
}
|
||||
|
||||
func (s *stubChangePasswordUserService) ChangePassword(
|
||||
ctx context.Context,
|
||||
userID, oldPassword, newPassword string,
|
||||
) error {
|
||||
return s.changePassword(ctx, userID, oldPassword, newPassword)
|
||||
}
|
||||
|
||||
func changePasswordErrorCapture() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Next()
|
||||
if len(c.Errors) == 0 {
|
||||
return
|
||||
}
|
||||
err := c.Errors.Last().Err
|
||||
if appErr, ok := err.(*apperrors.AppError); ok {
|
||||
c.JSON(appErr.HTTPCode, gin.H{
|
||||
"success": false,
|
||||
"error": gin.H{
|
||||
"code": appErr.Code,
|
||||
"message": appErr.Message,
|
||||
"details": appErr.Details,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
}
|
||||
}
|
||||
|
||||
func newChangePasswordTestRouter(h *AuthHandler) *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(changePasswordErrorCapture())
|
||||
r.POST("/auth/change-password", h.ChangePassword)
|
||||
return r
|
||||
}
|
||||
|
||||
func doChangePassword(t *testing.T, r *gin.Engine, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
buf, _ := json.Marshal(body)
|
||||
req := httptest.NewRequest(http.MethodPost, "/auth/change-password", bytes.NewReader(buf))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestChangePassword_MapsInvalidOldPasswordDetail(t *testing.T) {
|
||||
h := &AuthHandler{
|
||||
userService: &stubChangePasswordUserService{
|
||||
getCurrentUser: func(ctx context.Context) (*types.User, error) {
|
||||
return &types.User{ID: "user-1", Email: "alice@example.com"}, nil
|
||||
},
|
||||
changePassword: func(ctx context.Context, userID, oldPassword, newPassword string) error {
|
||||
return service.ErrInvalidOldPassword
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
w := doChangePassword(t, newChangePasswordTestRouter(h), map[string]string{
|
||||
"old_password": "wrong",
|
||||
"new_password": "NewSecure9",
|
||||
})
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
}
|
||||
|
||||
var resp struct {
|
||||
Error struct {
|
||||
Details string `json:"details"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if resp.Error.Details != service.DetailInvalidOldPassword {
|
||||
t.Fatalf("details = %q, want %q", resp.Error.Details, service.DetailInvalidOldPassword)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangePassword_MapsSamePasswordDetail(t *testing.T) {
|
||||
h := &AuthHandler{
|
||||
userService: &stubChangePasswordUserService{
|
||||
getCurrentUser: func(ctx context.Context) (*types.User, error) {
|
||||
return &types.User{ID: "user-1", Email: "alice@example.com"}, nil
|
||||
},
|
||||
changePassword: func(ctx context.Context, userID, oldPassword, newPassword string) error {
|
||||
return service.ErrSamePassword
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
w := doChangePassword(t, newChangePasswordTestRouter(h), map[string]string{
|
||||
"old_password": "OldSecure9",
|
||||
"new_password": "OldSecure9",
|
||||
})
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
}
|
||||
|
||||
var resp struct {
|
||||
Error struct {
|
||||
Details string `json:"details"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if resp.Error.Details != service.DetailSamePassword {
|
||||
t.Fatalf("details = %q, want %q", resp.Error.Details, service.DetailSamePassword)
|
||||
}
|
||||
}
|
||||
|
|
@ -37,6 +37,12 @@ type UserPreferences struct {
|
|||
// a stored *0 the same as nil.
|
||||
// *N = preferred workspace id.
|
||||
LastActiveTenantID *uint64 `json:"last_active_tenant_id,omitempty"`
|
||||
|
||||
// OidcOnlyLogin is set server-side when an account is auto-provisioned
|
||||
// via OIDC with a random password the user never received. The profile
|
||||
// UI hides self-service password rotation until the user sets a known
|
||||
// password via ChangePassword (which clears this flag).
|
||||
OidcOnlyLogin *bool `json:"oidc_only_login,omitempty"`
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer so GORM persists UserPreferences as
|
||||
|
|
|
|||
Loading…
Reference in New Issue