feat: add discord login
This commit is contained in:
parent
298592681b
commit
8d7b3d6dc2
15 changed files with 289 additions and 1 deletions
8
src/app.d.ts
vendored
8
src/app.d.ts
vendored
|
@ -1,14 +1,20 @@
|
|||
import type { Session, User } from "$lib/auth";
|
||||
|
||||
// See https://kit.svelte.dev/docs/types#app
|
||||
// for information about these interfaces
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
// interface Locals {}
|
||||
// interface PageData {}
|
||||
// interface PageState {}
|
||||
interface Locals {
|
||||
user: User | null;
|
||||
session: Session | null;
|
||||
}
|
||||
interface Platform {
|
||||
env?: {
|
||||
TCL_GUESSR_KV: KVNamespace;
|
||||
TCL_GUESSR_D1: D1Database;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
25
src/hooks.server.ts
Normal file
25
src/hooks.server.ts
Normal file
|
@ -0,0 +1,25 @@
|
|||
import { deleteSessionTokenCookie, setSessionTokenCookie } from "$lib/auth/cookie";
|
||||
import { validateSessionToken } from "$lib/auth/session";
|
||||
import type { Handle } from "@sveltejs/kit";
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
const db = event.platform?.env?.TCL_GUESSR_D1 ?? null;
|
||||
const token = event.cookies.get("session") ?? null;
|
||||
|
||||
if (db === null || token === null) {
|
||||
event.locals.session = null;
|
||||
event.locals.user = null;
|
||||
return resolve(event);
|
||||
}
|
||||
|
||||
const { session, user } = await validateSessionToken(token, db);
|
||||
if (session !== null) {
|
||||
setSessionTokenCookie(event.cookies, token, session.expiresAt);
|
||||
} else {
|
||||
deleteSessionTokenCookie(event.cookies);
|
||||
}
|
||||
|
||||
event.locals.session = session;
|
||||
event.locals.user = user;
|
||||
return resolve(event);
|
||||
};
|
19
src/lib/auth/cookie.ts
Normal file
19
src/lib/auth/cookie.ts
Normal file
|
@ -0,0 +1,19 @@
|
|||
import type { Cookies } from "@sveltejs/kit";
|
||||
|
||||
export function setSessionTokenCookie(cookies: Cookies, token: string, expiresAt: Date): void {
|
||||
cookies.set("session", token, {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
expires: expiresAt,
|
||||
path: "/",
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteSessionTokenCookie(cookies: Cookies): void {
|
||||
cookies.set("session", "", {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
maxAge: 0,
|
||||
path: "/",
|
||||
});
|
||||
}
|
14
src/lib/auth/discord.ts
Normal file
14
src/lib/auth/discord.ts
Normal file
|
@ -0,0 +1,14 @@
|
|||
import { Discord } from "arctic";
|
||||
import { DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET } from "$env/static/private";
|
||||
|
||||
export interface DiscordUser {
|
||||
id: string;
|
||||
username: string;
|
||||
avatar: string;
|
||||
}
|
||||
|
||||
export const discord = new Discord(
|
||||
DISCORD_CLIENT_ID,
|
||||
DISCORD_CLIENT_SECRET,
|
||||
"http://localhost:8788/login/callback",
|
||||
);
|
15
src/lib/auth/index.ts
Normal file
15
src/lib/auth/index.ts
Normal file
|
@ -0,0 +1,15 @@
|
|||
export type SessionValidationResult =
|
||||
| { session: Session; user: User }
|
||||
| { session: null; user: null };
|
||||
|
||||
export interface Session {
|
||||
id: string;
|
||||
userId: string;
|
||||
expiresAt: Date;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
avatarHash: string;
|
||||
}
|
76
src/lib/auth/session.ts
Normal file
76
src/lib/auth/session.ts
Normal file
|
@ -0,0 +1,76 @@
|
|||
import { encodeBase32LowerCaseNoPadding, encodeHexLowerCase } from "@oslojs/encoding";
|
||||
import { sha256 } from "@oslojs/crypto/sha2";
|
||||
import type { Session, SessionValidationResult, User } from ".";
|
||||
|
||||
interface ValidateResponse {
|
||||
id: string;
|
||||
user_id: string;
|
||||
expires_at: number;
|
||||
name: string;
|
||||
avatar_hash: string;
|
||||
}
|
||||
|
||||
export function generateSessionToken(): string {
|
||||
const bytes = new Uint8Array(40);
|
||||
crypto.getRandomValues(bytes);
|
||||
return encodeBase32LowerCaseNoPadding(bytes);
|
||||
}
|
||||
|
||||
export async function createSession(
|
||||
token: string,
|
||||
userId: string,
|
||||
db: D1Database,
|
||||
): Promise<Session> {
|
||||
const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
|
||||
const session: Session = {
|
||||
id: sessionId,
|
||||
userId,
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7), // 7 days
|
||||
};
|
||||
|
||||
await db
|
||||
.prepare("INSERT INTO session (id, user_id, expires_at) VALUES (?, ?, ?)")
|
||||
.bind(session.id, session.userId, Math.floor(session.expiresAt.getTime() / 1000))
|
||||
.run();
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
export async function validateSessionToken(
|
||||
token: string,
|
||||
db: D1Database,
|
||||
): Promise<SessionValidationResult> {
|
||||
const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
|
||||
|
||||
const row = await db
|
||||
.prepare(
|
||||
"SELECT session.id, session.user_id, session.expires_at, user.name, user.avatar_hash FROM session INNER JOIN user ON user.id = session.user_id WHERE session.id = ?",
|
||||
)
|
||||
.bind(sessionId)
|
||||
.first<ValidateResponse>();
|
||||
|
||||
if (row === null) return { session: null, user: null };
|
||||
|
||||
const session: Session = {
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
expiresAt: new Date(row.expires_at * 1000),
|
||||
};
|
||||
|
||||
const user: User = {
|
||||
id: row.user_id,
|
||||
name: row.name,
|
||||
avatarHash: row.avatar_hash,
|
||||
};
|
||||
|
||||
if (Date.now() >= session.expiresAt.getTime()) {
|
||||
await invalidateSession(sessionId, db);
|
||||
return { session: null, user: null };
|
||||
} else {
|
||||
return { session, user };
|
||||
}
|
||||
}
|
||||
|
||||
export async function invalidateSession(sessionId: string, db: D1Database): Promise<void> {
|
||||
await db.prepare("DELETE FROM session WHERE id = ?").bind(sessionId).run();
|
||||
}
|
5
src/routes/+page.server.ts
Normal file
5
src/routes/+page.server.ts
Normal file
|
@ -0,0 +1,5 @@
|
|||
import type { PageServerLoad } from "./$types";
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
return { user: locals.user };
|
||||
};
|
|
@ -1,9 +1,29 @@
|
|||
<script lang="ts">
|
||||
import type { PageData } from "./$types";
|
||||
|
||||
interface Props {
|
||||
data: PageData;
|
||||
}
|
||||
|
||||
const props: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="container">
|
||||
<h1>TCL-Guessr</h1>
|
||||
|
||||
<div class="login">
|
||||
{#if props.data.user === null}
|
||||
<a href="/login">Login</a>
|
||||
{:else}
|
||||
Logged in as <img
|
||||
src={`https://cdn.discordapp.com/avatars/${props.data.user.id}/${props.data.user.avatarHash}.webp?size=32`}
|
||||
alt="avatar"
|
||||
/> <b>{props.data.user.name}</b> - <a href="logout">Logout</a>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<span class="login"> </span>
|
||||
|
||||
<form action="/game" method="GET">
|
||||
<label>
|
||||
difficulté: <select name="mode">
|
||||
|
|
19
src/routes/login/+server.ts
Normal file
19
src/routes/login/+server.ts
Normal file
|
@ -0,0 +1,19 @@
|
|||
import { redirect } from "@sveltejs/kit";
|
||||
import { generateState } from "arctic";
|
||||
import { discord } from "$lib/auth/discord";
|
||||
import type { RequestHandler } from "./$types";
|
||||
|
||||
export const GET: RequestHandler = async ({ cookies }) => {
|
||||
const state = generateState();
|
||||
const scopes = ["identify"];
|
||||
const url = discord.createAuthorizationURL(state, scopes);
|
||||
|
||||
cookies.set("discord_oauth_state", state, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
maxAge: 60 * 10,
|
||||
sameSite: "lax",
|
||||
});
|
||||
|
||||
redirect(302, url);
|
||||
};
|
53
src/routes/login/callback/+server.ts
Normal file
53
src/routes/login/callback/+server.ts
Normal file
|
@ -0,0 +1,53 @@
|
|||
import { error, redirect } from "@sveltejs/kit";
|
||||
import type { RequestHandler } from "./$types";
|
||||
import { discord, type DiscordUser } from "$lib/auth/discord";
|
||||
import { OAuth2RequestError, type OAuth2Tokens } from "arctic";
|
||||
import { createSession, generateSessionToken } from "$lib/auth/session";
|
||||
import { setSessionTokenCookie } from "$lib/auth/cookie";
|
||||
|
||||
export const GET: RequestHandler = async ({ platform, url, cookies, fetch }) => {
|
||||
const db = platform?.env?.TCL_GUESSR_D1 ?? null;
|
||||
if (db === null) error(500, "could not access D1");
|
||||
|
||||
const code = url.searchParams.get("code");
|
||||
const state = url.searchParams.get("state");
|
||||
const storedState = cookies.get("discord_oauth_state") ?? null;
|
||||
|
||||
if (code === null || state === null || storedState === null) {
|
||||
error(400, "missing things from oauth2 response");
|
||||
}
|
||||
|
||||
if (state !== storedState) {
|
||||
error(400, "state does not match");
|
||||
}
|
||||
|
||||
let tokens: OAuth2Tokens;
|
||||
try {
|
||||
tokens = await discord.validateAuthorizationCode(code);
|
||||
} catch (e) {
|
||||
if (e instanceof OAuth2RequestError) {
|
||||
error(400, e.message);
|
||||
} else {
|
||||
error(400, "could not validate auth code");
|
||||
}
|
||||
}
|
||||
|
||||
const discordUser: DiscordUser = await fetch("https://discord.com/api/v10/users/@me", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens.accessToken()}`,
|
||||
},
|
||||
}).then((r) => r.json());
|
||||
|
||||
await db
|
||||
.prepare(
|
||||
"INSERT INTO user(id, name, avatar_hash) VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET name=excluded.name;",
|
||||
)
|
||||
.bind(discordUser.id, discordUser.username, discordUser.avatar)
|
||||
.run();
|
||||
|
||||
const sessionToken = generateSessionToken();
|
||||
const session = await createSession(sessionToken, discordUser.id, db);
|
||||
setSessionTokenCookie(cookies, sessionToken, session.expiresAt);
|
||||
|
||||
redirect(302, "/");
|
||||
};
|
16
src/routes/logout/+server.ts
Normal file
16
src/routes/logout/+server.ts
Normal file
|
@ -0,0 +1,16 @@
|
|||
import { invalidateSession } from "$lib/auth/session";
|
||||
import { redirect } from "@sveltejs/kit";
|
||||
import type { RequestHandler } from "./$types";
|
||||
|
||||
export const GET: RequestHandler = async ({ platform, locals }) => {
|
||||
const db = platform?.env?.TCL_GUESSR_D1 ?? null;
|
||||
|
||||
if (locals.session !== null && db !== null) {
|
||||
await invalidateSession(locals.session.id, db);
|
||||
}
|
||||
|
||||
locals.session = null;
|
||||
locals.user = null;
|
||||
|
||||
redirect(302, "/");
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue