auth: work on adding google auth via invite

This commit is contained in:
2025-03-14 01:08:42 -07:00
parent 073bf65094
commit 02ff13e4d3
19 changed files with 577 additions and 100 deletions

13
src/lib/assets/google.svg Normal file
View File

@@ -0,0 +1,13 @@
<svg width="40" height="40" viewBox="10 10 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_710_6221)">
<path d="M29.6 20.2273C29.6 19.5182 29.5364 18.8364 29.4182 18.1818H20V22.05H25.3818C25.15 23.3 24.4455 24.3591 23.3864 25.0682V27.5773H26.6182C28.5091 25.8364 29.6 23.2727 29.6 20.2273Z" fill="#4285F4"/>
<path d="M20 30C22.7 30 24.9636 29.1045 26.6181 27.5773L23.3863 25.0682C22.4909 25.6682 21.3454 26.0227 20 26.0227C17.3954 26.0227 15.1909 24.2636 14.4045 21.9H11.0636V24.4909C12.7091 27.7591 16.0909 30 20 30Z" fill="#34A853"/>
<path d="M14.4045 21.9C14.2045 21.3 14.0909 20.6591 14.0909 20C14.0909 19.3409 14.2045 18.7 14.4045 18.1V15.5091H11.0636C10.3864 16.8591 10 18.3864 10 20C10 21.6136 10.3864 23.1409 11.0636 24.4909L14.4045 21.9Z" fill="#FBBC04"/>
<path d="M20 13.9773C21.4681 13.9773 22.7863 14.4818 23.8227 15.4727L26.6909 12.6045C24.9591 10.9909 22.6954 10 20 10C16.0909 10 12.7091 12.2409 11.0636 15.5091L14.4045 18.1C15.1909 15.7364 17.3954 13.9773 20 13.9773Z" fill="#E94235"/>
</g>
<defs>
<clipPath id="clip0_710_6221">
<rect width="20" height="20" fill="white" transform="translate(10 10)"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -2,14 +2,16 @@
import { LucideLoaderCircle } from 'lucide-svelte';
import { Button } from '$lib/components/ui/button';
import { cn } from '$lib/utils.js';
import googleIcon from '$lib/assets/google.svg';
let { class: className, ...rest }: { 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);
</script>
<div class={cn('flex gap-6', className)} {...rest}>
<form method="get" action="/auth/authentik">
<form method="get" action="/auth/authentik{inviteToken ? `?invite=${inviteToken}` : ''}">
<input type="hidden" value={inviteToken} name="invite" />
<Button
type="submit"
onclick={() => {
@@ -28,4 +30,24 @@
Sign in with Authentik
</Button>
</form>
<form method="get" action="/auth/google">
<input type="hidden" value={inviteToken} name="invite" />
<Button
type="submit"
onclick={() => {
isLoading = true;
}}
>
{#if isLoading}
<LucideLoaderCircle class="mr-2 h-4 w-4 animate-spin" />
{:else}
<img
class="mr-2 h-4 w-4"
alt="Google Logo"
src={googleIcon}
/>
{/if}
Sign in with Google
</Button>
</form>
</div>

View File

@@ -5,6 +5,7 @@ import { db } from '$lib/server/db';
import * as table from '$lib/server/db/schema';
import type { RequestEvent } from '@sveltejs/kit';
import { dev } from '$app/environment';
import { env } from '$env/dynamic/private';
const DAY_IN_MS = 1000 * 60 * 60 * 24;
@@ -79,4 +80,8 @@ export async function validateSession(sessionId: string) {
return { session, user };
}
export function isValidInviteToken(inviteToken: string) {
return inviteToken === env.INVITE_TOKEN;
}
export type SessionValidationResult = Awaited<ReturnType<typeof validateSession>>;

View File

@@ -3,6 +3,7 @@ import { relations } from 'drizzle-orm';
export const users = sqliteTable('users', {
id: text('id').primaryKey(),
authSource: text('auth_source').notNull().default('authentik'),
username: text('username').notNull(),
name: text('name').notNull(),
});

View File

@@ -2,7 +2,7 @@ import { ipAllocations, users, devices } from './schema';
import { eq } from 'drizzle-orm';
import assert from 'node:assert';
import { drizzle } from 'drizzle-orm/libsql';
import * as schema from '$lib/server/db/schema';
import * as schema from './schema';
assert(process.env.DATABASE_URL, 'DATABASE_URL is not set');
const db = drizzle(process.env.DATABASE_URL, { schema });

View File

@@ -1,4 +1,4 @@
import { Authentik } from 'arctic';
import { Authentik, Google } from 'arctic';
import { env } from '$env/dynamic/private';
export const authentik = new Authentik(
@@ -7,3 +7,9 @@ export const authentik = new Authentik(
env.AUTH_CLIENT_SECRET,
`${env.ORIGIN}/auth/authentik/callback`,
);
export const google = new Google(
env.GOOGLE_CLIENT_ID,
env.GOOGLE_CLIENT_SECRET,
`${env.ORIGIN}/auth/google/callback`,
);

View File

@@ -1,27 +1,28 @@
import { createSession, setSessionTokenCookie } from "$lib/server/auth";
import { authentik } from "$lib/server/oauth";
import { decodeIdToken } from "arctic";
import { createSession, setSessionTokenCookie } from '$lib/server/auth';
import { authentik } from '$lib/server/oauth';
import { decodeIdToken } from 'arctic';
import type { RequestEvent } from "@sveltejs/kit";
import type { OAuth2Tokens } from "arctic";
import type { RequestEvent } from '@sveltejs/kit';
import type { OAuth2Tokens } from 'arctic';
import { db } from '$lib/server/db';
import { eq } from 'drizzle-orm';
import * as table from '$lib/server/db/schema';
export async function GET(event: RequestEvent): Promise<Response> {
const code = event.url.searchParams.get("code");
const state = event.url.searchParams.get("state");
const storedState = event.cookies.get("authentik_oauth_state") ?? null;
const codeVerifier = event.cookies.get("authentik_code_verifier") ?? null;
const code = event.url.searchParams.get('code');
const state = event.url.searchParams.get('state');
const storedState = event.cookies.get('authentik_oauth_state') ?? null;
const codeVerifier = event.cookies.get('authentik_code_verifier') ?? null;
if (code === null || state === null || storedState === null || codeVerifier === null) {
return new Response(null, {
status: 400
status: 400,
});
}
if (state !== storedState) {
return new Response(null, {
status: 400
status: 400,
});
}
@@ -31,15 +32,19 @@ export async function GET(event: RequestEvent): Promise<Response> {
} catch (e) {
// Invalid code or client credentials
return new Response(null, {
status: 400
status: 400,
});
}
const claims = decodeIdToken(tokens.idToken()) as { sub: string, preferred_username: string, name: string };
console.log("claims", claims);
const claims = decodeIdToken(tokens.idToken()) as {
sub: string;
preferred_username: string;
name: string;
};
console.log('claims', claims);
const userId: string = claims.sub;
const username: string = claims.preferred_username;
const existingUser = await db.query.users.findFirst({where: eq(table.users.id, userId)});
const existingUser = await db.query.users.findFirst({ where: eq(table.users.id, userId) });
if (existingUser) {
const session = await createSession(existingUser.id);
@@ -47,13 +52,14 @@ export async function GET(event: RequestEvent): Promise<Response> {
return new Response(null, {
status: 302,
headers: {
Location: "/"
}
Location: '/',
},
});
}
const user: table.User = {
id: userId,
authSource: 'authentik',
username,
name: claims.name as string,
};
@@ -65,14 +71,14 @@ export async function GET(event: RequestEvent): Promise<Response> {
} catch (e) {
console.error('failed to create user', e);
return new Response(null, {
status: 500
status: 500,
});
}
return new Response(null, {
status: 302,
headers: {
Location: "/"
}
Location: '/',
},
});
}

View File

@@ -0,0 +1,38 @@
import type { RequestHandler } from './$types';
import { generateCodeVerifier, generateState } from 'arctic';
import { google } from '$lib/server/oauth';
export const GET: RequestHandler = ({ url, cookies }) => {
const inviteToken = url.searchParams.get('invite');
const state = generateState();
const codeVerifier = generateCodeVerifier();
const scopes = ['openid', 'profile', 'email'];
const authUrl = google.createAuthorizationURL(state, codeVerifier, scopes);
cookies.set('google_oauth_state', state, {
path: '/',
httpOnly: true,
maxAge: 60 * 10, // 10 minutes
sameSite: 'lax',
});
cookies.set('google_code_verifier', codeVerifier, {
path: '/',
httpOnly: true,
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,
headers: {
Location: authUrl.toString(),
},
});
};

View File

@@ -0,0 +1,97 @@
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 type { OAuth2Tokens } from 'arctic';
export const GET: RequestHandler = 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;
if (code === null || state === null || storedState === null || codeVerifier === null) {
return new Response(null, {
status: 400,
});
}
let tokens: OAuth2Tokens;
try {
tokens = await google.validateAuthorizationCode(code, codeVerifier);
} catch (e) {
if (e instanceof arctic.OAuth2RequestError) {
// Invalid authorization code, credentials, or redirect URI
console.debug(e);
console.debug(state)
return new Response(null, {
status: 400,
});
}
if (e instanceof arctic.ArcticFetchError) {
// Failed to call `fetch()`
console.debug(e.cause);
return new Response(null, {
status: 400,
});
}
}
const accessToken = tokens.accessToken();
const idToken = tokens.idToken();
const claims = arctic.decodeIdToken(idToken) as {
sub: string;
email: string;
name: string;
};
console.log('claims', claims);
const userId = claims.sub;
const existingUser = await db.query.users.findFirst({ where: eq(table.users.id, userId) });
if (existingUser) {
const session = await createSession(existingUser.id);
setSessionTokenCookie(event, session.id, session.expiresAt);
return new Response(null, {
status: 302,
headers: {
Location: '/',
},
});
}
// TODO: proper error page
if (inviteToken === null || !isValidInviteToken(inviteToken)) {
return new Response(null, {
status: 400,
});
}
const user: table.User = {
id: userId,
authSource: 'google',
username: claims.email,
name: claims.name,
};
// TODO: proper error handling, delete cookies
await db.insert(table.users).values(user);
console.log('created user', user, 'with invite token', inviteToken);
const session = await createSession(user.id);
setSessionTokenCookie(event, session.id, session.expiresAt);
return new Response(null, {
status: 302,
headers: {
Location: '/',
},
});
};

View File

@@ -0,0 +1,7 @@
import type { LayoutServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';
import { isValidInviteToken } from '$lib/server/auth';
export const load: LayoutServerLoad = ({ params }) => {
if (!isValidInviteToken(params.id)) redirect(307, '/')
};

View File

@@ -0,0 +1,16 @@
<script lang="ts">
import { AuthForm } from '$lib/components/app/auth-form';
import { page } from '$app/state';
let inviteToken = page.params.id;
</script>
<svelte:head>
<title>You are Invited to VPGen</title>
</svelte:head>
<h1 class="mb-2 scroll-m-20 text-center text-3xl font-extrabold tracking-tight lg:text-4xl">
Welcome to VPGen
</h1>
<AuthForm inviteToken={inviteToken} />