46 lines
1.9 KiB
TypeScript
46 lines
1.9 KiB
TypeScript
import { redirect, useActionData } from 'react-router';
|
|
import { ClientResponseError } from 'pocketbase';
|
|
import type { Route } from './+types/login';
|
|
import { LoginPanel } from '~/components/auth/form/login-panel';
|
|
import { LoginShowcase } from '~/components/auth/showcase/login-showcase';
|
|
import { LoadingScreen } from '~/components/ui/loading-screen';
|
|
import { LOGIN_ERRORS } from '~/data/auth/constants';
|
|
import { ROUTES } from '~/data/routes';
|
|
import { getErrorMessage } from '~/lib/errors';
|
|
import { loginSchema } from '~/schemas/auth/login';
|
|
import { isSignedIn, signIn } from '~/services/auth';
|
|
import type { LoginFailure } from '~/types/auth';
|
|
|
|
export async function clientLoader() {
|
|
return isSignedIn() ? redirect(ROUTES.home) : null;
|
|
}
|
|
|
|
export async function clientAction({ request }: Route.ClientActionArgs) {
|
|
const parsed = loginSchema.safeParse(await request.json());
|
|
if (!parsed.success) return { error: parsed.error.issues[0]?.message ?? LOGIN_ERRORS.mismatch, invalidCredentials: false } satisfies LoginFailure;
|
|
|
|
const { email, password, remember } = parsed.data;
|
|
try {
|
|
await signIn(email, password, remember);
|
|
} catch (error) {
|
|
const status = error instanceof ClientResponseError ? error.status : undefined;
|
|
if (status === 400) return { error: LOGIN_ERRORS.mismatch, invalidCredentials: true } satisfies LoginFailure;
|
|
return { error: status === 0 ? LOGIN_ERRORS.offline : getErrorMessage(error), invalidCredentials: false } satisfies LoginFailure;
|
|
}
|
|
return redirect(ROUTES.home);
|
|
}
|
|
|
|
export function HydrateFallback() {
|
|
return <LoadingScreen />;
|
|
}
|
|
|
|
export default function Login() {
|
|
const failure = useActionData<typeof clientAction>();
|
|
return (
|
|
<div className='flex min-h-screen flex-col bg-background split:flex-row'>
|
|
<LoginPanel failure={failure} />
|
|
<LoginShowcase />
|
|
</div>
|
|
);
|
|
}
|