feat(15-03): rewrite login page and auth hooks for OIDC

- Login page redirects to Logto instead of showing credential form
- AuthState uses string id (Logto sub claim) instead of number
- Remove useLogin, useSetup, useChangePassword hooks
- useLogout redirects to /logout (server-side OIDC logout)
- Remove ChangePasswordSection from settings page
- Update UserMenu to use new useLogout API
- Settings page shows API keys section when authenticated
This commit is contained in:
2026-04-04 20:52:58 +02:00
parent f7c9f3dc94
commit 79b27b6bcc
4 changed files with 37 additions and 186 deletions

View File

@@ -43,7 +43,7 @@ export function UserMenu() {
type="button" type="button"
onClick={() => { onClick={() => {
setOpen(false); setOpen(false);
logout.mutate(); logout();
}} }}
className="flex items-center gap-2 w-full px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors" className="flex items-center gap-2 w-full px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors"
> >

View File

@@ -1,9 +1,9 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiDelete, apiGet, apiPost, apiPut } from "../lib/api"; import { apiDelete, apiGet, apiPost } from "../lib/api";
interface AuthState { interface AuthState {
user: { id: number } | null; user: { id: string; email?: string } | null;
setupRequired: boolean; authenticated: boolean;
} }
export function useAuth() { export function useAuth() {
@@ -14,43 +14,11 @@ export function useAuth() {
}); });
} }
export function useLogin() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: { username: string; password: string }) =>
apiPost<{ username: string }>("/api/auth/login", data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["auth"] });
},
});
}
export function useLogout() { export function useLogout() {
const queryClient = useQueryClient(); const logout = () => {
return useMutation({ window.location.href = "/logout";
mutationFn: () => apiPost<{ success: boolean }>("/api/auth/logout", {}), };
onSuccess: () => { return { logout };
queryClient.invalidateQueries({ queryKey: ["auth"] });
},
});
}
export function useSetup() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: { username: string; password: string }) =>
apiPost<{ username: string }>("/api/auth/setup", data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["auth"] });
},
});
}
export function useChangePassword() {
return useMutation({
mutationFn: (data: { currentPassword: string; newPassword: string }) =>
apiPut<{ success: boolean }>("/api/auth/password", data),
});
} }
interface ApiKeyListItem { interface ApiKeyListItem {

View File

@@ -1,6 +1,6 @@
import { createFileRoute, useNavigate } from "@tanstack/react-router"; import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useState } from "react"; import { useEffect } from "react";
import { useAuth, useLogin, useSetup } from "../hooks/useAuth"; import { useAuth } from "../hooks/useAuth";
export const Route = createFileRoute("/login")({ export const Route = createFileRoute("/login")({
component: LoginPage, component: LoginPage,
@@ -8,96 +8,42 @@ export const Route = createFileRoute("/login")({
function LoginPage() { function LoginPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const { data: auth } = useAuth(); const { data: auth, isLoading } = useAuth();
const login = useLogin();
const setup = useSetup();
const [username, setUsername] = useState(""); useEffect(() => {
const [password, setPassword] = useState(""); if (auth?.authenticated) {
const [error, setError] = useState("");
const isSetup = auth?.setupRequired ?? false;
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError("");
try {
if (isSetup) {
await setup.mutateAsync({ username, password });
} else {
await login.mutateAsync({ username, password });
}
navigate({ to: "/" }); navigate({ to: "/" });
} catch (err) {
setError((err as Error).message);
}
} }
}, [auth, navigate]);
const isPending = login.isPending || setup.isPending; if (isLoading) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<p className="text-gray-500 text-sm">Loading...</p>
</div>
);
}
return ( return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center px-4"> <div className="min-h-screen bg-gray-50 flex items-center justify-center px-4">
<div className="w-full max-w-sm"> <div className="w-full max-w-sm">
<h1 className="text-xl font-semibold text-gray-900 text-center mb-6"> <h1 className="text-xl font-semibold text-gray-900 text-center mb-6">
{isSetup ? "Create Account" : "Sign In"} Sign in to GearBox
</h1> </h1>
<div className="bg-white rounded-xl border border-gray-100 p-6 space-y-4">
<form <p className="text-sm text-gray-500 text-center">
onSubmit={handleSubmit} You will be redirected to sign in with your account.
className="bg-white rounded-xl border border-gray-100 p-6 space-y-4"
>
{isSetup && (
<p className="text-sm text-gray-500">
Create your admin account to manage your gear collection.
</p> </p>
)}
<div>
<label
htmlFor="username"
className="block text-sm font-medium text-gray-700 mb-1"
>
Username
</label>
<input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-200"
/>
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700 mb-1"
>
Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={isSetup ? 6 : undefined}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-200"
/>
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
<button <button
type="submit" type="button"
disabled={isPending} onClick={() => {
className="w-full py-2 px-4 text-sm font-medium text-white bg-gray-700 hover:bg-gray-800 disabled:opacity-50 rounded-lg transition-colors" window.location.href = "/login";
}}
className="w-full py-2 px-4 text-sm font-medium text-white bg-gray-700 hover:bg-gray-800 rounded-lg transition-colors"
> >
{isPending ? "..." : isSetup ? "Create Account" : "Sign In"} Sign In
</button> </button>
</form> </div>
</div> </div>
</div> </div>
); );

View File

@@ -3,7 +3,6 @@ import { useRef, useState } from "react";
import { import {
useApiKeys, useApiKeys,
useAuth, useAuth,
useChangePassword,
useCreateApiKey, useCreateApiKey,
useDeleteApiKey, useDeleteApiKey,
} from "../hooks/useAuth"; } from "../hooks/useAuth";
@@ -16,9 +15,9 @@ import type { Currency, WeightUnit } from "../lib/formatters";
const UNITS: WeightUnit[] = ["g", "oz", "lb", "kg"]; const UNITS: WeightUnit[] = ["g", "oz", "lb", "kg"];
const CURRENCIES: { value: Currency; label: string }[] = [ const CURRENCIES: { value: Currency; label: string }[] = [
{ value: "USD", label: "$" }, { value: "USD", label: "$" },
{ value: "EUR", label: "" }, { value: "EUR", label: "\u20AC" },
{ value: "GBP", label: "£" }, { value: "GBP", label: "\u00A3" },
{ value: "JPY", label: "¥" }, { value: "JPY", label: "\u00A5" },
{ value: "CAD", label: "CA$" }, { value: "CAD", label: "CA$" },
{ value: "AUD", label: "A$" }, { value: "AUD", label: "A$" },
]; ];
@@ -27,66 +26,6 @@ export const Route = createFileRoute("/settings")({
component: SettingsPage, component: SettingsPage,
}); });
function ChangePasswordSection() {
const changePassword = useChangePassword();
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [message, setMessage] = useState<{
type: "success" | "error";
text: string;
} | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setMessage(null);
try {
await changePassword.mutateAsync({ currentPassword, newPassword });
setMessage({ type: "success", text: "Password changed" });
setCurrentPassword("");
setNewPassword("");
} catch (err) {
setMessage({ type: "error", text: (err as Error).message });
}
}
return (
<form onSubmit={handleSubmit} className="space-y-3">
<h3 className="text-sm font-medium text-gray-900">Change Password</h3>
<input
type="password"
placeholder="Current password"
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
required
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-200"
/>
<input
type="password"
placeholder="New password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
required
minLength={6}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-200"
/>
{message && (
<p
className={`text-sm ${message.type === "success" ? "text-green-600" : "text-red-600"}`}
>
{message.text}
</p>
)}
<button
type="submit"
disabled={changePassword.isPending}
className="px-4 py-2 text-sm font-medium text-white bg-gray-700 hover:bg-gray-800 disabled:opacity-50 rounded-lg transition-colors"
>
{changePassword.isPending ? "..." : "Change Password"}
</button>
</form>
);
}
function ApiKeySection() { function ApiKeySection() {
const { data: keys } = useApiKeys(); const { data: keys } = useApiKeys();
const createKey = useCreateApiKey(); const createKey = useCreateApiKey();
@@ -349,10 +288,8 @@ function SettingsPage() {
<ImportExportSection /> <ImportExportSection />
</div> </div>
{auth?.user && ( {auth?.authenticated && (
<div className="bg-white rounded-xl border border-gray-100 p-5 space-y-6 mt-4"> <div className="bg-white rounded-xl border border-gray-100 p-5 space-y-6 mt-4">
<ChangePasswordSection />
<div className="border-t border-gray-100" />
<ApiKeySection /> <ApiKeySection />
</div> </div>
)} )}