headplane/app/routes/auth/login.tsx

187 lines
4.7 KiB
TypeScript
Raw Normal View History

import { useEffect } from 'react';
import {
type ActionFunctionArgs,
type LoaderFunctionArgs,
redirect,
useSearchParams,
} from 'react-router';
2024-12-31 10:30:14 +05:30
import { Form, useActionData, useLoaderData } from 'react-router';
import Button from '~/components/Button';
import Card from '~/components/Card';
import Code from '~/components/Code';
2025-01-28 16:02:47 -05:00
import Input from '~/components/Input';
2025-03-22 01:36:27 -04:00
import type { LoadContext } from '~/server';
2024-12-31 10:31:50 +05:30
import type { Key } from '~/types';
2024-03-25 17:51:11 -04:00
2025-03-22 01:36:27 -04:00
export async function loader({
request,
context,
}: LoaderFunctionArgs<LoadContext>) {
const qp = new URL(request.url).searchParams;
const state = qp.get('s');
try {
2025-03-22 01:36:27 -04:00
const session = await context.sessions.auth(request);
if (session.has('api_key')) {
return redirect('/machines');
}
} catch {}
2024-03-25 17:51:11 -04:00
2025-03-22 01:36:27 -04:00
const disableApiKeyLogin = context.config.oidc?.disable_api_key_login;
if (context.oidc && disableApiKeyLogin) {
// Prevents automatic redirect loop if OIDC is enabled and API key login is disabled
// Since logging out would just log back in based on the redirects
if (state !== 'logout') {
return redirect('/oidc/start');
}
2025-03-22 01:36:27 -04:00
}
return {
2025-03-22 01:36:27 -04:00
oidc: context.oidc,
disableApiKeyLogin,
state,
2024-12-31 10:30:14 +05:30
};
2024-03-25 17:51:11 -04:00
}
2025-03-22 01:36:27 -04:00
export async function action({
request,
context,
}: ActionFunctionArgs<LoadContext>) {
2024-12-31 10:30:14 +05:30
const formData = await request.formData();
const oidcStart = formData.get('oidc-start');
2025-03-22 01:36:27 -04:00
const session = await context.sessions.getOrCreate(request);
2024-03-30 02:44:06 -04:00
if (oidcStart) {
if (!context.oidc) {
2025-03-22 01:36:27 -04:00
throw new Error('OIDC is not enabled');
}
return redirect('/oidc/start');
2024-03-30 02:44:06 -04:00
}
2024-12-31 10:30:14 +05:30
const apiKey = String(formData.get('api-key'));
2024-03-26 11:11:12 -04:00
// Test the API key
try {
2025-03-22 01:36:27 -04:00
const apiKeys = await context.client.get<{ apiKeys: Key[] }>(
'v1/apikey',
apiKey,
);
2024-12-31 10:30:14 +05:30
const key = apiKeys.apiKeys.find((k) => apiKey.startsWith(k.prefix));
2024-03-30 02:44:06 -04:00
if (!key) {
2025-03-22 01:36:27 -04:00
return {
error: 'Invalid API key',
};
2024-03-30 02:44:06 -04:00
}
2024-12-31 10:30:14 +05:30
const expiry = new Date(key.expiration);
const expiresIn = expiry.getTime() - Date.now();
const expiresDays = Math.round(expiresIn / 1000 / 60 / 60 / 24);
2024-03-30 02:44:06 -04:00
2025-03-22 01:36:27 -04:00
session.set('state', 'auth');
session.set('api_key', apiKey);
2024-03-30 02:44:06 -04:00
session.set('user', {
subject: 'unknown-non-oauth',
2024-03-30 02:44:06 -04:00
name: key.prefix,
2024-05-15 21:54:02 -04:00
email: `${expiresDays.toString()} days`,
2024-12-31 10:30:14 +05:30
});
2024-03-30 02:44:06 -04:00
return redirect('/machines', {
headers: {
2025-03-22 01:36:27 -04:00
'Set-Cookie': await context.sessions.commit(session, {
2024-05-15 21:54:02 -04:00
maxAge: expiresIn,
}),
},
2024-12-31 10:30:14 +05:30
});
2024-07-10 19:36:13 -04:00
} catch {
2024-12-06 11:58:17 -05:00
return {
2024-05-15 21:54:02 -04:00
error: 'Invalid API key',
2024-12-31 10:30:14 +05:30
};
2024-03-26 11:11:12 -04:00
}
}
2024-03-25 17:51:11 -04:00
export default function Page() {
const { state, disableApiKeyLogin, oidc } = useLoaderData<typeof loader>();
2024-12-31 10:30:14 +05:30
const actionData = useActionData<typeof action>();
const [params] = useSearchParams();
useEffect(() => {
// State is a one time thing, we need to remove it after it has
// been consumed to prevent logic loops.
if (state !== null) {
const searchParams = new URLSearchParams(params);
searchParams.delete('s');
// Replacing because it's not a navigation, just a cleanup of the URL
// We can't use the useSearchParams method since it revalidates
// which will trigger a full reload
const newUrl = searchParams.toString()
? `{${window.location.pathname}?${searchParams.toString()}`
: window.location.pathname;
window.history.replaceState(null, '', newUrl);
}
}, [state, params]);
if (state === 'logout') {
return (
<div className="flex min-h-screen items-center justify-center">
<Card className="max-w-sm m-4 sm:m-0" variant="raised">
<Card.Title>You have been logged out</Card.Title>
<Card.Text>
You can now close this window. If you would like to log in again,
please refresh the page.
</Card.Text>
</Card>
</div>
);
}
2024-03-25 17:51:11 -04:00
return (
2024-05-15 21:54:02 -04:00
<div className="flex min-h-screen items-center justify-center">
<Card className="max-w-sm m-4 sm:m-0" variant="raised">
2024-12-31 10:30:14 +05:30
<Card.Title>Welcome to Headplane</Card.Title>
{!disableApiKeyLogin ? (
2024-12-31 10:30:14 +05:30
<Form method="post">
2025-02-04 17:21:03 -05:00
<Card.Text>
2024-12-31 10:30:14 +05:30
Enter an API key to authenticate with Headplane. You can generate
one by running <Code>headscale apikeys create</Code> in your
terminal.
</Card.Text>
{actionData?.error ? (
<p className="text-red-500 text-sm mb-2">{actionData.error}</p>
) : undefined}
2025-01-28 16:02:47 -05:00
<Input
2024-12-31 10:30:14 +05:30
isRequired
2025-02-04 17:21:03 -05:00
labelHidden
2024-12-31 10:30:14 +05:30
label="API Key"
name="api-key"
placeholder="API Key"
type="password"
2025-02-04 17:21:03 -05:00
className="mt-4 mb-2"
2024-12-31 10:30:14 +05:30
/>
2025-02-04 17:21:03 -05:00
<Button className="w-full" variant="heavy" type="submit">
Sign In
2024-12-31 10:30:14 +05:30
</Button>
</Form>
) : undefined}
{oidc ? (
2024-12-31 10:30:14 +05:30
<Form method="POST">
<input type="hidden" name="oidc-start" value="true" />
2025-02-04 17:21:03 -05:00
<Button
className="w-full mt-2"
variant={disableApiKeyLogin ? 'heavy' : 'light'}
2025-02-04 17:21:03 -05:00
type="submit"
>
Single Sign-On
2024-12-31 10:30:14 +05:30
</Button>
</Form>
) : undefined}
2024-03-30 02:46:21 -04:00
</Card>
2024-03-25 17:51:11 -04:00
</div>
2024-12-31 10:30:14 +05:30
);
2024-03-25 17:51:11 -04:00
}