mirror of
https://github.com/nicotsx/ironmount.git
synced 2025-12-10 12:10:51 +01:00
feat: auth client middleware
This commit is contained in:
@@ -68,6 +68,10 @@ export const register = <ThrowOnError extends boolean = false>(options?: Options
|
||||
return (options?.client ?? _heyApiClient).post<RegisterResponses, RegisterErrors, ThrowOnError>({
|
||||
url: "/api/v1/auth/register",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options?.headers,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -78,6 +82,10 @@ export const login = <ThrowOnError extends boolean = false>(options?: Options<Lo
|
||||
return (options?.client ?? _heyApiClient).post<LoginResponses, LoginErrors, ThrowOnError>({
|
||||
url: "/api/v1/auth/login",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options?.headers,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export type RegisterData = {
|
||||
body?: never;
|
||||
body?: {
|
||||
password: string;
|
||||
username: string;
|
||||
};
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: "/api/v1/auth/register";
|
||||
@@ -30,7 +33,10 @@ export type RegisterResponses = {
|
||||
export type RegisterResponse = RegisterResponses[keyof RegisterResponses];
|
||||
|
||||
export type LoginData = {
|
||||
body?: never;
|
||||
body?: {
|
||||
password: string;
|
||||
username: string;
|
||||
};
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: "/api/v1/auth/login";
|
||||
|
||||
@@ -1,8 +1,35 @@
|
||||
import { Outlet } from "react-router";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { Outlet, useNavigate } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { AppBreadcrumb } from "./app-breadcrumb";
|
||||
import { Button } from "./ui/button";
|
||||
import { logoutMutation } from "~/api-client/@tanstack/react-query.gen";
|
||||
import type { Route } from "./+types/layout";
|
||||
import { appContext } from "~/context";
|
||||
import { authMiddleware } from "~/middleware/auth";
|
||||
|
||||
export const clientMiddleware = [authMiddleware];
|
||||
|
||||
export async function clientLoader({ context }: Route.LoaderArgs) {
|
||||
const ctx = context.get(appContext);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export default function Layout({ loaderData }: Route.ComponentProps) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const logout = useMutation({
|
||||
...logoutMutation(),
|
||||
onSuccess: async () => {
|
||||
navigate("/login", { replace: true });
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
toast.error("Logout failed");
|
||||
},
|
||||
});
|
||||
|
||||
export default function Layout() {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -14,7 +41,17 @@ export default function Layout() {
|
||||
>
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-white [mask-image:radial-gradient(ellipse_at_center,transparent_20%,black)] dark:bg-black"></div>
|
||||
<main className="relative flex flex-col pt-4 sm:pt-8 px-2 sm:px-4 pb-4 container mx-auto">
|
||||
<AppBreadcrumb />
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<AppBreadcrumb />
|
||||
{loaderData.user && (
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-sm text-muted-foreground">Welcome, {loaderData.user?.username}</span>
|
||||
<Button variant="outline" size="sm" onClick={() => logout.mutate({})} loading={logout.isPending}>
|
||||
Logout
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
12
apps/client/app/context.ts
Normal file
12
apps/client/app/context.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { createContext } from "react-router";
|
||||
import type { User } from "./lib/types";
|
||||
|
||||
type AppContext = {
|
||||
user: User | null;
|
||||
hasUsers: boolean;
|
||||
};
|
||||
|
||||
export const appContext = createContext<AppContext>({
|
||||
user: null,
|
||||
hasUsers: false,
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { GetVolumeResponse } from "~/api-client";
|
||||
import type { GetMeResponse, GetVolumeResponse } from "~/api-client";
|
||||
|
||||
export type Volume = GetVolumeResponse["volume"];
|
||||
export type StatFs = GetVolumeResponse["statfs"];
|
||||
export type VolumeStatus = Volume["status"];
|
||||
|
||||
export type User = GetMeResponse["user"];
|
||||
|
||||
18
apps/client/app/middleware/auth.ts
Normal file
18
apps/client/app/middleware/auth.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { redirect, type MiddlewareFunction } from "react-router";
|
||||
import { getMe, getStatus } from "~/api-client";
|
||||
import { appContext } from "~/context";
|
||||
|
||||
export const authMiddleware: MiddlewareFunction = async ({ context }) => {
|
||||
const session = await getMe();
|
||||
|
||||
if (!session.data?.user.id) {
|
||||
const status = await getStatus();
|
||||
if (!status.data?.hasUsers) {
|
||||
throw redirect("/register");
|
||||
}
|
||||
|
||||
throw redirect("/login");
|
||||
}
|
||||
|
||||
context.set(appContext, { user: session.data.user, hasUsers: true });
|
||||
};
|
||||
@@ -1,5 +1,7 @@
|
||||
import { index, layout, type RouteConfig, route } from "@react-router/dev/routes";
|
||||
|
||||
export default [
|
||||
route("onboarding", "./routes/onboarding.tsx"),
|
||||
route("login", "./routes/login.tsx"),
|
||||
layout("./components/layout.tsx", [index("./routes/home.tsx"), route("volumes/:name", "./routes/details.tsx")]),
|
||||
] satisfies RouteConfig;
|
||||
|
||||
86
apps/client/app/routes/login.tsx
Normal file
86
apps/client/app/routes/login.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useId, useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
import { loginMutation } from "~/api-client/@tanstack/react-query.gen";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const usernameId = useId();
|
||||
const passwordId = useId();
|
||||
|
||||
const login = useMutation({
|
||||
...loginMutation(),
|
||||
onSuccess: async () => {
|
||||
navigate("/");
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
toast.error("Login failed");
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!username.trim() || !password.trim()) {
|
||||
toast.error("Username and password are required");
|
||||
return;
|
||||
}
|
||||
|
||||
login.mutate({
|
||||
body: {
|
||||
username: username.trim(),
|
||||
password: password.trim(),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-2xl font-bold">Welcome Back</CardTitle>
|
||||
<CardDescription>Sign in to your account</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={usernameId}>Username</Label>
|
||||
<Input
|
||||
id={usernameId}
|
||||
type="text"
|
||||
placeholder="Enter your username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
disabled={login.isPending}
|
||||
autoFocus
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={passwordId}>Password</Label>
|
||||
<Input
|
||||
id={passwordId}
|
||||
type="password"
|
||||
placeholder="Enter your password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={login.isPending}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" className="w-full" loading={login.isPending}>
|
||||
Sign In
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
106
apps/client/app/routes/onboarding.tsx
Normal file
106
apps/client/app/routes/onboarding.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useId, useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
import { registerMutation } from "~/api-client/@tanstack/react-query.gen";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
|
||||
export default function OnboardingPage() {
|
||||
const navigate = useNavigate();
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const usernameId = useId();
|
||||
const passwordId = useId();
|
||||
const confirmPasswordId = useId();
|
||||
|
||||
const register = useMutation({
|
||||
...registerMutation(),
|
||||
onSuccess: async () => {
|
||||
toast.success("Admin user created successfully!");
|
||||
navigate("/");
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
toast.error("Failed to create admin user");
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!username.trim() || !password.trim()) {
|
||||
toast.error("Username and password are required");
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
toast.error("Passwords do not match");
|
||||
return;
|
||||
}
|
||||
|
||||
register.mutate({
|
||||
body: {
|
||||
username: username.trim(),
|
||||
password: password.trim(),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-2xl font-bold">Welcome to IronMount</CardTitle>
|
||||
<CardDescription>Create the admin user to get started</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={usernameId}>Username</Label>
|
||||
<Input
|
||||
id={usernameId}
|
||||
type="text"
|
||||
placeholder="admin"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
disabled={register.isPending}
|
||||
autoFocus
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={passwordId}>Password</Label>
|
||||
<Input
|
||||
id={passwordId}
|
||||
type="password"
|
||||
placeholder="Enter a secure password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={register.isPending}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={confirmPasswordId}>Confirm Password</Label>
|
||||
<Input
|
||||
id={confirmPasswordId}
|
||||
type="password"
|
||||
placeholder="Re-enter your password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
disabled={register.isPending}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={register.isPending}>
|
||||
{register.isPending ? "Creating..." : "Create Admin User"}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user