auth: refactor common oauth provider logic, add options to disable providers and require invites
This commit is contained in:
36
src/routes/auth/[provider]/+server.ts
Normal file
36
src/routes/auth/[provider]/+server.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { generateCodeVerifier, generateState } from 'arctic';
|
||||
import { oauthProviders } from '$lib/server/oauth';
|
||||
import { is } from 'typia';
|
||||
import { type AuthProvider, enabledAuthProviders } from '$lib/auth';
|
||||
|
||||
export async function GET(event) {
|
||||
const { provider } = event.params;
|
||||
if (!is<AuthProvider>(provider) || !enabledAuthProviders[provider]) {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
const oauthProvider = oauthProviders[provider];
|
||||
|
||||
const state = generateState();
|
||||
const codeVerifier = generateCodeVerifier();
|
||||
const url = oauthProvider.createAuthorizationURL(state, codeVerifier);
|
||||
|
||||
event.cookies.set(`${provider}_oauth_state`, state, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
maxAge: 60 * 10, // 10 minutes
|
||||
sameSite: 'lax',
|
||||
});
|
||||
event.cookies.set(`${provider}_code_verifier`, codeVerifier, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
maxAge: 60 * 10, // 10 minutes
|
||||
sameSite: 'lax',
|
||||
});
|
||||
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: url.toString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,21 +1,24 @@
|
||||
import { createSession, isValidInviteToken, setSessionTokenCookie } from '$lib/server/auth';
|
||||
import { is } from 'typia';
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { error, redirect } from '@sveltejs/kit';
|
||||
import { type AuthProvider, enabledAuthProviders } from '$lib/auth';
|
||||
import { oauthProviders } from '$lib/server/oauth';
|
||||
import { ArcticFetchError, OAuth2RequestError } from 'arctic';
|
||||
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';
|
||||
import { createSession, isValidInviteToken, setSessionTokenCookie } from '$lib/server/auth';
|
||||
|
||||
export const load: PageServerLoad = async (event) => {
|
||||
const { url, cookies } = event;
|
||||
export const load: PageServerLoad = async ({ params: { provider }, url, cookies }) => {
|
||||
if (!is<AuthProvider>(provider) || !enabledAuthProviders[provider]) {
|
||||
error(404);
|
||||
}
|
||||
|
||||
const oauthProvider = oauthProviders[provider];
|
||||
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 storedState = cookies.get(`${provider}_oauth_state`) ?? null;
|
||||
const codeVerifier = cookies.get(`${provider}_code_verifier`) ?? null;
|
||||
|
||||
if (code === null || state === null || storedState === null || codeVerifier === null) {
|
||||
error(400, 'Missing url parameters');
|
||||
@@ -27,35 +30,23 @@ export const load: PageServerLoad = async (event) => {
|
||||
error(400, 'Invalid state in url');
|
||||
}
|
||||
|
||||
let tokens: OAuth2Tokens;
|
||||
let claims;
|
||||
try {
|
||||
tokens = await google.validateAuthorizationCode(code, codeVerifier);
|
||||
claims = await oauthProvider.validateAuthorizationCode(code, codeVerifier);
|
||||
} catch (e) {
|
||||
if (e instanceof arctic.OAuth2RequestError) {
|
||||
if (e instanceof OAuth2RequestError) {
|
||||
console.debug('Arctic: OAuth: invalid authorization code, credentials, or redirect URI', e);
|
||||
throw error(400, 'Invalid authorization code');
|
||||
error(400, 'Invalid authorization code');
|
||||
}
|
||||
if (e instanceof arctic.ArcticFetchError) {
|
||||
if (e instanceof ArcticFetchError) {
|
||||
console.debug('Arctic: failed to call `fetch()`', e);
|
||||
error(400, 'Failed to validate authorization code');
|
||||
}
|
||||
console.error('Unxepcted error validating authorization code', code, e);
|
||||
console.error('Unexpected error validating authorization code', code, e);
|
||||
error(500);
|
||||
}
|
||||
|
||||
const idToken = tokens.idToken();
|
||||
const claims = arctic.decodeIdToken(idToken);
|
||||
|
||||
console.log('claims', claims);
|
||||
|
||||
assertGuard<{
|
||||
sub: string;
|
||||
email: string;
|
||||
name: string;
|
||||
}>(claims);
|
||||
|
||||
const userId = claims.sub;
|
||||
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, claims.sub) });
|
||||
|
||||
if (existingUser) {
|
||||
const session = await createSession(existingUser.id);
|
||||
@@ -63,25 +54,22 @@ export const load: PageServerLoad = async (event) => {
|
||||
redirect(302, '/');
|
||||
}
|
||||
|
||||
if (!isValidInviteToken(stateInviteToken)) {
|
||||
if (oauthProvider.requireInvite && !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 = {
|
||||
id: userId,
|
||||
authSource: 'google',
|
||||
username: claims.email,
|
||||
id: claims.sub,
|
||||
authSource: provider,
|
||||
username: claims.username,
|
||||
name: claims.name,
|
||||
};
|
||||
|
||||
// TODO: proper error handling, delete cookies
|
||||
await db.insert(table.users).values(user);
|
||||
console.log('created user', user, 'with invite token', stateInviteToken);
|
||||
console.log('created user', user, 'using provider', provider, 'with invite token', stateInviteToken);
|
||||
|
||||
const session = await createSession(user.id);
|
||||
|
||||
setSessionTokenCookie(cookies, session.id, session.expiresAt);
|
||||
|
||||
redirect(302, '/');
|
||||
@@ -1,30 +0,0 @@
|
||||
import { generateState, generateCodeVerifier } from "arctic";
|
||||
import { authentik } from "$lib/server/oauth";
|
||||
|
||||
import type { RequestEvent } from "@sveltejs/kit";
|
||||
|
||||
export async function GET(event: RequestEvent): Promise<Response> {
|
||||
const state = generateState();
|
||||
const codeVerifier = generateCodeVerifier();
|
||||
const url = authentik.createAuthorizationURL(state, codeVerifier, ["openid", "profile"]);
|
||||
|
||||
event.cookies.set("authentik_oauth_state", state, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
maxAge: 60 * 10, // 10 minutes
|
||||
sameSite: "lax"
|
||||
});
|
||||
event.cookies.set("authentik_code_verifier", codeVerifier, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
maxAge: 60 * 10, // 10 minutes
|
||||
sameSite: "lax"
|
||||
});
|
||||
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: url.toString()
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
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 { 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;
|
||||
|
||||
if (code === null || state === null || storedState === null || codeVerifier === null) {
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
if (state !== storedState) {
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
let tokens: OAuth2Tokens;
|
||||
try {
|
||||
tokens = await authentik.validateAuthorizationCode(code, codeVerifier);
|
||||
} catch (e) {
|
||||
// Invalid code or client credentials
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
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) });
|
||||
|
||||
if (existingUser) {
|
||||
const session = await createSession(existingUser.id);
|
||||
setSessionTokenCookie(event.cookies, session.id, session.expiresAt);
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: '/',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const user: table.User = {
|
||||
id: userId,
|
||||
authSource: 'authentik',
|
||||
username,
|
||||
name: claims.name as string,
|
||||
};
|
||||
|
||||
try {
|
||||
await db.insert(table.users).values(user);
|
||||
const session = await createSession(user.id);
|
||||
setSessionTokenCookie(event.cookies, session.id, session.expiresAt);
|
||||
} catch (e) {
|
||||
console.error('failed to create user', e);
|
||||
return new Response(null, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: '/',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
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 + inviteToken, 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',
|
||||
});
|
||||
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: authUrl.toString(),
|
||||
},
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user