mirror of
https://github.com/steveiliop56/tinyauth.git
synced 2025-11-04 16:15:45 +00:00
feat: finalize username login
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Input } from "../ui/input";
|
||||
import { z } from "zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import {
|
||||
@@ -12,26 +11,21 @@ import {
|
||||
FormMessage,
|
||||
} from "../ui/form";
|
||||
import { Button } from "../ui/button";
|
||||
import { loginSchema, LoginSchema } from "@/schemas/login-schema";
|
||||
|
||||
export const LoginForm = () => {
|
||||
interface Props {
|
||||
onSubmit: (data: LoginSchema) => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export const LoginForm = (props: Props) => {
|
||||
const { onSubmit, loading } = props;
|
||||
const { t } = useTranslation();
|
||||
|
||||
const schema = z.object({
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
const form = useForm<LoginSchema>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
});
|
||||
|
||||
type LoginFormType = z.infer<typeof schema>;
|
||||
|
||||
const form = useForm<LoginFormType>({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
const onSubmit = (data: LoginFormType) => {
|
||||
// Handle login logic here
|
||||
console.log("Login data:", data);
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
@@ -42,7 +36,11 @@ export const LoginForm = () => {
|
||||
<FormItem className="mb-4">
|
||||
<FormLabel>{t("loginUsername")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder={t("loginUsername")} {...field} />
|
||||
<Input
|
||||
placeholder={t("loginUsername")}
|
||||
disabled={loading}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -66,6 +64,7 @@ export const LoginForm = () => {
|
||||
<Input
|
||||
placeholder={t("loginPassword")}
|
||||
type="password"
|
||||
disabled={loading}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
@@ -73,7 +72,7 @@ export const LoginForm = () => {
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button className="w-full" type="submit">
|
||||
<Button className="w-full" type="submit" loading={loading}>
|
||||
{t("loginSubmit")}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { z } from "zod";
|
||||
import { Form, FormControl, FormField, FormItem } from "../ui/form";
|
||||
import {
|
||||
InputOTP,
|
||||
@@ -8,23 +7,19 @@ import {
|
||||
} from "../ui/input-otp";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { totpSchema, TotpSchema } from "@/schemas/totp-schema";
|
||||
|
||||
interface Props {
|
||||
formId: string;
|
||||
onSubmit: (code: FormValues) => void;
|
||||
onSubmit: (code: TotpSchema) => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
const schema = z.object({
|
||||
code: z.string(),
|
||||
});
|
||||
|
||||
export type FormValues = z.infer<typeof schema>;
|
||||
|
||||
export const TotpForm = (props: Props) => {
|
||||
const { formId, onSubmit } = props;
|
||||
const { formId, onSubmit, loading } = props;
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
const form = useForm<TotpSchema>({
|
||||
resolver: zodResolver(totpSchema),
|
||||
});
|
||||
|
||||
return (
|
||||
@@ -36,7 +31,7 @@ export const TotpForm = (props: Props) => {
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<InputOTP maxLength={6} {...field}>
|
||||
<InputOTP maxLength={6} disabled={loading} {...field}>
|
||||
<InputOTPGroup>
|
||||
<InputOTPSlot index={0} />
|
||||
<InputOTPSlot index={1} />
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
@@ -42,13 +43,28 @@ function Button({
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
loading = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean;
|
||||
loading?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
disabled
|
||||
{...props}
|
||||
>
|
||||
<Loader2 className="animate-spin" />
|
||||
</Comp>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
|
||||
23
frontend/src/components/ui/sonner.tsx
Normal file
23
frontend/src/components/ui/sonner.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -15,6 +15,7 @@ import { UnauthorizedPage } from "./pages/unauthorized-page.tsx";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { AppContextProvider } from "./context/app-context.tsx";
|
||||
import { UserContextProvider } from "./context/user-context.tsx";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
@@ -52,6 +53,11 @@ const router = createBrowserRouter([
|
||||
element: <UnauthorizedPage />,
|
||||
errorElement: <ErrorPage />,
|
||||
},
|
||||
{
|
||||
path: "/error",
|
||||
element: <ErrorPage />,
|
||||
errorElement: <ErrorPage />,
|
||||
},
|
||||
{
|
||||
path: "*",
|
||||
element: <NotFoundPage />,
|
||||
@@ -68,6 +74,7 @@ createRoot(document.getElementById("root")!).render(
|
||||
<UserContextProvider>
|
||||
<Layout>
|
||||
<RouterProvider router={router} />
|
||||
<Toaster />
|
||||
</Layout>
|
||||
</UserContextProvider>
|
||||
</AppContextProvider>
|
||||
|
||||
@@ -20,24 +20,24 @@ export const ContinuePage = () => {
|
||||
const { domain, disableContinue } = useAppContext();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
if (!isLoggedIn) {
|
||||
return <Navigate to="/login" />;
|
||||
}
|
||||
|
||||
if (!redirectURI) {
|
||||
return <Navigate to="/" />;
|
||||
return <Navigate to="/logout" />;
|
||||
}
|
||||
|
||||
if (!isValidUrl(redirectURI)) {
|
||||
return <Navigate to="/" />;
|
||||
return <Navigate to="/logout" />;
|
||||
}
|
||||
|
||||
if (disableContinue) {
|
||||
window.location.href = redirectURI;
|
||||
}
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const url = new URL(redirectURI);
|
||||
|
||||
if (!url.hostname.includes(domain)) {
|
||||
@@ -60,12 +60,12 @@ export const ContinuePage = () => {
|
||||
</CardHeader>
|
||||
<CardFooter className="flex flex-col items-stretch gap-2">
|
||||
<Button
|
||||
onClick={() => window.location.replace(redirectURI)}
|
||||
onClick={() => (window.location.href = redirectURI)}
|
||||
variant="destructive"
|
||||
>
|
||||
{t("continueTitle")}
|
||||
</Button>
|
||||
<Button onClick={() => navigate("/")} variant="outline">
|
||||
<Button onClick={() => navigate("/logout")} variant="outline">
|
||||
{t("cancelTitle")}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
@@ -92,12 +92,12 @@ export const ContinuePage = () => {
|
||||
</CardHeader>
|
||||
<CardFooter className="flex flex-col items-stretch gap-2">
|
||||
<Button
|
||||
onClick={() => window.location.replace(redirectURI)}
|
||||
onClick={() => (window.location.href = redirectURI)}
|
||||
variant="warning"
|
||||
>
|
||||
{t("continueTitle")}
|
||||
</Button>
|
||||
<Button onClick={() => navigate("/")} variant="outline">
|
||||
<Button onClick={() => navigate("/logout")} variant="outline">
|
||||
{t("cancelTitle")}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
@@ -112,7 +112,7 @@ export const ContinuePage = () => {
|
||||
<CardDescription>{t("continueSubtitle")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardFooter className="flex flex-col items-stretch">
|
||||
<Button onClick={() => window.location.replace(redirectURI)}>
|
||||
<Button onClick={() => (window.location.href = redirectURI)}>
|
||||
{t("continueTitle")}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
|
||||
@@ -12,19 +12,57 @@ import {
|
||||
import { OAuthButton } from "@/components/ui/oauth-button";
|
||||
import { SeperatorWithChildren } from "@/components/ui/separator";
|
||||
import { useAppContext } from "@/context/app-context";
|
||||
import { useUserContext } from "@/context/user-context";
|
||||
import { LoginSchema } from "@/schemas/login-schema";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import axios from "axios";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Navigate } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export const LoginPage = () => {
|
||||
const { configuredProviders, title } = useAppContext();
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
const redirectUri = searchParams.get("redirect_uri");
|
||||
|
||||
console.log("Configured providers:", configuredProviders);
|
||||
const { isLoggedIn } = useUserContext();
|
||||
const { configuredProviders, title } = useAppContext();
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (isLoggedIn) {
|
||||
return <Navigate to="/logout" />;
|
||||
}
|
||||
|
||||
const oauthConfigured =
|
||||
configuredProviders.filter((provider) => provider !== "username").length >
|
||||
0;
|
||||
const userAuthConfigured = configuredProviders.includes("username");
|
||||
|
||||
const loginMutation = useMutation({
|
||||
mutationFn: (values: LoginSchema) => axios.post("/api/login", values),
|
||||
mutationKey: ["login"],
|
||||
onSuccess: (data) => {
|
||||
if (data.data.totpPending) {
|
||||
window.location.replace(`/totp?redirect_uri=${redirectUri}`);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success(t("loginSuccessTitle"), {
|
||||
description: t("loginSuccessSubtitle"),
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
window.location.replace(`/continue?redirect_uri=${redirectUri}`);
|
||||
}, 500);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(t("loginFailTitle"), {
|
||||
description: error.message.includes("429")
|
||||
? t("loginFailRateLimit")
|
||||
: t("loginFailSubtitle"),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="min-w-xs sm:min-w-sm">
|
||||
<CardHeader>
|
||||
@@ -64,7 +102,12 @@ export const LoginPage = () => {
|
||||
{userAuthConfigured && oauthConfigured && (
|
||||
<SeperatorWithChildren>{t("loginDivider")}</SeperatorWithChildren>
|
||||
)}
|
||||
{userAuthConfigured && <LoginForm />}
|
||||
{userAuthConfigured && (
|
||||
<LoginForm
|
||||
onSubmit={(values) => loginMutation.mutate(values)}
|
||||
loading={loginMutation.isPending}
|
||||
/>
|
||||
)}
|
||||
{configuredProviders.length == 0 && (
|
||||
<h3 className="text-center text-xl text-red-600">
|
||||
{t("failedToFetchProvidersTitle")}
|
||||
|
||||
@@ -9,8 +9,11 @@ import {
|
||||
import { useAppContext } from "@/context/app-context";
|
||||
import { useUserContext } from "@/context/user-context";
|
||||
import { capitalize } from "@/lib/utils";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import axios from "axios";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { Navigate } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export const LogoutPage = () => {
|
||||
const { provider, username, email, isLoggedIn } = useUserContext();
|
||||
@@ -21,6 +24,25 @@ export const LogoutPage = () => {
|
||||
return <Navigate to="/login" />;
|
||||
}
|
||||
|
||||
const logoutMutation = useMutation({
|
||||
mutationFn: () => axios.post("/api/logout"),
|
||||
mutationKey: ["logout"],
|
||||
onSuccess: () => {
|
||||
toast.success(t("logoutSuccessTitle"), {
|
||||
description: t("logoutSuccessSubtitle"),
|
||||
});
|
||||
|
||||
setTimeout(async () => {
|
||||
window.location.replace("/login");
|
||||
}, 500);
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t("logoutFailTitle"), {
|
||||
description: t("logoutFailSubtitle"),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="min-w-xs sm:min-w-sm">
|
||||
<CardHeader>
|
||||
@@ -47,14 +69,19 @@ export const LogoutPage = () => {
|
||||
code: <code />,
|
||||
}}
|
||||
values={{
|
||||
username: username,
|
||||
username,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardFooter className="flex flex-col items-stretch">
|
||||
<Button>{t("logoutTitle")}</Button>
|
||||
<Button
|
||||
loading={logoutMutation.isPending}
|
||||
onClick={() => logoutMutation.mutate()}
|
||||
>
|
||||
{t("logoutTitle")}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FormValues, TotpForm } from "@/components/auth/totp-form";
|
||||
import { TotpForm } from "@/components/auth/totp-form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
@@ -8,16 +8,40 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { TotpSchema } from "@/schemas/totp-schema";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import axios from "axios";
|
||||
import { useId } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export const TotpPage = () => {
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
const redirectUri = searchParams.get("redirect_uri");
|
||||
|
||||
const { t } = useTranslation();
|
||||
const formId = useId();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const onSubmit = (data: FormValues) => {
|
||||
console.log("TOTP data:", data);
|
||||
};
|
||||
const totpMutation = useMutation({
|
||||
mutationFn: (values: TotpSchema) => axios.post("/api/totp", values),
|
||||
mutationKey: ["totp"],
|
||||
onSuccess: () => {
|
||||
toast.success(t("totpSuccessTitle"), {
|
||||
description: t("totpSuccessSubtitle"),
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
navigate(`/continue?redirect_uri=${redirectUri}`);
|
||||
}, 500);
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t("totpFailTitle"), {
|
||||
description: t("totpFailSubtitle"),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="min-w-xs sm:min-w-sm">
|
||||
@@ -26,10 +50,14 @@ export const TotpPage = () => {
|
||||
<CardDescription>{t("totpSubtitle")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col items-center">
|
||||
<TotpForm formId={formId} onSubmit={onSubmit} />
|
||||
<TotpForm
|
||||
formId={formId}
|
||||
onSubmit={(values) => totpMutation.mutate(values)}
|
||||
loading={totpMutation.isPending}
|
||||
/>
|
||||
</CardContent>
|
||||
<CardFooter className="flex flex-col items-stretch">
|
||||
<Button form={formId} type="submit">
|
||||
<Button form={formId} type="submit" loading={totpMutation.isPending}>
|
||||
{t("continueTitle")}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
|
||||
@@ -16,12 +16,13 @@ export const UnauthorizedPage = () => {
|
||||
const groupErr = searchParams.get("groupErr");
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
if (!username) {
|
||||
return <Navigate to="/" />;
|
||||
}
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
let i18nKey = "unaothorizedLoginSubtitle";
|
||||
|
||||
if (resource) {
|
||||
@@ -44,8 +45,8 @@ export const UnauthorizedPage = () => {
|
||||
code: <code />,
|
||||
}}
|
||||
values={{
|
||||
username: username,
|
||||
resource: resource,
|
||||
username,
|
||||
resource,
|
||||
}}
|
||||
/>
|
||||
</CardDescription>
|
||||
|
||||
8
frontend/src/schemas/login-schema.ts
Normal file
8
frontend/src/schemas/login-schema.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const loginSchema = z.object({
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
export type LoginSchema = z.infer<typeof loginSchema>;
|
||||
7
frontend/src/schemas/totp-schema.ts
Normal file
7
frontend/src/schemas/totp-schema.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const totpSchema = z.object({
|
||||
code: z.string(),
|
||||
});
|
||||
|
||||
export type TotpSchema = z.infer<typeof totpSchema>;
|
||||
Reference in New Issue
Block a user