feat: add change password to web and mobile settings

Add a change password feature using Better Auth's built-in
changePassword endpoint. On web, a dialog opens from a new card in the
Account section. On mobile, a dedicated screen is pushed from a new
SettingsRow. Both use listAccounts to detect credential-based accounts
and only show the option when the user has a password and password login
is enabled (respecting OIDC-only configurations).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-13 20:43:34 -04:00
co-authored by Claude Opus 4.6
parent 1798107afc
commit b7bacb352f
7 changed files with 449 additions and 0 deletions
+4
View File
@@ -31,6 +31,10 @@ BETTER_AUTH_URL=http://localhost:3000
# Log verbosity: error, warn, info, debug (default: info) # Log verbosity: error, warn, info, debug (default: info)
# LOG_LEVEL=info # LOG_LEVEL=info
# ─── Update Checks ────────────────────────────────────────────────────
# Base URL for the public API used for update checks and other centralized features
# PUBLIC_API_URL=https://public-api.sofa.watch
# ─── Image Caching ───────────────────────────────────────────────────── # ─── Image Caching ─────────────────────────────────────────────────────
# Set IMAGE_CACHE_ENABLED to "false" to use TMDB CDN directly (default: enabled) # Set IMAGE_CACHE_ENABLED to "false" to use TMDB CDN directly (default: enabled)
# IMAGE_CACHE_ENABLED=true # IMAGE_CACHE_ENABLED=true
+1
View File
@@ -103,6 +103,7 @@ Required: `TMDB_API_READ_ACCESS_TOKEN`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`.
Optional: Optional:
- `DATA_DIR` — Root for DB + cache (default `./data`). `DATABASE_URL` and `CACHE_DIR` derived from it but overridable. - `DATA_DIR` — Root for DB + cache (default `./data`). `DATABASE_URL` and `CACHE_DIR` derived from it but overridable.
- `TMDB_API_BASE_URL`, `TMDB_IMAGE_BASE_URL` — Override TMDB endpoints. - `TMDB_API_BASE_URL`, `TMDB_IMAGE_BASE_URL` — Override TMDB endpoints.
- `PUBLIC_API_URL` — Base URL for centralized public API (default: `https://public-api.sofa.watch`). Used for update checks.
- `IMAGE_CACHE_ENABLED` — Default `true`. Set `false` for direct TMDB CDN URLs. - `IMAGE_CACHE_ENABLED` — Default `true`. Set `false` for direct TMDB CDN URLs.
- `LOG_LEVEL``error`/`warn`/`info`/`debug` (default: `info`). - `LOG_LEVEL``error`/`warn`/`info`/`debug` (default: `info`).
- OIDC: `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, `OIDC_ISSUER_URL`, `OIDC_PROVIDER_NAME`, `OIDC_AUTO_REGISTER`, `DISABLE_PASSWORD_LOGIN`. - OIDC: `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, `OIDC_ISSUER_URL`, `OIDC_PROVIDER_NAME`, `OIDC_AUTO_REGISTER`, `DISABLE_PASSWORD_LOGIN`.
+1
View File
@@ -9,6 +9,7 @@ npm-debug.*
*.mobileprovision *.mobileprovision
*.orig.* *.orig.*
*.tar.gz *.tar.gz
*.ipa
web-build/ web-build/
# macOS # macOS
@@ -0,0 +1,203 @@
import { useForm } from "@tanstack/react-form";
import { Stack, useRouter } from "expo-router";
import { useRef, useState } from "react";
import { Alert, type TextInput, View } from "react-native";
import Animated, { FadeInDown } from "react-native-reanimated";
import { z } from "zod";
import { Button, ButtonLabel } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { Text } from "@/components/ui/text";
import {
FieldError,
Input,
Label,
TextField,
} from "@/components/ui/text-field";
import { authClient } from "@/lib/auth-client";
import { toast } from "@/lib/toast";
import * as Haptics from "@/utils/haptics";
const changePasswordSchema = z
.object({
currentPassword: z.string().min(1, "Current password is required"),
newPassword: z.string().min(8, "Password must be at least 8 characters"),
confirmPassword: z.string().min(1, "Please confirm your password"),
})
.refine((data) => data.newPassword === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"],
});
function formatFormErrors(errors: unknown): string | null {
if (!errors) return null;
if (typeof errors === "string") return errors;
if (typeof errors === "object") {
const first = Object.values(errors as Record<string, { message: string }[]>)
.flat()
.find((e) => e.message);
if (first) return first.message;
}
return null;
}
export default function ChangePasswordScreen() {
const router = useRouter();
const newPasswordRef = useRef<TextInput>(null);
const confirmPasswordRef = useRef<TextInput>(null);
const [revokeOtherSessions, setRevokeOtherSessions] = useState(false);
const form = useForm({
defaultValues: {
currentPassword: "",
newPassword: "",
confirmPassword: "",
},
validators: { onSubmit: changePasswordSchema },
onSubmit: async ({ value, formApi }) => {
try {
const result = await authClient.changePassword({
currentPassword: value.currentPassword,
newPassword: value.newPassword,
revokeOtherSessions,
});
if (result.error) {
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
Alert.alert(
"Error",
result.error.message ?? "Failed to change password",
);
return;
}
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
toast.success("Password updated");
formApi.reset();
router.back();
} catch {
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
Alert.alert("Error", "Something went wrong");
}
},
});
return (
<View className="flex-1 bg-background px-4 pt-4">
<Stack.Screen options={{ title: "Change Password" }} />
<form.Subscribe
selector={(state) => ({
isSubmitting: state.isSubmitting,
validationError: formatFormErrors(state.errorMap.onSubmit),
})}
>
{({ isSubmitting, validationError }) => (
<View className="gap-4">
{validationError && (
<FieldError isInvalid className="mb-1">
{validationError}
</FieldError>
)}
<Animated.View entering={FadeInDown.duration(300).delay(100)}>
<form.Field name="currentPassword">
{(field) => (
<TextField>
<Label>Current password</Label>
<Input
value={field.state.value}
onBlur={field.handleBlur}
onChangeText={field.handleChange}
placeholder="••••••••"
secureTextEntry
autoComplete="current-password"
textContentType="password"
returnKeyType="next"
blurOnSubmit={false}
onSubmitEditing={() => newPasswordRef.current?.focus()}
/>
</TextField>
)}
</form.Field>
</Animated.View>
<Animated.View entering={FadeInDown.duration(300).delay(200)}>
<form.Field name="newPassword">
{(field) => (
<TextField>
<Label>New password</Label>
<Input
ref={newPasswordRef}
value={field.state.value}
onBlur={field.handleBlur}
onChangeText={field.handleChange}
placeholder="••••••••"
secureTextEntry
autoComplete="new-password"
textContentType="newPassword"
returnKeyType="next"
blurOnSubmit={false}
onSubmitEditing={() =>
confirmPasswordRef.current?.focus()
}
/>
</TextField>
)}
</form.Field>
</Animated.View>
<Animated.View entering={FadeInDown.duration(300).delay(300)}>
<form.Field name="confirmPassword">
{(field) => (
<TextField>
<Label>Confirm new password</Label>
<Input
ref={confirmPasswordRef}
value={field.state.value}
onBlur={field.handleBlur}
onChangeText={field.handleChange}
placeholder="••••••••"
secureTextEntry
autoComplete="new-password"
textContentType="newPassword"
returnKeyType="go"
onSubmitEditing={form.handleSubmit}
/>
</TextField>
)}
</form.Field>
</Animated.View>
<Animated.View
entering={FadeInDown.duration(300).delay(400)}
className="flex-row items-center justify-between rounded-xl border border-border bg-input px-3.5 py-3"
style={{ borderCurve: "continuous" }}
>
<Text className="text-[15px] text-foreground">
Sign out of other sessions
</Text>
<Switch
value={revokeOtherSessions}
onValueChange={setRevokeOtherSessions}
/>
</Animated.View>
<Animated.View entering={FadeInDown.duration(300).delay(500)}>
<Button
onPress={form.handleSubmit}
disabled={isSubmitting}
className="mt-2 bg-primary"
>
{isSubmitting ? (
<Spinner size="sm" />
) : (
<ButtonLabel>Update Password</ButtonLabel>
)}
</Button>
</Animated.View>
</View>
)}
</form.Subscribe>
</View>
);
}
@@ -8,6 +8,7 @@ import {
IconDeviceMobileCog, IconDeviceMobileCog,
IconDots, IconDots,
IconLink, IconLink,
IconLock,
IconLogout, IconLogout,
IconPhoto, IconPhoto,
IconServer, IconServer,
@@ -63,6 +64,21 @@ export default function SettingsScreen() {
const isAdmin = session?.user?.role === "admin"; const isAdmin = session?.user?.role === "admin";
const serverUrl = getServerUrl(); const serverUrl = getServerUrl();
const authConfig = useQuery(orpc.system.authConfig.queryOptions());
const { data: accounts } = useQuery({
queryKey: ["auth", "listAccounts"],
queryFn: async () => {
const result = await authClient.listAccounts();
return result.data;
},
});
const hasPassword =
accounts?.some(
(a: { providerId: string }) => a.providerId === "credential",
) ?? false;
const showPasswordOption =
hasPassword && !(authConfig.data?.passwordLoginDisabled ?? true);
const systemHealth = useQuery({ const systemHealth = useQuery({
...orpc.system.health.queryOptions(), ...orpc.system.health.queryOptions(),
enabled: isAdmin, enabled: isAdmin,
@@ -318,6 +334,14 @@ export default function SettingsScreen() {
)} )}
</View> </View>
{showPasswordOption && (
<SettingsRow
label={hasPassword ? "Change password" : "Set password"}
icon={IconLock}
onPress={() => push("/(tabs)/(settings)/change-password")}
/>
)}
<SettingsRow <SettingsRow
label="Sign out" label="Sign out"
icon={IconLogout} icon={IconLogout}
@@ -0,0 +1,214 @@
import { IconAlertTriangle, IconLock } from "@tabler/icons-react";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardTitle,
} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Spinner } from "@/components/ui/spinner";
import { authClient } from "@/lib/auth/client";
import { orpc } from "@/lib/orpc/client";
export function ChangePasswordSection() {
const { data: authConfig, isPending: authConfigPending } = useQuery(
orpc.system.authConfig.queryOptions(),
);
const { data: accounts, isPending: accountsPending } = useQuery({
queryKey: ["auth", "listAccounts"],
queryFn: async () => {
const result = await authClient.listAccounts();
return result.data;
},
});
const isLoading = authConfigPending || accountsPending;
const passwordLoginDisabled = authConfig?.passwordLoginDisabled ?? true;
const hasPassword =
accounts?.some(
(a: { providerId: string }) => a.providerId === "credential",
) ?? false;
// Only show for users who have a password account and password login is enabled
if (isLoading || passwordLoginDisabled || !hasPassword) return null;
return (
<Card>
<CardContent>
<div className="flex items-center justify-between gap-4">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<IconLock aria-hidden={true} className="size-4 text-primary" />
</div>
<div>
<CardTitle>Change password</CardTitle>
<CardDescription>Update your account password</CardDescription>
</div>
</div>
<ChangePasswordDialog />
</div>
</CardContent>
</Card>
);
}
function ChangePasswordDialog() {
const [open, setOpen] = useState(false);
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [revokeOtherSessions, setRevokeOtherSessions] = useState(false);
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
function resetForm() {
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
setRevokeOtherSessions(false);
setError("");
}
function handleOpenChange(nextOpen: boolean) {
setOpen(nextOpen);
if (!nextOpen) resetForm();
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError("");
if (!currentPassword) {
setError("Current password is required");
return;
}
if (newPassword.length < 8) {
setError("New password must be at least 8 characters");
return;
}
if (newPassword !== confirmPassword) {
setError("Passwords do not match");
return;
}
setIsSubmitting(true);
try {
const result = await authClient.changePassword({
currentPassword,
newPassword,
revokeOtherSessions,
});
if (result.error) {
setError(result.error.message ?? "Failed to change password");
return;
}
toast.success("Password updated");
handleOpenChange(false);
} catch {
setError("Something went wrong");
} finally {
setIsSubmitting(false);
}
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<Button variant="outline" size="sm" onClick={() => setOpen(true)}>
Change
</Button>
<DialogContent>
<DialogHeader>
<DialogTitle>Change password</DialogTitle>
<DialogDescription>
Enter your current password and choose a new one.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="grid gap-3">
{error && (
<Alert variant="destructive">
<IconAlertTriangle />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="grid gap-1.5">
<Label htmlFor="current-password">Current password</Label>
<Input
id="current-password"
type="password"
autoComplete="current-password"
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
disabled={isSubmitting}
/>
</div>
<div className="grid gap-1.5">
<Label htmlFor="new-password">New password</Label>
<Input
id="new-password"
type="password"
autoComplete="new-password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
disabled={isSubmitting}
/>
</div>
<div className="grid gap-1.5">
<Label htmlFor="confirm-password">Confirm new password</Label>
<Input
id="confirm-password"
type="password"
autoComplete="new-password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
disabled={isSubmitting}
/>
</div>
<div className="flex items-center gap-2 pt-1">
<Checkbox
id="revoke-sessions"
checked={revokeOtherSessions}
onCheckedChange={(checked) =>
setRevokeOtherSessions(checked === true)
}
disabled={isSubmitting}
/>
<Label htmlFor="revoke-sessions" className="cursor-pointer">
Sign out of other sessions
</Label>
</div>
<DialogFooter className="pt-2">
<DialogClose render={<Button variant="outline" />}>
Cancel
</DialogClose>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Spinner className="size-3.5" />}
Update password
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
+2
View File
@@ -8,6 +8,7 @@ import { AccountSection } from "@/components/settings/account-section";
import { BackupRestoreSection } from "@/components/settings/backup-restore-section"; import { BackupRestoreSection } from "@/components/settings/backup-restore-section";
import { BackupScheduleSection } from "@/components/settings/backup-schedule-section"; import { BackupScheduleSection } from "@/components/settings/backup-schedule-section";
import { BackupSection } from "@/components/settings/backup-section"; import { BackupSection } from "@/components/settings/backup-section";
import { ChangePasswordSection } from "@/components/settings/change-password-section";
import { IntegrationsSection } from "@/components/settings/integrations-section"; import { IntegrationsSection } from "@/components/settings/integrations-section";
import { RegistrationSection } from "@/components/settings/registration-section"; import { RegistrationSection } from "@/components/settings/registration-section";
import { SettingsShell } from "@/components/settings/settings-shell"; import { SettingsShell } from "@/components/settings/settings-shell";
@@ -82,6 +83,7 @@ function SettingsPage() {
role: session.user.role ?? undefined, role: session.user.role ?? undefined,
}} }}
/> />
<ChangePasswordSection />
<IntegrationsSection /> <IntegrationsSection />
{isAdmin && ( {isAdmin && (
<> <>