Compare commits
5 Commits
c416057349
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
3b2ed4ddea
|
|||
|
7169bf0fb1
|
|||
|
31d23c5e87
|
|||
|
5fc9cf25c8
|
|||
|
0901e242eb
|
@@ -2,4 +2,4 @@ DATABASE_URL=local.db
|
|||||||
AUTH_DOMAIN=auth.lab.cazzzer.com
|
AUTH_DOMAIN=auth.lab.cazzzer.com
|
||||||
AUTH_CLIENT_ID=
|
AUTH_CLIENT_ID=
|
||||||
AUTH_CLIENT_SECRET=
|
AUTH_CLIENT_SECRET=
|
||||||
AUTH_REDIRECT_URI=
|
AUTH_REDIRECT_URI=http://localhost:5173/auth/authentik/callback
|
||||||
|
|||||||
@@ -46,6 +46,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@oslojs/crypto": "^1.0.1",
|
"@oslojs/crypto": "^1.0.1",
|
||||||
"@oslojs/encoding": "^1.1.0",
|
"@oslojs/encoding": "^1.1.0",
|
||||||
|
"arctic": "^2.2.1",
|
||||||
"better-sqlite3": "^11.1.2",
|
"better-sqlite3": "^11.1.2",
|
||||||
"drizzle-orm": "^0.33.0",
|
"drizzle-orm": "^0.33.0",
|
||||||
"lucide-svelte": "^0.454.0"
|
"lucide-svelte": "^0.454.0"
|
||||||
|
|||||||
@@ -7,6 +7,6 @@
|
|||||||
%sveltekit.head%
|
%sveltekit.head%
|
||||||
</head>
|
</head>
|
||||||
<body data-sveltekit-preload-data="hover">
|
<body data-sveltekit-preload-data="hover">
|
||||||
<div style="display: contents" class="flex flex-col min-h-screen">%sveltekit.body%</div>
|
<div class="flex flex-col min-h-screen">%sveltekit.body%</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { Handle } from '@sveltejs/kit';
|
import { type Handle, redirect } from '@sveltejs/kit';
|
||||||
import { dev } from '$app/environment';
|
import { dev } from '$app/environment';
|
||||||
import * as auth from '$lib/server/auth';
|
import * as auth from '$lib/server/auth';
|
||||||
|
import { sequence } from '@sveltejs/kit/hooks';
|
||||||
|
|
||||||
const handleAuth: Handle = async ({ event, resolve }) => {
|
const handleAuth: Handle = async ({ event, resolve }) => {
|
||||||
const sessionId = event.cookies.get(auth.sessionCookieName);
|
const sessionId = event.cookies.get(auth.sessionCookieName);
|
||||||
@@ -29,4 +30,16 @@ const handleAuth: Handle = async ({ event, resolve }) => {
|
|||||||
return resolve(event);
|
return resolve(event);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const handle: Handle = handleAuth;
|
|
||||||
|
const authRequired = new Set([
|
||||||
|
'/user',
|
||||||
|
'/connections',
|
||||||
|
]);
|
||||||
|
const handleProtectedPaths: Handle = ({ event, resolve }) => {
|
||||||
|
if (authRequired.has(event.url.pathname) && !event.locals.user) {
|
||||||
|
return redirect(302, '/');
|
||||||
|
}
|
||||||
|
return resolve(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const handle: Handle = sequence(handleAuth, handleProtectedPaths);
|
||||||
|
|||||||
@@ -6,23 +6,17 @@
|
|||||||
let { class: className, ...rest }: {class: string | undefined | null, rest: { [p: string]: unknown }} = $props();
|
let { class: className, ...rest }: {class: string | undefined | null, rest: { [p: string]: unknown }} = $props();
|
||||||
|
|
||||||
let isLoading = $state(false);
|
let isLoading = $state(false);
|
||||||
async function onSubmit(event: Event) {
|
|
||||||
event.preventDefault();
|
|
||||||
isLoading = true;
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
isLoading = false;
|
|
||||||
}, 3000);
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class={cn("grid gap-6", className)} {...rest}>
|
<div class={cn("grid gap-6", className)} {...rest}>
|
||||||
<Button disabled={isLoading} onclick={onSubmit}>
|
<form method="get" action="/auth/authentik">
|
||||||
{#if isLoading}
|
<Button type="submit" onclick={() => {isLoading=true}}>
|
||||||
<LucideLoaderCircle class="mr-2 h-4 w-4 animate-spin" />
|
{#if isLoading}
|
||||||
{:else}
|
<LucideLoaderCircle class="mr-2 h-4 w-4 animate-spin" />
|
||||||
<img class="mr-2 h-4 w-4" alt="Authentik Logo" src="https://auth.cazzzer.com/static/dist/assets/icons/icon.svg" />
|
{:else}
|
||||||
{/if}
|
<img class="mr-2 h-4 w-4" alt="Authentik Logo" src="https://auth.cazzzer.com/static/dist/assets/icons/icon.svg" />
|
||||||
Authentik
|
{/if}
|
||||||
</Button>
|
Sign in with Authentik
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { sha256 } from '@oslojs/crypto/sha2';
|
|||||||
import { encodeBase32LowerCaseNoPadding, encodeHexLowerCase } from '@oslojs/encoding';
|
import { encodeBase32LowerCaseNoPadding, encodeHexLowerCase } from '@oslojs/encoding';
|
||||||
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 type { RequestEvent } from '@sveltejs/kit';
|
||||||
|
import { dev } from '$app/environment';
|
||||||
|
|
||||||
const DAY_IN_MS = 1000 * 60 * 60 * 24;
|
const DAY_IN_MS = 1000 * 60 * 60 * 24;
|
||||||
|
|
||||||
@@ -25,15 +27,29 @@ export async function createSession(userId: string): Promise<table.Session> {
|
|||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function setSessionTokenCookie(event: RequestEvent, sessionId: string, expiresAt: Date) {
|
||||||
|
event.cookies.set(sessionCookieName, sessionId, {
|
||||||
|
path: '/',
|
||||||
|
sameSite: 'lax',
|
||||||
|
httpOnly: true,
|
||||||
|
expires: expiresAt,
|
||||||
|
secure: !dev,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function invalidateSession(sessionId: string): Promise<void> {
|
export async function invalidateSession(sessionId: string): Promise<void> {
|
||||||
await db.delete(table.session).where(eq(table.session.id, sessionId));
|
await db.delete(table.session).where(eq(table.session.id, sessionId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function deleteSessionTokenCookie(event: RequestEvent) {
|
||||||
|
event.cookies.delete(sessionCookieName, { path: '/' });
|
||||||
|
}
|
||||||
|
|
||||||
export async function validateSession(sessionId: string) {
|
export async function validateSession(sessionId: string) {
|
||||||
const [result] = await db
|
const [result] = await db
|
||||||
.select({
|
.select({
|
||||||
// Adjust user table here to tweak returned data
|
// Adjust user table here to tweak returned data
|
||||||
user: { id: table.user.id, username: table.user.username },
|
user: { id: table.user.id, username: table.user.username, name: table.user.name },
|
||||||
session: table.session
|
session: table.session
|
||||||
})
|
})
|
||||||
.from(table.session)
|
.from(table.session)
|
||||||
|
|||||||
9
src/lib/server/oauth.ts
Normal file
9
src/lib/server/oauth.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { Authentik } from 'arctic';
|
||||||
|
import * as env from '$env/static/private';
|
||||||
|
|
||||||
|
export const authentik = new Authentik(
|
||||||
|
env.AUTH_DOMAIN,
|
||||||
|
env.AUTH_CLIENT_ID,
|
||||||
|
env.AUTH_CLIENT_SECRET,
|
||||||
|
env.AUTH_REDIRECT_URI
|
||||||
|
);
|
||||||
9
src/routes/+layout.server.ts
Normal file
9
src/routes/+layout.server.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import type { LayoutServerLoad } from "./$types";
|
||||||
|
|
||||||
|
export const load: LayoutServerLoad = async (event) => {
|
||||||
|
const { user } = event.locals;
|
||||||
|
|
||||||
|
return {
|
||||||
|
user
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -1,19 +1,30 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import '../app.css';
|
import '../app.css';
|
||||||
let { children } = $props();
|
import { page } from '$app/stores';
|
||||||
|
import { cn } from '$lib/utils';
|
||||||
|
|
||||||
|
const { data, children } = $props();
|
||||||
|
const { user } = data;
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<header class="p-4">
|
<header class="p-4 sm:flex">
|
||||||
<h1 class="text-2xl font-bold">My App</h1>
|
<span class=" mr-6 font-bold sm:inline-block">My App</span>
|
||||||
<nav>
|
<nav class="flex items-center gap-6 text-sm">
|
||||||
<a href="/">Home</a>
|
<a href="/" class={cn("hover:text-foreground/80 transition-colors",
|
||||||
<a href="/about">About</a>
|
$page.url.pathname === "/" ? "text-foreground" : "text-foreground/60")}>Home</a>
|
||||||
|
{#if user}
|
||||||
|
<a href="/user" class={cn("hover:text-foreground/80 transition-colors",
|
||||||
|
$page.url.pathname === "/user" ? "text-foreground" : "text-foreground/60")}>Profile</a>
|
||||||
|
{/if}
|
||||||
</nav>
|
</nav>
|
||||||
</header>
|
</header>
|
||||||
<main class="flex-grow p-4">
|
<main class="flex-grow p-4">
|
||||||
{@render children()}
|
{@render children()}
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer class="p-4 text-center">
|
<!--https://github.com/sveltejs/kit/discussions/7585#discussioncomment-9997936-->
|
||||||
|
<!--Some shenanings needed to be done to get the footer position to stick correctly,
|
||||||
|
didn't work with display: contents-->
|
||||||
|
<footer class="p-4 relative text-center inset-x-0 bottom-0">
|
||||||
<p>© 2024</p>
|
<p>© 2024</p>
|
||||||
</footer>
|
</footer>
|
||||||
|
|||||||
@@ -1,7 +1,18 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { AuthForm } from "$lib/components/app/auth-form";
|
import { AuthForm } from '$lib/components/app/auth-form';
|
||||||
|
|
||||||
|
const { data } = $props();
|
||||||
|
const { user } = data;
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>VpGen</title>
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
<h1>Welcome to SvelteKit</h1>
|
<h1>Welcome to SvelteKit</h1>
|
||||||
|
|
||||||
<AuthForm />
|
{#if user }
|
||||||
|
<p>Hi {user.name}</p>
|
||||||
|
{:else}
|
||||||
|
<AuthForm class="p-4" />
|
||||||
|
{/if}
|
||||||
|
|||||||
14
src/routes/auth/+page.server.ts
Normal file
14
src/routes/auth/+page.server.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { fail, redirect } from "@sveltejs/kit";
|
||||||
|
import { invalidateSession, deleteSessionTokenCookie } from "$lib/server/auth";
|
||||||
|
import type { Actions } from "./$types";
|
||||||
|
|
||||||
|
export const actions: Actions = {
|
||||||
|
logout: async (event) => {
|
||||||
|
if (event.locals.session === null) {
|
||||||
|
return fail(401);
|
||||||
|
}
|
||||||
|
await invalidateSession(event.locals.session.id);
|
||||||
|
deleteSessionTokenCookie(event);
|
||||||
|
return redirect(302, "/");
|
||||||
|
}
|
||||||
|
};
|
||||||
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()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
78
src/routes/auth/authentik/callback/+server.ts
Normal file
78
src/routes/auth/authentik/callback/+server.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
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());
|
||||||
|
console.log("claims", claims);
|
||||||
|
const userId: string = claims.sub;
|
||||||
|
const username: string = claims.preferred_username;
|
||||||
|
|
||||||
|
const [existingUser] = await db.select().from(table.user).where(eq(table.user.id, userId));
|
||||||
|
|
||||||
|
if (existingUser) {
|
||||||
|
const session = await createSession(existingUser.id);
|
||||||
|
setSessionTokenCookie(event, session.id, session.expiresAt);
|
||||||
|
return new Response(null, {
|
||||||
|
status: 302,
|
||||||
|
headers: {
|
||||||
|
Location: "/"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const user: table.User = {
|
||||||
|
id: userId,
|
||||||
|
username,
|
||||||
|
name: claims.name as string,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await db.insert(table.user).values(user);
|
||||||
|
const session = await createSession(user.id);
|
||||||
|
setSessionTokenCookie(event, 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: "/"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
40
src/routes/user/+page.svelte
Normal file
40
src/routes/user/+page.svelte
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { invalidate, invalidateAll } from '$app/navigation';
|
||||||
|
import { Button } from '$lib/components/ui/button';
|
||||||
|
import { LucideLoaderCircle, LucideLogOut, LucideRefreshCw } from 'lucide-svelte';
|
||||||
|
|
||||||
|
let { data } = $props();
|
||||||
|
let isLoadingSignOut = $state(false);
|
||||||
|
|
||||||
|
function refetch() {
|
||||||
|
console.log("refetching");
|
||||||
|
invalidate((url) => {
|
||||||
|
console.log("invalidation url", url);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
invalidateAll();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>User Profile</title>
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
{JSON.stringify(data.user)}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<Button onclick={refetch}>
|
||||||
|
<LucideRefreshCw class="mr-2 h-4 w-4" />
|
||||||
|
Invalidate Data
|
||||||
|
</Button>
|
||||||
|
<form class="inline-flex" method="post" action="/auth?/logout">
|
||||||
|
<Button type="submit" onclick={() => {isLoadingSignOut = true}}>
|
||||||
|
{#if isLoadingSignOut}
|
||||||
|
<LucideLoaderCircle class="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
{:else}
|
||||||
|
<LucideLogOut class="mr-2 h-4 w-4" />
|
||||||
|
{/if}
|
||||||
|
Sign Out
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
Reference in New Issue
Block a user