Compare commits
17 Commits
feature/au
...
feature/ci
Author | SHA1 | Date | |
---|---|---|---|
8797238c4d
|
|||
a5a840accc
|
|||
0cd67da306
|
|||
2519fec3c4
|
|||
7fea7dd00c
|
|||
fbc93d87e0
|
|||
ee261142e8
|
|||
101c53709d
|
|||
0baedd2d0e
|
|||
5affe758ad
|
|||
501d967115
|
|||
1e2613b617
|
|||
5db86ca285
|
|||
700e5857ae
|
|||
190b1d0c90
|
|||
5b72ab28dd
|
|||
8f20c168a2
|
17
.env.example
17
.env.example
@@ -1,17 +1,12 @@
|
|||||||
DATABASE_URL=file:local.db
|
DATABASE_URL=file:local.db
|
||||||
|
|
||||||
PUBLIC_AUTH_AUTHENTIK_ENABLE=1
|
AUTH_DOMAIN=auth.lab.cazzzer.com
|
||||||
AUTH_AUTHENTIK_REQUIRE_INVITE=0
|
AUTH_CLIENT_ID=
|
||||||
AUTH_AUTHENTIK_DOMAIN=auth.lab.cazzzer.com
|
AUTH_CLIENT_SECRET=
|
||||||
AUTH_AUTHENTIK_CLIENT_ID=
|
GOOGLE_CLIENT_ID=
|
||||||
AUTH_AUTHENTIK_CLIENT_SECRET=
|
GOOGLE_CLIENT_SECRET=
|
||||||
|
|
||||||
PUBLIC_AUTH_GOOGLE_ENABLE=1
|
INVITE_TOKEN=GUjdsz9aREFTEBYDrA3AajUE8oVys2xW
|
||||||
AUTH_GOOGLE_REQUIRE_INVITE=1
|
|
||||||
AUTH_GOOGLE_CLIENT_ID=
|
|
||||||
AUTH_GOOGLE_CLIENT_SECRET=
|
|
||||||
|
|
||||||
AUTH_INVITE_TOKEN=GUjdsz9aREFTEBYDrA3AajUE8oVys2xW
|
|
||||||
|
|
||||||
OPNSENSE_API_URL=https://opnsense.cazzzer.com
|
OPNSENSE_API_URL=https://opnsense.cazzzer.com
|
||||||
OPNSENSE_API_KEY=
|
OPNSENSE_API_KEY=
|
||||||
|
@@ -6,7 +6,7 @@ steps:
|
|||||||
settings:
|
settings:
|
||||||
registry: gitea.cazzzer.com
|
registry: gitea.cazzzer.com
|
||||||
repo: ${CI_REPO,,}
|
repo: ${CI_REPO,,}
|
||||||
# replace '/' in branch name
|
# replace invalid characters in branch name
|
||||||
tags: ${CI_COMMIT_BRANCH/\//-}
|
tags: ${CI_COMMIT_BRANCH/\//-}
|
||||||
cache: true
|
cache: true
|
||||||
username:
|
username:
|
||||||
|
11
README.md
11
README.md
@@ -27,3 +27,14 @@ bun install
|
|||||||
bun run prepare
|
bun run prepare
|
||||||
bun run dev
|
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?)
|
||||||
|
@@ -1,9 +0,0 @@
|
|||||||
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,7 +3,6 @@
|
|||||||
import { Button } from '$lib/components/ui/button';
|
import { Button } from '$lib/components/ui/button';
|
||||||
import { cn } from '$lib/utils.js';
|
import { cn } from '$lib/utils.js';
|
||||||
import googleIcon from '$lib/assets/google.svg';
|
import googleIcon from '$lib/assets/google.svg';
|
||||||
import { enabledAuthProviders } from '$lib/auth';
|
|
||||||
|
|
||||||
let { inviteToken, class: className, ...rest }: {
|
let { inviteToken, class: className, ...rest }: {
|
||||||
inviteToken?: string;
|
inviteToken?: string;
|
||||||
@@ -15,7 +14,6 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class={cn('flex gap-6', className)} {...rest}>
|
<div class={cn('flex gap-6', className)} {...rest}>
|
||||||
{#if enabledAuthProviders.authentik }
|
|
||||||
<form method="get" onsubmit={() => submitted = true}
|
<form method="get" onsubmit={() => submitted = true}
|
||||||
action="/auth/authentik{inviteToken ? `?invite=${inviteToken}` : ''}">
|
action="/auth/authentik{inviteToken ? `?invite=${inviteToken}` : ''}">
|
||||||
<input type="hidden" value={inviteToken} name="invite" />
|
<input type="hidden" value={inviteToken} name="invite" />
|
||||||
@@ -32,8 +30,6 @@
|
|||||||
Sign in with Authentik
|
Sign in with Authentik
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
{/if}
|
|
||||||
{#if enabledAuthProviders.google }
|
|
||||||
<form method="get" onsubmit={() => submitted = true}
|
<form method="get" onsubmit={() => submitted = true}
|
||||||
action="/auth/google{inviteToken ? `?invite=${inviteToken}` : ''}">
|
action="/auth/google{inviteToken ? `?invite=${inviteToken}` : ''}">
|
||||||
<input type="hidden" value={inviteToken} name="invite" />
|
<input type="hidden" value={inviteToken} name="invite" />
|
||||||
@@ -50,5 +46,4 @@
|
|||||||
Sign in with Google
|
Sign in with Google
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
{/if}
|
|
||||||
</div>
|
</div>
|
||||||
|
@@ -86,7 +86,7 @@ export async function validateSession(sessionId: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function isValidInviteToken(inviteToken: string) {
|
export function isValidInviteToken(inviteToken: string) {
|
||||||
return inviteToken === env.AUTH_INVITE_TOKEN;
|
return inviteToken === env.INVITE_TOKEN;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SessionValidationResult = Awaited<ReturnType<typeof validateSession>>;
|
export type SessionValidationResult = Awaited<ReturnType<typeof validateSession>>;
|
||||||
|
@@ -1,34 +0,0 @@
|
|||||||
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,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
};
|
|
@@ -1,33 +0,0 @@
|
|||||||
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,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
};
|
|
@@ -1,2 +0,0 @@
|
|||||||
export { authentik } from './authentik';
|
|
||||||
export { google } from './google';
|
|
@@ -1,19 +1,15 @@
|
|||||||
import type { AuthProvider } from '$lib/auth';
|
import { Authentik, Google } from 'arctic';
|
||||||
import { authentik, google } from '$lib/server/oauth-providers';
|
import { env } from '$env/dynamic/private';
|
||||||
|
|
||||||
export interface IOAuthClaims {
|
export const authentik = new Authentik(
|
||||||
sub: string;
|
env.AUTH_DOMAIN,
|
||||||
name: string;
|
env.AUTH_CLIENT_ID,
|
||||||
username: string;
|
env.AUTH_CLIENT_SECRET,
|
||||||
}
|
`${env.ORIGIN}/auth/authentik/callback`,
|
||||||
|
);
|
||||||
|
|
||||||
export interface IOAuthProvider {
|
export const google = new Google(
|
||||||
readonly requireInvite: boolean;
|
env.GOOGLE_CLIENT_ID,
|
||||||
createAuthorizationURL(state: string, codeVerifier: string): URL;
|
env.GOOGLE_CLIENT_SECRET,
|
||||||
validateAuthorizationCode(code: string, codeVerifier: string): Promise<IOAuthClaims>;
|
`${env.ORIGIN}/auth/google/callback`,
|
||||||
}
|
);
|
||||||
|
|
||||||
export const oauthProviders: Record<AuthProvider, IOAuthProvider> = {
|
|
||||||
authentik,
|
|
||||||
google,
|
|
||||||
};
|
|
||||||
|
@@ -4,11 +4,3 @@ import { twMerge } from "tailwind-merge";
|
|||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return twMerge(clsx(inputs));
|
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());
|
|
||||||
}
|
|
||||||
|
@@ -1,36 +0,0 @@
|
|||||||
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(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
30
src/routes/auth/authentik/+server.ts
Normal file
30
src/routes/auth/authentik/+server.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
84
src/routes/auth/authentik/callback/+server.ts
Normal file
84
src/routes/auth/authentik/callback/+server.ts
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
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: '/',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
32
src/routes/auth/google/+server.ts
Normal file
32
src/routes/auth/google/+server.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
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(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
@@ -1,24 +1,21 @@
|
|||||||
import { is } from 'typia';
|
import { createSession, isValidInviteToken, setSessionTokenCookie } from '$lib/server/auth';
|
||||||
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 { db } from '$lib/server/db';
|
||||||
import * as table from '$lib/server/db/schema';
|
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 { eq } from 'drizzle-orm';
|
||||||
import { createSession, isValidInviteToken, setSessionTokenCookie } from '$lib/server/auth';
|
import { assertGuard } from 'typia';
|
||||||
|
import type { PageServerLoad } from './$types';
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ params: { provider }, url, cookies }) => {
|
export const load: PageServerLoad = async (event) => {
|
||||||
if (!is<AuthProvider>(provider) || !enabledAuthProviders[provider]) {
|
const { url, cookies } = event;
|
||||||
error(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
const oauthProvider = oauthProviders[provider];
|
|
||||||
const code = url.searchParams.get('code');
|
const code = url.searchParams.get('code');
|
||||||
const state = url.searchParams.get('state');
|
const state = url.searchParams.get('state');
|
||||||
const storedState = cookies.get(`${provider}_oauth_state`) ?? null;
|
const storedState = cookies.get('google_oauth_state') ?? null;
|
||||||
const codeVerifier = cookies.get(`${provider}_code_verifier`) ?? null;
|
const codeVerifier = cookies.get('google_code_verifier') ?? null;
|
||||||
|
|
||||||
if (code === null || state === null || storedState === null || codeVerifier === null) {
|
if (code === null || state === null || storedState === null || codeVerifier === null) {
|
||||||
error(400, 'Missing url parameters');
|
error(400, 'Missing url parameters');
|
||||||
@@ -30,23 +27,35 @@ export const load: PageServerLoad = async ({ params: { provider }, url, cookies
|
|||||||
error(400, 'Invalid state in url');
|
error(400, 'Invalid state in url');
|
||||||
}
|
}
|
||||||
|
|
||||||
let claims;
|
let tokens: OAuth2Tokens;
|
||||||
try {
|
try {
|
||||||
claims = await oauthProvider.validateAuthorizationCode(code, codeVerifier);
|
tokens = await google.validateAuthorizationCode(code, codeVerifier);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof OAuth2RequestError) {
|
if (e instanceof arctic.OAuth2RequestError) {
|
||||||
console.debug('Arctic: OAuth: invalid authorization code, credentials, or redirect URI', e);
|
console.debug('Arctic: OAuth: invalid authorization code, credentials, or redirect URI', e);
|
||||||
error(400, 'Invalid authorization code');
|
throw error(400, 'Invalid authorization code');
|
||||||
}
|
}
|
||||||
if (e instanceof ArcticFetchError) {
|
if (e instanceof arctic.ArcticFetchError) {
|
||||||
console.debug('Arctic: failed to call `fetch()`', e);
|
console.debug('Arctic: failed to call `fetch()`', e);
|
||||||
error(400, 'Failed to validate authorization code');
|
error(400, 'Failed to validate authorization code');
|
||||||
}
|
}
|
||||||
console.error('Unexpected error validating authorization code', code, e);
|
console.error('Unxepcted error validating authorization code', code, e);
|
||||||
error(500);
|
error(500);
|
||||||
}
|
}
|
||||||
|
|
||||||
const existingUser = await db.query.users.findFirst({ where: eq(table.users.id, claims.sub) });
|
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) });
|
||||||
|
|
||||||
if (existingUser) {
|
if (existingUser) {
|
||||||
const session = await createSession(existingUser.id);
|
const session = await createSession(existingUser.id);
|
||||||
@@ -54,22 +63,25 @@ export const load: PageServerLoad = async ({ params: { provider }, url, cookies
|
|||||||
redirect(302, '/');
|
redirect(302, '/');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (oauthProvider.requireInvite && !isValidInviteToken(stateInviteToken)) {
|
if (!isValidInviteToken(stateInviteToken)) {
|
||||||
const message =
|
const message =
|
||||||
stateInviteToken.length === 0 ? 'sign up with an invite link first' : 'invalid invite link';
|
stateInviteToken.length === 0 ? 'sign up with an invite link first' : 'invalid invite link';
|
||||||
error(403, 'Not Authorized: ' + message);
|
error(403, 'Not Authorized: ' + message);
|
||||||
}
|
}
|
||||||
|
|
||||||
const user: table.User = {
|
const user: table.User = {
|
||||||
id: claims.sub,
|
id: userId,
|
||||||
authSource: provider,
|
authSource: 'google',
|
||||||
username: claims.username,
|
username: claims.email,
|
||||||
name: claims.name,
|
name: claims.name,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// TODO: proper error handling, delete cookies
|
||||||
await db.insert(table.users).values(user);
|
await db.insert(table.users).values(user);
|
||||||
console.log('created user', user, 'using provider', provider, 'with invite token', stateInviteToken);
|
console.log('created user', user, 'with invite token', stateInviteToken);
|
||||||
|
|
||||||
const session = await createSession(user.id);
|
const session = await createSession(user.id);
|
||||||
|
|
||||||
setSessionTokenCookie(cookies, session.id, session.expiresAt);
|
setSessionTokenCookie(cookies, session.id, session.expiresAt);
|
||||||
|
|
||||||
redirect(302, '/');
|
redirect(302, '/');
|
Reference in New Issue
Block a user