Skip to content

Commit

Permalink
feat: Migrate to lucia v4 (removed the lucia library, implemented aut…
Browse files Browse the repository at this point in the history
…h manually)
  • Loading branch information
ottomated committed Oct 22, 2024
1 parent 39facec commit e80c19f
Show file tree
Hide file tree
Showing 20 changed files with 219 additions and 314 deletions.
106 changes: 106 additions & 0 deletions template_builder/templates/extras/src/lib/auth/{Auth}index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { Twitch } from 'arctic';
import { Base32Encoding, encodeHex } from 'oslo/encoding';
import { generateRandomString, sha256 } from 'oslo/crypto';
import type { Selectable } from 'kysely';
import { db } from '$lib/db';
import { CLIENT_ID, CLIENT_SECRET } from '$env/static/private';
import type { DB } from '$lib/db/schema';

const ONE_DAY = 1000 * 60 * 60 * 24;
const base32 = new Base32Encoding('abcdefghijklmnopqrstuvwxyz234567');

export function generateId(length = 15): string {
return generateRandomString(length, 'abcdefghijklmnopqrstuvwxyz0123456789');
}

export function generateSessionToken(): string {
const bytes = new Uint8Array(20);
crypto.getRandomValues(bytes);
const token = base32.encode(bytes, {
includePadding: false,
});
return token;
}

export async function createSession(
token: string,
userId: string,
): Promise<Session> {
const sessionId = encodeHex(await sha256(new TextEncoder().encode(token)));
const session: Session = {
id: sessionId,
userId,
expiresAt: new Date(Date.now() + ONE_DAY * 7),
};
await db
.insertInto('Session')
.values({
id: session.id,
user_id: session.userId,
expires_at: Math.floor(session.expiresAt.getTime() / 1000),
})
.execute();
return session;
}

export async function validateSessionToken(
token: string,
): Promise<SessionValidationResult> {
const sessionId = encodeHex(await sha256(new TextEncoder().encode(token)));
const row = await db
.selectFrom('Session as s')
.innerJoin('User as u', 'u.id', 's.user_id')
.select(['s.id', 's.user_id', 's.expires_at', 'u.twitch_id', 'u.username'])
.where('s.id', '=', sessionId)
.executeTakeFirst();
if (!row) {
return { session: null, user: null };
}
const session: Session = {
id: row.id,
userId: row.user_id,
expiresAt: new Date(row.expires_at * 1000),
};
if (Date.now() >= session.expiresAt.getTime()) {
await db.deleteFrom('Session').where('id', '=', session.id).execute();
return { session: null, user: null };
}
const user: User = {
id: row.user_id,
twitch_id: row.twitch_id,
username: row.username,
};
if (Date.now() >= session.expiresAt.getTime() - ONE_DAY * 15) {
session.expiresAt = new Date(Date.now() + ONE_DAY * 30);
await db
.updateTable('Session')
.set({
expires_at: Math.floor(session.expiresAt.getTime() / 1000),
})
.where('id', '=', session.id)
.execute();
}
return { session, user };
}

export async function invalidateSession(sessionId: string): Promise<void> {
await db.deleteFrom('Session').where('id', '=', sessionId).execute();
}

export type SessionValidationResult =
| { session: Session; user: User }
| { session: null; user: null };

export interface Session {
id: string;
userId: string;
expiresAt: Date;
}

export type User = Selectable<DB['User']>;

export let twitch: Twitch;
export function initAuth(origin: string) {
if (twitch) return;
twitch = new Twitch(CLIENT_ID, CLIENT_SECRET, origin + '/api/auth/callback');
}
41 changes: 0 additions & 41 deletions template_builder/templates/extras/src/lib/server/{Auth,D1}auth.ts

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { TRPCError, initTRPC } from '@trpc/server';
import type { Context } from './context';
import { transformer } from '$lib/trpc/transformer';
import { transformer } from '$lib/trpc';

const t = initTRPC.context<Context>().create({
transformer,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { initTRPC } from '@trpc/server';
import type { Context } from './context';
import { transformer } from '$lib/trpc/transformer';
import { transformer } from '$lib/trpc';

const t = initTRPC.context<Context>().create({
transformer,
Expand Down
13 changes: 0 additions & 13 deletions template_builder/templates/extras/src/lib/trpc/{Trpc}index.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { createTRPCSvelte } from 'trpc-svelte-query';
import { httpBatchLink } from '@trpc/client';
import type { AppRouter } from '$lib/server/routes/_app';
import { parse, stringify, uneval } from 'devalue';

export const transformer = {
Expand All @@ -10,3 +13,12 @@ export const transformer = {
deserialize: (object: string) => (0, eval)(`(${object})`),
},
};

export const trpc = createTRPCSvelte<AppRouter>({
links: [
httpBatchLink({
url: '/api/trpc',
}),
],
transformer,
});
Loading

0 comments on commit e80c19f

Please sign in to comment.