auth: work on adding google auth via invite
This commit is contained in:
@@ -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: '/',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
38
src/routes/auth/google/+server.ts
Normal file
38
src/routes/auth/google/+server.ts
Normal 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(),
|
||||
},
|
||||
});
|
||||
};
|
||||
97
src/routes/auth/google/callback/+server.ts
Normal file
97
src/routes/auth/google/callback/+server.ts
Normal 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: '/',
|
||||
},
|
||||
});
|
||||
};
|
||||
7
src/routes/invite/[id]/+layout.server.ts
Normal file
7
src/routes/invite/[id]/+layout.server.ts
Normal 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, '/')
|
||||
};
|
||||
16
src/routes/invite/[id]/+page.svelte
Normal file
16
src/routes/invite/[id]/+page.svelte
Normal 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} />
|
||||
Reference in New Issue
Block a user