Skip to content

📚 The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.

fix: require current password when changing password (#620) (#628)

A Sivasubramanian Manojdf4b39d419e7
diff --git a/backend/controllers/access.go b/backend/controllers/access.go
index a20c3824..77ada60d 100644
--- a/backend/controllers/access.go
+++ b/backend/controllers/access.go
@@ -26,5 +26,11 @@ func statusFromAccessError(err error) int {
if errors.Is(err, permissions.ErrNotFound) {
return http.StatusNotFound
}
+ if errors.Is(err, permissions.ErrInvalidPassword) {
+ return http.StatusBadRequest
+ }
+ if errors.Is(err, permissions.ErrIncorrectPassword) {
+ return http.StatusUnauthorized
+ }
return http.StatusInternalServerError
}
diff --git a/backend/controllers/users.controller.go b/backend/controllers/users.controller.go
index 5698d4cf..69bba398 100644
--- a/backend/controllers/users.controller.go
+++ b/backend/controllers/users.controller.go
@@ -163,7 +163,7 @@ func (ctr *Controller) UpdateUser(c *gin.Context) (int, any) {
// @Router /users/{id}/password [patch]
// @Security Authenfification: Auth, {self, admin}
// @Param id path int true "User ID"
-// @Body Password
+// @Body CurrentPassword, Password
// @Success 200 {object} Success(string)
// @Failure 400 {object} Error
// @Failure 401 {object} Error
@@ -178,13 +178,14 @@ func (ctr *Controller) UpdatePassword(c *gin.Context) (int, any) {
}
var payload struct {
- Password string `form:"password" json:"password"`
+ CurrentPassword string `form:"current_password" json:"current_password"`
+ Password string `form:"password" json:"password"`
}
if err := c.ShouldBind(&payload); err != nil {
return http.StatusBadRequest, errors.New("invalid request payload")
}
- err = ctr.app.Services.User.UpdatePassword(c.Request.Context(), targetUserId, payload.Password)
+ err = ctr.app.Services.User.UpdatePassword(c.Request.Context(), targetUserId, payload.CurrentPassword, payload.Password)
if err != nil {
return statusFromAccessError(err), err
}
diff --git a/backend/permissions/service.go b/backend/permissions/service.go
index 13f7543c..6c9c973f 100644
--- a/backend/permissions/service.go
+++ b/backend/permissions/service.go
@@ -30,9 +30,11 @@ func ActorFromContext(ctx context.Context) (Actor, bool) {
}
var (
- ErrUnauthorized = errors.New("unauthorized")
- ErrForbidden = errors.New("forbidden")
- ErrNotFound = errors.New("not found")
+ ErrUnauthorized = errors.New("unauthorized")
+ ErrForbidden = errors.New("forbidden")
+ ErrNotFound = errors.New("not found")
+ ErrInvalidPassword = errors.New("current password is required")
+ ErrIncorrectPassword = errors.New("current password is incorrect")
)
type NodeDecision struct {
diff --git a/backend/services/user.service.go b/backend/services/user.service.go
index 065e2866..c740dc95 100644
--- a/backend/services/user.service.go
+++ b/backend/services/user.service.go
@@ -27,7 +27,7 @@ type UserService interface {
SearchPublicUsers(query string) ([]*models.User, error)
CreateUser(username string, firstname, lastname, avatar, email string, password *string) (*models.User, error)
UpdateUser(ctx context.Context, id types.Snowflake, firstname, lastname, avatar, email *string) (*models.User, error)
- UpdatePassword(ctx context.Context, id types.Snowflake, newPassword string) error
+ UpdatePassword(ctx context.Context, id types.Snowflake, currentPassword string, newPassword string) error
DeleteUser(ctx context.Context, id types.Snowflake, minioService MinioService) error
GenerateUniqueUsername(givenName *string, userID types.Snowflake) string
LoadAppAdmins()
@@ -151,7 +151,7 @@ func (s *userService) UpdateUser(ctx context.Context, id types.Snowflake, firstn
return s.userRepo.Update(id, user)
}
-func (s *userService) UpdatePassword(ctx context.Context, id types.Snowflake, newPassword string) error {
+func (s *userService) UpdatePassword(ctx context.Context, id types.Snowflake, currentPassword string, newPassword string) error {
actor, err := actorFromContext(ctx)
if err != nil {
return err
@@ -164,6 +164,27 @@ func (s *userService) UpdatePassword(ctx context.Context, id types.Snowflake, ne
return errors.New("password is required")
}
+ // Only require the current password when users change their own password.
+ // App admins resetting another user's password are exempt (e.g. account recovery).
+ if actor.UserID == id {
+ dbUser, err := s.userRepo.GetByID(id, true)
+ if err != nil || dbUser == nil {
+ return permissions.ErrNotFound
+ }
+
+ // If the user already has a password set, they must confirm it.
+ // Users without a password (e.g. OAuth/SSO-only accounts) are setting
+ // a password for the first time, so no current-password check applies.
+ if dbUser.Password != nil {
+ if currentPassword == "" {
+ return permissions.ErrInvalidPassword
+ }
+ if err := bcrypt.CompareHashAndPassword([]byte(*dbUser.Password), []byte(currentPassword)); err != nil {
+ return permissions.ErrIncorrectPassword
+ }
+ }
+ }
+
hash, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
if err != nil {
return errors.New("failed to hash password")
diff --git a/backend/tests/user_lifecycle_test.go b/backend/tests/user_lifecycle_test.go
index 067f39f0..a0f8f1a1 100644
--- a/backend/tests/user_lifecycle_test.go
+++ b/backend/tests/user_lifecycle_test.go
@@ -126,6 +126,41 @@ func TestUserLifeCycle(t *testing.T) {
assert.Equal(t, "Unauthorized", r.Message)
})
// ************************************************************
+ // PATCH /users/@me/password
+ // ************************************************************
+ t.Run("Update password without current password fails", func(t *testing.T) {
+ r := DoPatch(t, client, "/users/@me/password", map[string]any{
+ "password": "new-strong-password",
+ })
+ assert.Equal(t, "error", r.Status)
+ assert.Equal(t, 400, r.StatusCode)
+ })
+ t.Run("Update password with wrong current password fails", func(t *testing.T) {
+ r := DoPatch(t, client, "/users/@me/password", map[string]any{
+ "current_password": "not-the-real-password",
+ "password": "new-strong-password",
+ })
+ assert.Equal(t, "error", r.Status)
+ assert.Equal(t, 401, r.StatusCode)
+ })
+ t.Run("Update password with correct current password succeeds", func(t *testing.T) {
+ r := DoPatch(t, client, "/users/@me/password", map[string]any{
+ "current_password": "password",
+ "password": "new-strong-password",
+ })
+ assert.Equal(t, "success", r.Status)
+ assert.Equal(t, 200, r.StatusCode)
+ })
+ t.Run("Login with old password fails after change", func(t *testing.T) {
+ r := LoginAs(t, client, "gnolan", "password")
+ assert.Equal(t, "error", r.Status)
+ })
+ t.Run("Login with new password succeeds", func(t *testing.T) {
+ r := LoginAs(t, client, "gnolan", "new-strong-password")
+ assert.Equal(t, "success", r.Status)
+ assert.Equal(t, 200, r.StatusCode)
+ })
+ // ************************************************************
// DELETE /users/@me
// ************************************************************
t.Run("Delete user", func(t *testing.T) {
diff --git a/frontend/app/pages/dashboard/settings/_views/_components/SecuritySectionPassword.vue b/frontend/app/pages/dashboard/settings/_views/_components/SecuritySectionPassword.vue
index d79b442c..08e20c8e 100644
--- a/frontend/app/pages/dashboard/settings/_views/_components/SecuritySectionPassword.vue
+++ b/frontend/app/pages/dashboard/settings/_views/_components/SecuritySectionPassword.vue
@@ -2,6 +2,10 @@
<section>
<h3>{{ t('settings.security.password') }}</h3>
<form @submit.prevent="changePassword">
+ <div class="form-group">
+ <label for="current_password">{{ t('settings.security.currentPassword') }}</label>
+ <input id="current_password" v-model="currentPasswordValue" autocomplete="current-password" type="password" required />
+ </div>
<div class="form-group">
<label for="password">{{ t('settings.security.newPassword') }}</label>
<input id="password" v-model="passwordValue" autocomplete="new-password" type="password" required />
@@ -25,6 +29,7 @@ const { t } = useI18nT();
const notifications = useNotifications();
const passwordValue = ref('');
+const currentPasswordValue = ref('');
const passwordConfirmValue = ref('');
const errPasswordNotMatch = ref(false);
@@ -32,14 +37,15 @@ const changePassword = async () => {
if (!userStore.user) return;
if (passwordValue.value !== passwordConfirmValue.value) return (errPasswordNotMatch.value = true);
userStore
- .updatePassword(passwordValue.value)
+ .updatePassword(currentPasswordValue.value, passwordValue.value)
.then(() => {
+ currentPasswordValue.value = '';
passwordValue.value = '';
passwordConfirmValue.value = '';
errPasswordNotMatch.value = false;
notifications.add({ type: 'success', title: t('settings.security.notifications.passwordChanged') });
})
- .catch(e => notifications.add({ type: 'error', title: t('settings.security.notifications.passwordError'), message: e.message }));
+ .catch(e => notifications.add({ type: 'error', title: t('settings.security.notifications.passwordError'), message: e }));
};
</script>
<style lang="scss" scoped>
diff --git a/frontend/app/stores/user.store.ts b/frontend/app/stores/user.store.ts
index 3b347db9..db445636 100644
--- a/frontend/app/stores/user.store.ts
+++ b/frontend/app/stores/user.store.ts
@@ -138,9 +138,9 @@ export const useUserStore = defineStore('user', {
} else throw request.message;
},
- async updatePassword(newPassword: string) {
+ async updatePassword(currentPassword: string, newPassword: string) {
if (!this.user) return;
- const request = await makeRequest(`users/${this.user.id}/password`, 'PATCH', { password: newPassword });
+ const request = await makeRequest(`users/${this.user.id}/password`, 'PATCH', { current_password: currentPassword, password: newPassword });
if (request.status === 'success') {
return true;
} else throw request.message;
diff --git a/frontend/app/styles/features/markdown.scss b/frontend/app/styles/features/markdown.scss
index 5fabf2c6..23facc76 100644
--- a/frontend/app/styles/features/markdown.scss
+++ b/frontend/app/styles/features/markdown.scss
@@ -279,15 +279,15 @@
position: relative;
display: inline-block;
- > .hint-tooltip {
+ >.hint-tooltip {
width: max-content;
max-width: 280px;
text-transform: none;
white-space: normal;
}
- &:hover > .hint-tooltip,
- &:focus-visible > .hint-tooltip {
+ &:hover>.hint-tooltip,
+ &:focus-visible>.hint-tooltip {
opacity: 1;
visibility: visible;
transition-delay: 0s;
@@ -313,4 +313,4 @@
background-color: var(--primary);
cursor: help;
user-select: none;
-}
+}
\ No newline at end of file
diff --git a/frontend/i18n/locales/de/settings.ts b/frontend/i18n/locales/de/settings.ts
index cfad1fe7..53432ee6 100644
--- a/frontend/i18n/locales/de/settings.ts
+++ b/frontend/i18n/locales/de/settings.ts
@@ -225,6 +225,7 @@ export default {
connected: 'Verbunden',
connectedAccounts: 'Verbundene Konten',
connectedAccountsDesc: 'Verknüpfe externe Konten für einfachere Anmeldung.',
+ currentPassword: 'Aktuelles Passwort',
dangerZone: 'Gefahrenzone',
dangerZoneDesc: 'Irreversible Aktionen. Mit Vorsicht vorgehen.',
deleteAccount: 'Konto löschen',
diff --git a/frontend/i18n/locales/en/settings.ts b/frontend/i18n/locales/en/settings.ts
index d1c01b8c..9c69274b 100644
--- a/frontend/i18n/locales/en/settings.ts
+++ b/frontend/i18n/locales/en/settings.ts
@@ -224,6 +224,7 @@ export default {
connected: 'Connected',
connectedAccounts: 'Connected accounts',
connectedAccountsDesc: 'Link external accounts for easier sign-in.',
+ currentPassword: 'Current password',
dangerZone: 'Danger zone',
dangerZoneDesc: 'Irreversible actions. Proceed with caution.',
deleteAccount: 'Delete account',
diff --git a/frontend/i18n/locales/fr/settings.ts b/frontend/i18n/locales/fr/settings.ts
index 42f3627d..8a5178c8 100644
--- a/frontend/i18n/locales/fr/settings.ts
+++ b/frontend/i18n/locales/fr/settings.ts
@@ -225,6 +225,7 @@ export default {
connected: 'Connecté',
connectedAccounts: 'Comptes connectés',
connectedAccountsDesc: 'Liez des comptes externes pour une connexion plus facile.',
+ currentPassword: 'Mot de passe actuel',
dangerZone: 'Zone de danger',
dangerZoneDesc: 'Actions irréversibles. Procédez avec précaution.',
deleteAccount: 'Supprimer le compte',
diff --git a/frontend/i18n/locales/it/settings.ts b/frontend/i18n/locales/it/settings.ts
index 9a3438e4..44b9b2a0 100644
--- a/frontend/i18n/locales/it/settings.ts
+++ b/frontend/i18n/locales/it/settings.ts
@@ -224,6 +224,7 @@ export default {
connected: 'Connesso',
connectedAccounts: 'Account collegati',
connectedAccountsDesc: 'Collega account esterni per accedere più facilmente.',
+ currentPassword: 'Password attuale',
dangerZone: 'Zona di pericolo',
dangerZoneDesc: 'Azioni irreversibili. Procedi con cautela.',
deleteAccount: 'Elimina account',
diff --git a/frontend/i18n/locales/ko/settings.ts b/frontend/i18n/locales/ko/settings.ts
index 36163f3b..4c1f529e 100644
--- a/frontend/i18n/locales/ko/settings.ts
+++ b/frontend/i18n/locales/ko/settings.ts
@@ -224,6 +224,7 @@ export default {
connected: '연결됨',
connectedAccounts: '연결된 계정',
connectedAccountsDesc: '쉬운 로그인을 위해 외부 계정을 연결합니다.',
+ currentPassword: '현재 비밀번호',
dangerZone: '위험 구역',
dangerZoneDesc: '되돌릴 수 없는 작업입니다. 주의해서 진행하세요.',
deleteAccount: '계정 삭제',
diff --git a/frontend/i18n/locales/uk/settings.ts b/frontend/i18n/locales/uk/settings.ts
index 6d214158..b72887df 100644
--- a/frontend/i18n/locales/uk/settings.ts
+++ b/frontend/i18n/locales/uk/settings.ts
@@ -224,6 +224,7 @@ export default {
connected: 'Підключено',
connectedAccounts: "Пов'язані акаунти",
connectedAccountsDesc: "Прив'яжіть зовнішні акаунти для зручнішого входу.",
+ currentPassword: 'Поточний пароль',
dangerZone: 'Небезпечна зона',
dangerZoneDesc: 'Незворотні дії. Будьте обережні.',
deleteAccount: 'Видалити обліковий запис',