Authentication improvements (#21194)

* jwt permissions

* add old password to body req

* add model and migration

need to track the datetime that passwords were changed for the jwt

* auth api backend changes

- use os.open to create jwt secret with restrictive permissions (0o600: read/write for owner only)
- add backend validation for password strength
- add iat claim to jwt so the server can determine when a token was issued and reject any jwts issued before a user's password_changed_at timestamp, ensuring old tokens are invalidated after a password change
- set logout route to public to avoid 401 when logging out
- issue new jwt for users who change their own password so they stay logged in

* improve set password dialog

- add field to verify old password
- add password strength requirements

* frontend tweaks for password dialog

* i18n

* use verify endpoint for existing password verification

avoid /login side effects (creating a new session)

* public logout

* only check if password has changed on jwt refresh

* fix tests

Fix migration 030 by using raw sql to select usernames (avoid ORM selecting nonexistent columns)

* add multi device warning to password dialog

* remove password verification endpoint

Just send old_password + new password in one request, let the backend handle verification in a single operation
This commit is contained in:
Josh Hawkins
2025-12-08 09:02:28 -07:00
committed by GitHub
parent 28b0ad782a
commit 152e585206
12 changed files with 554 additions and 101 deletions
+20 -11
View File
@@ -42,19 +42,27 @@ export default function AccountSettings({ className }: AccountSettingsProps) {
const logoutUrl = config?.proxy?.logout_url || `${baseUrl}api/logout`;
const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
const [passwordError, setPasswordError] = useState<string | null>(null);
const [isPasswordLoading, setIsPasswordLoading] = useState(false);
const Container = isDesktop ? DropdownMenu : Drawer;
const Trigger = isDesktop ? DropdownMenuTrigger : DrawerTrigger;
const Content = isDesktop ? DropdownMenuContent : DrawerContent;
const MenuItem = isDesktop ? DropdownMenuItem : DrawerClose;
const handlePasswordSave = async (password: string) => {
const handlePasswordSave = async (password: string, oldPassword?: string) => {
if (!profile?.username || profile.username === "anonymous") return;
setIsPasswordLoading(true);
axios
.put(`users/${profile.username}/password`, { password })
.put(`users/${profile.username}/password`, {
password,
old_password: oldPassword,
})
.then((response) => {
if (response.status === 200) {
setPasswordDialogOpen(false);
setPasswordError(null);
setIsPasswordLoading(false);
toast.success(t("users.toast.success.updatePassword"), {
position: "top-center",
});
@@ -65,14 +73,10 @@ export default function AccountSettings({ className }: AccountSettingsProps) {
error.response?.data?.message ||
error.response?.data?.detail ||
"Unknown error";
toast.error(
t("users.toast.error.setPasswordFailed", {
errorMessage,
}),
{
position: "top-center",
},
);
// Keep dialog open and show error
setPasswordError(errorMessage);
setIsPasswordLoading(false);
});
};
@@ -154,8 +158,13 @@ export default function AccountSettings({ className }: AccountSettingsProps) {
<SetPasswordDialog
show={passwordDialogOpen}
onSave={handlePasswordSave}
onCancel={() => setPasswordDialogOpen(false)}
onCancel={() => {
setPasswordDialogOpen(false);
setPasswordError(null);
}}
initialError={passwordError}
username={profile?.username}
isLoading={isPasswordLoading}
/>
</Container>
);
+21 -12
View File
@@ -116,13 +116,22 @@ export default function GeneralSettings({ className }: GeneralSettingsProps) {
const SubItemContent = isDesktop ? DropdownMenuSubContent : DialogContent;
const Portal = isDesktop ? DropdownMenuPortal : DialogPortal;
const handlePasswordSave = async (password: string) => {
const [passwordError, setPasswordError] = useState<string | null>(null);
const [isPasswordLoading, setIsPasswordLoading] = useState(false);
const handlePasswordSave = async (password: string, oldPassword?: string) => {
if (!profile?.username || profile.username === "anonymous") return;
setIsPasswordLoading(true);
axios
.put(`users/${profile.username}/password`, { password })
.put(`users/${profile.username}/password`, {
password,
old_password: oldPassword,
})
.then((response) => {
if (response.status === 200) {
setPasswordDialogOpen(false);
setPasswordError(null);
setIsPasswordLoading(false);
toast.success(
t("users.toast.success.updatePassword", {
ns: "views/settings",
@@ -138,15 +147,10 @@ export default function GeneralSettings({ className }: GeneralSettingsProps) {
error.response?.data?.message ||
error.response?.data?.detail ||
"Unknown error";
toast.error(
t("users.toast.error.setPasswordFailed", {
ns: "views/settings",
errorMessage,
}),
{
position: "top-center",
},
);
// Keep dialog open and show error
setPasswordError(errorMessage);
setIsPasswordLoading(false);
});
};
@@ -554,8 +558,13 @@ export default function GeneralSettings({ className }: GeneralSettingsProps) {
<SetPasswordDialog
show={passwordDialogOpen}
onSave={handlePasswordSave}
onCancel={() => setPasswordDialogOpen(false)}
onCancel={() => {
setPasswordDialogOpen(false);
setPasswordError(null);
}}
initialError={passwordError}
username={profile?.username}
isLoading={isPasswordLoading}
/>
</>
);
+319 -51
View File
@@ -1,5 +1,3 @@
"use client";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { useState, useEffect } from "react";
@@ -13,38 +11,84 @@ import {
} from "../ui/dialog";
import { Label } from "../ui/label";
import { LuCheck, LuX } from "react-icons/lu";
import { LuCheck, LuX, LuEye, LuEyeOff, LuExternalLink } from "react-icons/lu";
import { useTranslation } from "react-i18next";
import { useDocDomain } from "@/hooks/use-doc-domain";
import useSWR from "swr";
import { formatSecondsToDuration } from "@/utils/dateUtil";
import ActivityIndicator from "../indicators/activity-indicator";
type SetPasswordProps = {
show: boolean;
onSave: (password: string) => void;
onSave: (password: string, oldPassword?: string) => void;
onCancel: () => void;
initialError?: string | null;
username?: string;
isLoading?: boolean;
};
export default function SetPasswordDialog({
show,
onSave,
onCancel,
initialError,
username,
isLoading = false,
}: SetPasswordProps) {
const { t } = useTranslation(["views/settings"]);
const { t } = useTranslation(["views/settings", "common"]);
const { getLocaleDocUrl } = useDocDomain();
const { data: config } = useSWR("config");
const refreshSeconds: number | undefined =
config?.auth?.refresh_time ?? undefined;
const refreshTimeLabel = refreshSeconds
? formatSecondsToDuration(refreshSeconds)
: "30 minutes";
const [oldPassword, setOldPassword] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [confirmPassword, setConfirmPassword] = useState<string>("");
const [passwordStrength, setPasswordStrength] = useState<number>(0);
const [error, setError] = useState<string | null>(null);
// Reset state when dialog opens/closes
// visibility toggles for password fields
const [showOldPassword, setShowOldPassword] = useState<boolean>(false);
const [showPasswordVisible, setShowPasswordVisible] =
useState<boolean>(false);
const [showConfirmPassword, setShowConfirmPassword] =
useState<boolean>(false);
const [hasInitialized, setHasInitialized] = useState<boolean>(false);
// Password strength requirements
const requirements = {
length: password.length >= 8,
uppercase: /[A-Z]/.test(password),
digit: /\d/.test(password),
special: /[!@#$%^&*(),.?":{}|<>]/.test(password),
};
useEffect(() => {
if (show) {
setPassword("");
setConfirmPassword("");
setError(null);
if (!hasInitialized) {
setOldPassword("");
setPassword("");
setConfirmPassword("");
setError(null);
setHasInitialized(true);
}
} else {
setHasInitialized(false);
}
}, [show]);
}, [show, hasInitialized]);
useEffect(() => {
if (show && initialError) {
setError(initialError);
}
}, [show, initialError]);
// Password strength calculation
// Simple password strength calculation
useEffect(() => {
if (!password) {
setPasswordStrength(0);
@@ -52,30 +96,52 @@ export default function SetPasswordDialog({
}
let strength = 0;
// Length check
if (password.length >= 8) strength += 1;
// Contains number
if (/\d/.test(password)) strength += 1;
// Contains special char
if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength += 1;
// Contains uppercase
if (/[A-Z]/.test(password)) strength += 1;
if (requirements.length) strength += 1;
if (requirements.digit) strength += 1;
if (requirements.special) strength += 1;
if (requirements.uppercase) strength += 1;
setPasswordStrength(strength);
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [password]);
const handleSave = () => {
const handleSave = async () => {
if (!password) {
setError(t("users.dialog.passwordSetting.cannotBeEmpty"));
return;
}
// Validate all requirements
if (!requirements.length) {
setError(t("users.dialog.form.password.requirements.length"));
return;
}
if (!requirements.uppercase) {
setError(t("users.dialog.form.password.requirements.uppercase"));
return;
}
if (!requirements.digit) {
setError(t("users.dialog.form.password.requirements.digit"));
return;
}
if (!requirements.special) {
setError(t("users.dialog.form.password.requirements.special"));
return;
}
if (password !== confirmPassword) {
setError(t("users.dialog.passwordSetting.doNotMatch"));
return;
}
onSave(password);
// Require old password when changing own password (username is provided)
if (username && !oldPassword) {
setError(t("users.dialog.passwordSetting.currentPasswordRequired"));
return;
}
onSave(password, oldPassword || undefined);
};
const getStrengthLabel = () => {
@@ -112,39 +178,199 @@ export default function SetPasswordDialog({
<DialogDescription>
{t("users.dialog.passwordSetting.desc")}
</DialogDescription>
<p className="text-sm text-muted-foreground">
{t("users.dialog.passwordSetting.multiDeviceWarning", {
refresh_time: refreshTimeLabel,
ns: "views/settings",
})}
</p>
<p className="text-sm text-primary-variant">
<a
href={getLocaleDocUrl(
"configuration/authentication#jwt-token-secret",
)}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center text-primary"
>
{t("readTheDocumentation", { ns: "common" })}
<LuExternalLink className="ml-2 size-3" />
</a>
</p>
</DialogHeader>
<div className="space-y-4 pt-4">
{username && (
<div className="space-y-2">
<Label htmlFor="old-password">
{t("users.dialog.form.currentPassword.title")}
</Label>
<div className="relative">
<Input
id="old-password"
className="h-10 pr-10"
type={showOldPassword ? "text" : "password"}
value={oldPassword}
onChange={(event) => {
setOldPassword(event.target.value);
setError(null);
}}
placeholder={t(
"users.dialog.form.currentPassword.placeholder",
)}
/>
<Button
type="button"
variant="ghost"
size="sm"
tabIndex={-1}
aria-label={
showOldPassword
? t("users.dialog.form.password.hide", {
ns: "views/settings",
})
: t("users.dialog.form.password.show", {
ns: "views/settings",
})
}
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowOldPassword(!showOldPassword)}
>
{showOldPassword ? (
<LuEyeOff className="size-4" />
) : (
<LuEye className="size-4" />
)}
</Button>
</div>
</div>
)}
<div className="space-y-2">
<Label htmlFor="password">
{t("users.dialog.form.newPassword.title")}
</Label>
<Input
id="password"
className="h-10"
type="password"
value={password}
onChange={(event) => {
setPassword(event.target.value);
setError(null);
}}
placeholder={t("users.dialog.form.newPassword.placeholder")}
autoFocus
/>
<div className="relative">
<Input
id="password"
className="h-10 pr-10"
type={showPasswordVisible ? "text" : "password"}
value={password}
onChange={(event) => {
setPassword(event.target.value);
setError(null);
}}
placeholder={t("users.dialog.form.newPassword.placeholder")}
autoFocus
/>
<Button
type="button"
variant="ghost"
size="sm"
tabIndex={-1}
aria-label={
showPasswordVisible
? t("users.dialog.form.password.hide", {
ns: "views/settings",
})
: t("users.dialog.form.password.show", {
ns: "views/settings",
})
}
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowPasswordVisible(!showPasswordVisible)}
>
{showPasswordVisible ? (
<LuEyeOff className="size-4" />
) : (
<LuEye className="size-4" />
)}
</Button>
</div>
{/* Password strength indicator */}
{password && (
<div className="mt-2 space-y-1">
<div className="mt-2 space-y-2">
<div className="flex h-1.5 w-full overflow-hidden rounded-full bg-secondary-foreground">
<div
className={`${getStrengthColor()} transition-all duration-300`}
style={{ width: `${(passwordStrength / 3) * 100}%` }}
style={{ width: `${(passwordStrength / 4) * 100}%` }}
/>
</div>
<p className="text-xs text-muted-foreground">
{t("users.dialog.form.password.strength.title")}
<span className="font-medium">{getStrengthLabel()}</span>
</p>
<div className="space-y-1 rounded-md bg-muted/50 p-2">
<p className="text-xs font-medium text-muted-foreground">
{t("users.dialog.form.password.requirements.title")}
</p>
<ul className="space-y-1">
<li className="flex items-center gap-2 text-xs">
{requirements.length ? (
<LuCheck className="size-3.5 text-green-500" />
) : (
<LuX className="size-3.5 text-red-500" />
)}
<span
className={
requirements.length
? "text-green-600"
: "text-red-600"
}
>
{t("users.dialog.form.password.requirements.length")}
</span>
</li>
<li className="flex items-center gap-2 text-xs">
{requirements.uppercase ? (
<LuCheck className="size-3.5 text-green-500" />
) : (
<LuX className="size-3.5 text-red-500" />
)}
<span
className={
requirements.uppercase
? "text-green-600"
: "text-red-600"
}
>
{t("users.dialog.form.password.requirements.uppercase")}
</span>
</li>
<li className="flex items-center gap-2 text-xs">
{requirements.digit ? (
<LuCheck className="size-3.5 text-green-500" />
) : (
<LuX className="size-3.5 text-red-500" />
)}
<span
className={
requirements.digit ? "text-green-600" : "text-red-600"
}
>
{t("users.dialog.form.password.requirements.digit")}
</span>
</li>
<li className="flex items-center gap-2 text-xs">
{requirements.special ? (
<LuCheck className="size-3.5 text-green-500" />
) : (
<LuX className="size-3.5 text-red-500" />
)}
<span
className={
requirements.special
? "text-green-600"
: "text-red-600"
}
>
{t("users.dialog.form.password.requirements.special")}
</span>
</li>
</ul>
</div>
</div>
)}
</div>
@@ -153,19 +379,44 @@ export default function SetPasswordDialog({
<Label htmlFor="confirm-password">
{t("users.dialog.form.password.confirm.title")}
</Label>
<Input
id="confirm-password"
className="h-10"
type="password"
value={confirmPassword}
onChange={(event) => {
setConfirmPassword(event.target.value);
setError(null);
}}
placeholder={t(
"users.dialog.form.newPassword.confirm.placeholder",
)}
/>
<div className="relative">
<Input
id="confirm-password"
className="h-10 pr-10"
type={showConfirmPassword ? "text" : "password"}
value={confirmPassword}
onChange={(event) => {
setConfirmPassword(event.target.value);
setError(null);
}}
placeholder={t(
"users.dialog.form.newPassword.confirm.placeholder",
)}
/>
<Button
type="button"
variant="ghost"
size="sm"
tabIndex={-1}
aria-label={
showConfirmPassword
? t("users.dialog.form.password.hide", {
ns: "views/settings",
})
: t("users.dialog.form.password.show", {
ns: "views/settings",
})
}
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
>
{showConfirmPassword ? (
<LuEyeOff className="size-4" />
) : (
<LuEye className="size-4" />
)}
</Button>
</div>
{/* Password match indicator */}
{password && confirmPassword && (
@@ -204,6 +455,7 @@ export default function SetPasswordDialog({
aria-label={t("button.cancel", { ns: "common" })}
onClick={onCancel}
type="button"
disabled={isLoading}
>
{t("button.cancel", { ns: "common" })}
</Button>
@@ -212,9 +464,25 @@ export default function SetPasswordDialog({
aria-label={t("button.save", { ns: "common" })}
className="flex flex-1"
onClick={handleSave}
disabled={!password || password !== confirmPassword}
disabled={
isLoading ||
!password ||
password !== confirmPassword ||
(username && !oldPassword) ||
!requirements.length ||
!requirements.uppercase ||
!requirements.digit ||
!requirements.special
}
>
{t("button.save", { ns: "common" })}
{isLoading ? (
<div className="flex flex-row items-center gap-2">
<ActivityIndicator />
<span>{t("button.saving", { ns: "common" })}</span>
</div>
) : (
t("button.save", { ns: "common" })
)}
</Button>
</div>
</div>