Compare commits
3 Commits
318d453963
...
190b1d0c90
Author | SHA1 | Date | |
---|---|---|---|
190b1d0c90 | |||
5b72ab28dd | |||
8f20c168a2 |
13
README.md
13
README.md
@ -18,7 +18,7 @@ and [wg-quick](https://www.wireguard.com/quickstart/) for standalone setups.
|
||||
## Development
|
||||
|
||||
Development uses bun.
|
||||
An additional prepare step is needed to set up typia for type validation.
|
||||
An additional prepare step is needed to set up typia for type validation.
|
||||
|
||||
For example .env settings, see [.env.example](.env.example)
|
||||
|
||||
@ -27,3 +27,14 @@ bun install
|
||||
bun run prepare
|
||||
bun run dev
|
||||
```
|
||||
|
||||
## To Do
|
||||
|
||||
- [ ] Proper invite page
|
||||
- [ ] Proper error page for login without invite
|
||||
- [ ] Support file provider (for wg-quick)
|
||||
- [ ] Fix accessibility issues (lighthouse)
|
||||
- [ ] Add title to profile page (lighthouse)
|
||||
- [ ] wg-quick scripts (maybe?)
|
||||
- [ ] Get rid of api routes (maybe?)
|
||||
- [ ] Get rid of custom result types (maybe?)
|
||||
|
@ -4,21 +4,21 @@
|
||||
import { cn } from '$lib/utils.js';
|
||||
import googleIcon from '$lib/assets/google.svg';
|
||||
|
||||
let { inviteToken, class: className, ...rest }: { inviteToken?: string; class?: string; rest?: { [p: string]: unknown } } = $props();
|
||||
let { inviteToken, class: className, ...rest }: {
|
||||
inviteToken?: string;
|
||||
class?: string;
|
||||
rest?: { [p: string]: unknown }
|
||||
} = $props();
|
||||
|
||||
let isLoading = $state(false);
|
||||
let submitted = $state(false);
|
||||
</script>
|
||||
|
||||
<div class={cn('flex gap-6', className)} {...rest}>
|
||||
<form method="get" action="/auth/authentik{inviteToken ? `?invite=${inviteToken}` : ''}">
|
||||
<form method="get" onsubmit={() => submitted = true}
|
||||
action="/auth/authentik{inviteToken ? `?invite=${inviteToken}` : ''}">
|
||||
<input type="hidden" value={inviteToken} name="invite" />
|
||||
<Button
|
||||
type="submit"
|
||||
onclick={() => {
|
||||
isLoading = true;
|
||||
}}
|
||||
>
|
||||
{#if isLoading}
|
||||
<Button type="submit" disabled={submitted}>
|
||||
{#if submitted}
|
||||
<LucideLoaderCircle class="mr-2 h-4 w-4 animate-spin" />
|
||||
{:else}
|
||||
<img
|
||||
@ -30,15 +30,11 @@
|
||||
Sign in with Authentik
|
||||
</Button>
|
||||
</form>
|
||||
<form method="get" action="/auth/google">
|
||||
<form method="get" onsubmit={() => submitted = true}
|
||||
action="/auth/google{inviteToken ? `?invite=${inviteToken}` : ''}">
|
||||
<input type="hidden" value={inviteToken} name="invite" />
|
||||
<Button
|
||||
type="submit"
|
||||
onclick={() => {
|
||||
isLoading = true;
|
||||
}}
|
||||
>
|
||||
{#if isLoading}
|
||||
<Button type="submit" disabled={submitted}>
|
||||
{#if submitted}
|
||||
<LucideLoaderCircle class="mr-2 h-4 w-4 animate-spin" />
|
||||
{:else}
|
||||
<img
|
||||
|
@ -3,7 +3,7 @@ import { sha256 } from '@oslojs/crypto/sha2';
|
||||
import { encodeBase32LowerCaseNoPadding, encodeHexLowerCase } from '@oslojs/encoding';
|
||||
import { db } from '$lib/server/db';
|
||||
import * as table from '$lib/server/db/schema';
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
import type { Cookies } from '@sveltejs/kit';
|
||||
import { dev } from '$app/environment';
|
||||
import { env } from '$env/dynamic/private';
|
||||
|
||||
@ -22,14 +22,14 @@ export async function createSession(userId: string): Promise<table.Session> {
|
||||
const session: table.Session = {
|
||||
id: sessionId,
|
||||
userId,
|
||||
expiresAt: new Date(Date.now() + DAY_IN_MS * 30)
|
||||
expiresAt: new Date(Date.now() + DAY_IN_MS * 30),
|
||||
};
|
||||
await db.insert(table.sessions).values(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
export function setSessionTokenCookie(event: RequestEvent, sessionId: string, expiresAt: Date) {
|
||||
event.cookies.set(sessionCookieName, sessionId, {
|
||||
export function setSessionTokenCookie(cookies: Cookies, sessionId: string, expiresAt: Date) {
|
||||
cookies.set(sessionCookieName, sessionId, {
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
httpOnly: true,
|
||||
@ -42,16 +42,21 @@ export async function invalidateSession(sessionId: string): Promise<void> {
|
||||
await db.delete(table.sessions).where(eq(table.sessions.id, sessionId));
|
||||
}
|
||||
|
||||
export function deleteSessionTokenCookie(event: RequestEvent) {
|
||||
event.cookies.delete(sessionCookieName, { path: '/' });
|
||||
export function deleteSessionTokenCookie(cookies: Cookies) {
|
||||
cookies.delete(sessionCookieName, { path: '/' });
|
||||
}
|
||||
|
||||
export async function validateSession(sessionId: string) {
|
||||
const [result] = await db
|
||||
.select({
|
||||
// Adjust user table here to tweak returned data
|
||||
user: { id: table.users.id, authSource: table.users.authSource, username: table.users.username, name: table.users.name },
|
||||
session: table.sessions
|
||||
user: {
|
||||
id: table.users.id,
|
||||
authSource: table.users.authSource,
|
||||
username: table.users.username,
|
||||
name: table.users.name,
|
||||
},
|
||||
session: table.sessions,
|
||||
})
|
||||
.from(table.sessions)
|
||||
.innerJoin(table.users, eq(table.sessions.userId, table.users.id))
|
||||
|
@ -1,14 +1,14 @@
|
||||
import { fail, redirect } from "@sveltejs/kit";
|
||||
import { invalidateSession, deleteSessionTokenCookie } from "$lib/server/auth";
|
||||
import type { Actions } from "./$types";
|
||||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import { invalidateSession, deleteSessionTokenCookie } from '$lib/server/auth';
|
||||
import type { Actions } from './$types';
|
||||
|
||||
export const actions: Actions = {
|
||||
logout: async (event) => {
|
||||
if (event.locals.session === null) {
|
||||
logout: async ({ locals, cookies }) => {
|
||||
if (locals.session === null) {
|
||||
return fail(401);
|
||||
}
|
||||
await invalidateSession(event.locals.session.id);
|
||||
deleteSessionTokenCookie(event);
|
||||
return redirect(302, "/");
|
||||
}
|
||||
await invalidateSession(locals.session.id);
|
||||
deleteSessionTokenCookie(cookies);
|
||||
redirect(302, '/');
|
||||
},
|
||||
};
|
||||
|
@ -48,7 +48,7 @@ export async function GET(event: RequestEvent): Promise<Response> {
|
||||
|
||||
if (existingUser) {
|
||||
const session = await createSession(existingUser.id);
|
||||
setSessionTokenCookie(event, session.id, session.expiresAt);
|
||||
setSessionTokenCookie(event.cookies, session.id, session.expiresAt);
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
@ -67,7 +67,7 @@ export async function GET(event: RequestEvent): Promise<Response> {
|
||||
try {
|
||||
await db.insert(table.users).values(user);
|
||||
const session = await createSession(user.id);
|
||||
setSessionTokenCookie(event, session.id, session.expiresAt);
|
||||
setSessionTokenCookie(event.cookies, session.id, session.expiresAt);
|
||||
} catch (e) {
|
||||
console.error('failed to create user', e);
|
||||
return new Response(null, {
|
||||
|
@ -8,7 +8,7 @@ export const GET: RequestHandler = ({ url, cookies }) => {
|
||||
const state = generateState();
|
||||
const codeVerifier = generateCodeVerifier();
|
||||
const scopes = ['openid', 'profile', 'email'];
|
||||
const authUrl = google.createAuthorizationURL(state, codeVerifier, scopes);
|
||||
const authUrl = google.createAuthorizationURL(state + inviteToken, codeVerifier, scopes);
|
||||
|
||||
cookies.set('google_oauth_state', state, {
|
||||
path: '/',
|
||||
@ -22,12 +22,6 @@ export const GET: RequestHandler = ({ url, cookies }) => {
|
||||
maxAge: 60 * 10, // 10 minutes
|
||||
sameSite: 'lax',
|
||||
});
|
||||
if (inviteToken !== null) cookies.set('invite_token', inviteToken, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
maxAge: 60 * 10, // 10 minutes
|
||||
sameSite: 'lax',
|
||||
});
|
||||
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
|
@ -1,25 +1,30 @@
|
||||
import type { RequestHandler } from './$types';
|
||||
import * as arctic from 'arctic';
|
||||
import { google } from '$lib/server/oauth';
|
||||
import { db } from '$lib/server/db';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import * as table from '$lib/server/db/schema';
|
||||
import { createSession, isValidInviteToken, setSessionTokenCookie } from '$lib/server/auth';
|
||||
import { db } from '$lib/server/db';
|
||||
import * as table from '$lib/server/db/schema';
|
||||
import { google } from '$lib/server/oauth';
|
||||
import { error, redirect } from '@sveltejs/kit';
|
||||
import type { OAuth2Tokens } from 'arctic';
|
||||
import * as arctic from 'arctic';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { assertGuard } from 'typia';
|
||||
import type { PageServerLoad } from './$types';
|
||||
|
||||
export const GET: RequestHandler = async (event) => {
|
||||
export const load: PageServerLoad = async (event) => {
|
||||
const { url, cookies } = event;
|
||||
|
||||
const code = url.searchParams.get('code');
|
||||
const state = url.searchParams.get('state');
|
||||
const storedState = cookies.get('google_oauth_state') ?? null;
|
||||
const codeVerifier = cookies.get('google_code_verifier', ) ?? null;
|
||||
const inviteToken = cookies.get('invite_token') ?? null;
|
||||
const codeVerifier = cookies.get('google_code_verifier') ?? null;
|
||||
|
||||
if (code === null || state === null || storedState === null || codeVerifier === null) {
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
error(400, 'Missing url parameters');
|
||||
}
|
||||
|
||||
const stateGeneratedToken = state.slice(0, storedState.length);
|
||||
const stateInviteToken = state.slice(storedState.length);
|
||||
if (stateGeneratedToken !== storedState) {
|
||||
error(400, 'Invalid state in url');
|
||||
}
|
||||
|
||||
let tokens: OAuth2Tokens;
|
||||
@ -28,20 +33,14 @@ export const GET: RequestHandler = async (event) => {
|
||||
} catch (e) {
|
||||
if (e instanceof arctic.OAuth2RequestError) {
|
||||
console.debug('Arctic: OAuth: invalid authorization code, credentials, or redirect URI', e);
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
throw error(400, 'Invalid authorization code');
|
||||
}
|
||||
if (e instanceof arctic.ArcticFetchError) {
|
||||
console.debug('Arctic: failed to call `fetch()`', e);
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
error(400, 'Failed to validate authorization code');
|
||||
}
|
||||
|
||||
return new Response(null, {
|
||||
status: 500,
|
||||
});
|
||||
console.error('Unxepcted error validating authorization code', code, e);
|
||||
error(500);
|
||||
}
|
||||
|
||||
const idToken = tokens.idToken();
|
||||
@ -60,20 +59,14 @@ export const GET: RequestHandler = async (event) => {
|
||||
|
||||
if (existingUser) {
|
||||
const session = await createSession(existingUser.id);
|
||||
setSessionTokenCookie(event, session.id, session.expiresAt);
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: '/',
|
||||
},
|
||||
});
|
||||
setSessionTokenCookie(cookies, session.id, session.expiresAt);
|
||||
redirect(302, '/');
|
||||
}
|
||||
|
||||
// TODO: proper error page
|
||||
if (inviteToken === null || !isValidInviteToken(inviteToken)) {
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
if (!isValidInviteToken(stateInviteToken)) {
|
||||
const message =
|
||||
stateInviteToken.length === 0 ? 'sign up with an invite link first' : 'invalid invite link';
|
||||
error(403, 'Not Authorized: ' + message);
|
||||
}
|
||||
|
||||
const user: table.User = {
|
||||
@ -85,16 +78,11 @@ export const GET: RequestHandler = async (event) => {
|
||||
|
||||
// TODO: proper error handling, delete cookies
|
||||
await db.insert(table.users).values(user);
|
||||
console.log('created user', user, 'with invite token', inviteToken);
|
||||
console.log('created user', user, 'with invite token', stateInviteToken);
|
||||
|
||||
const session = await createSession(user.id);
|
||||
|
||||
setSessionTokenCookie(event, session.id, session.expiresAt);
|
||||
setSessionTokenCookie(cookies, session.id, session.expiresAt);
|
||||
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: '/',
|
||||
},
|
||||
});
|
||||
redirect(302, '/');
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user