auth: refactor common oauth provider logic, add options to disable providers and require invites
All checks were successful
ci/woodpecker/push/build-image Pipeline was successful
All checks were successful
ci/woodpecker/push/build-image Pipeline was successful
This commit is contained in:
9
src/lib/auth.ts
Normal file
9
src/lib/auth.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { envToBool } from '$lib/utils';
|
||||
import { env } from '$env/dynamic/public';
|
||||
|
||||
export type AuthProvider = 'authentik' | 'google';
|
||||
|
||||
export const enabledAuthProviders: Record<AuthProvider, boolean> = {
|
||||
authentik: envToBool(env.PUBLIC_AUTH_AUTHENTIK_ENABLE),
|
||||
google: envToBool(env.PUBLIC_AUTH_GOOGLE_ENABLE),
|
||||
};
|
@@ -3,22 +3,24 @@
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { cn } from '$lib/utils.js';
|
||||
import googleIcon from '$lib/assets/google.svg';
|
||||
import { enabledAuthProviders } from '$lib/auth';
|
||||
|
||||
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}` : ''}">
|
||||
{#if enabledAuthProviders.authentik }
|
||||
<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 +32,13 @@
|
||||
Sign in with Authentik
|
||||
</Button>
|
||||
</form>
|
||||
<form method="get" action="/auth/google">
|
||||
{/if}
|
||||
{#if enabledAuthProviders.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
|
||||
@@ -50,4 +50,5 @@
|
||||
Sign in with Google
|
||||
</Button>
|
||||
</form>
|
||||
{/if}
|
||||
</div>
|
||||
|
@@ -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))
|
||||
@@ -81,7 +86,7 @@ export async function validateSession(sessionId: string) {
|
||||
}
|
||||
|
||||
export function isValidInviteToken(inviteToken: string) {
|
||||
return inviteToken === env.INVITE_TOKEN;
|
||||
return inviteToken === env.AUTH_INVITE_TOKEN;
|
||||
}
|
||||
|
||||
export type SessionValidationResult = Awaited<ReturnType<typeof validateSession>>;
|
||||
|
34
src/lib/server/oauth-providers/authentik.ts
Normal file
34
src/lib/server/oauth-providers/authentik.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { envToBool } from '$lib/utils';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { Authentik, decodeIdToken } from 'arctic';
|
||||
import { assertGuard } from 'typia';
|
||||
import type { IOAuthProvider } from '$lib/server/oauth';
|
||||
|
||||
const authentikProvider = new Authentik(
|
||||
env.AUTH_AUTHENTIK_DOMAIN,
|
||||
env.AUTH_AUTHENTIK_CLIENT_ID,
|
||||
env.AUTH_AUTHENTIK_CLIENT_SECRET,
|
||||
`${env.ORIGIN}/auth/authentik/callback`,
|
||||
);
|
||||
|
||||
export const authentik: IOAuthProvider = {
|
||||
requireInvite: envToBool(env.AUTH_AUTHENTIK_REQUIRE_INVITE, true),
|
||||
createAuthorizationURL: (state: string, codeVerifier: string) => {
|
||||
const scopes = ['openid', 'profile'];
|
||||
return authentikProvider.createAuthorizationURL(state, codeVerifier, scopes);
|
||||
},
|
||||
validateAuthorizationCode: async (code: string, codeVerifier: string) => {
|
||||
const tokens = await authentikProvider.validateAuthorizationCode(code, codeVerifier);
|
||||
const claims = decodeIdToken(tokens.idToken());
|
||||
assertGuard<{
|
||||
sub: string;
|
||||
name: string;
|
||||
preferred_username: string;
|
||||
}>(claims);
|
||||
return {
|
||||
sub: claims.sub,
|
||||
name: claims.name,
|
||||
username: claims.preferred_username,
|
||||
};
|
||||
},
|
||||
};
|
33
src/lib/server/oauth-providers/google.ts
Normal file
33
src/lib/server/oauth-providers/google.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { decodeIdToken, Google } from 'arctic';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { envToBool } from '$lib/utils';
|
||||
import { assertGuard } from 'typia';
|
||||
import type { IOAuthProvider } from '$lib/server/oauth';
|
||||
|
||||
const googleProvider = new Google(
|
||||
env.AUTH_GOOGLE_CLIENT_ID,
|
||||
env.AUTH_GOOGLE_CLIENT_SECRET,
|
||||
`${env.ORIGIN}/auth/google/callback`,
|
||||
);
|
||||
|
||||
export const google: IOAuthProvider = {
|
||||
requireInvite: envToBool(env.AUTH_GOOGLE_REQUIRE_INVITE, true),
|
||||
createAuthorizationURL: (state: string, codeVerifier: string) => {
|
||||
const scopes = ['openid', 'profile', 'email'];
|
||||
return googleProvider.createAuthorizationURL(state, codeVerifier, scopes);
|
||||
},
|
||||
validateAuthorizationCode: async (code: string, codeVerifier: string) => {
|
||||
const tokens = await googleProvider.validateAuthorizationCode(code, codeVerifier);
|
||||
const claims = decodeIdToken(tokens.idToken());
|
||||
assertGuard<{
|
||||
sub: string;
|
||||
email: string;
|
||||
name: string;
|
||||
}>(claims);
|
||||
return {
|
||||
sub: claims.sub,
|
||||
name: claims.name,
|
||||
username: claims.email,
|
||||
};
|
||||
},
|
||||
};
|
2
src/lib/server/oauth-providers/index.ts
Normal file
2
src/lib/server/oauth-providers/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { authentik } from './authentik';
|
||||
export { google } from './google';
|
@@ -1,15 +1,19 @@
|
||||
import { Authentik, Google } from 'arctic';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import type { AuthProvider } from '$lib/auth';
|
||||
import { authentik, google } from '$lib/server/oauth-providers';
|
||||
|
||||
export const authentik = new Authentik(
|
||||
env.AUTH_DOMAIN,
|
||||
env.AUTH_CLIENT_ID,
|
||||
env.AUTH_CLIENT_SECRET,
|
||||
`${env.ORIGIN}/auth/authentik/callback`,
|
||||
);
|
||||
export interface IOAuthClaims {
|
||||
sub: string;
|
||||
name: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export const google = new Google(
|
||||
env.GOOGLE_CLIENT_ID,
|
||||
env.GOOGLE_CLIENT_SECRET,
|
||||
`${env.ORIGIN}/auth/google/callback`,
|
||||
);
|
||||
export interface IOAuthProvider {
|
||||
readonly requireInvite: boolean;
|
||||
createAuthorizationURL(state: string, codeVerifier: string): URL;
|
||||
validateAuthorizationCode(code: string, codeVerifier: string): Promise<IOAuthClaims>;
|
||||
}
|
||||
|
||||
export const oauthProviders: Record<AuthProvider, IOAuthProvider> = {
|
||||
authentik,
|
||||
google,
|
||||
};
|
||||
|
@@ -4,3 +4,11 @@ import { twMerge } from "tailwind-merge";
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function envToBool(value: string | undefined, defaultValue = false): boolean {
|
||||
if (typeof value === "undefined") {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return ['true', '1', 'yes'].includes(value.toLowerCase());
|
||||
}
|
||||
|
Reference in New Issue
Block a user