refactor: switch to lucia

This commit is contained in:
Jozef Steinhübl 2024-08-03 20:23:12 +02:00
parent 04522ee264
commit 19df67079a
No known key found for this signature in database
GPG key ID: E6BC90C91973B08F
23 changed files with 335 additions and 94 deletions

View file

@ -0,0 +1,6 @@
PRO=<production>
DISCORD_CLIENT_ID=<client id>
DISCORD_CLIENT_SECRET=<client secret>
DISCORD_BOT_TOKEN=<bot token>
DISCORD_REDIRECT_URI=<domain>/auth/callback/discord

View file

@ -19,3 +19,6 @@ pnpm-debug.log*
# macOS-specific files # macOS-specific files
.DS_Store .DS_Store
.dev.vars
.wrangler/

View file

@ -5,7 +5,6 @@ import preact from "@astrojs/preact";
import sitemap from "@astrojs/sitemap"; import sitemap from "@astrojs/sitemap";
import tailwind from "@astrojs/tailwind"; import tailwind from "@astrojs/tailwind";
import cloudflare from "@astrojs/cloudflare"; import cloudflare from "@astrojs/cloudflare";
import auth from "auth-astro";
import { CONFIG } from "./src/config"; import { CONFIG } from "./src/config";
@ -14,17 +13,17 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
// https://astro.build/config // https://astro.build/config
export default defineConfig({ export default defineConfig({
site: CONFIG.origin, site: CONFIG.origin,
integrations: [sitemap(), tailwind(), auth(), preact()], integrations: [sitemap(), tailwind(), preact()],
output: "server", output: "server",
adapter: cloudflare(), adapter: cloudflare(),
security: {
checkOrigin: true,
},
vite: { vite: {
resolve: { resolve: {
alias: { alias: {
"~": path.resolve(__dirname, "./src"), "~": path.resolve(__dirname, "./src"),
}, },
}, },
ssr: {
external: ["node:path", "path", "os", "crypto"],
},
}, },
}); });

Binary file not shown.

View file

@ -0,0 +1,18 @@
-- Migration number: 0001 2024-08-03T15:43:57.349Z
CREATE TABLE IF NOT EXISTS user (
id TEXT NOT NULL PRIMARY KEY,
discord_id TEXT NOT NULL UNIQUE,
username TEXT NOT NULL,
avatar TEXT NOT NULL,
access_token TEXT NOT NULL,
access_token_expiration NUMBER NOT NULL,
refresh_token TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session (
id TEXT NOT NULL PRIMARY KEY,
expires_at INTEGER NOT NULL,
user_id TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES user (id)
);

View file

@ -14,13 +14,13 @@
"@astrojs/prefetch": "^0.2.1", "@astrojs/prefetch": "^0.2.1",
"@astrojs/sitemap": "^3.1.6", "@astrojs/sitemap": "^3.1.6",
"@astrojs/tailwind": "^5.1.0", "@astrojs/tailwind": "^5.1.0",
"@auth/core": "^0.32.0", "@lucia-auth/adapter-sqlite": "^3.0.2",
"@tailwindcss/typography": "^0.5.9", "@tailwindcss/typography": "^0.5.9",
"arctic": "^1.9.2",
"astro": "^4.11.5", "astro": "^4.11.5",
"astro-google-fonts-optimizer": "^0.2.2", "astro-google-fonts-optimizer": "^0.2.2",
"astro-icon": "^0.8.0", "astro-icon": "^0.8.0",
"auth-astro": "^4.1.2", "lucia": "^3.2.0",
"dotenv": "^16.4.5",
"preact": "^10.23.1", "preact": "^10.23.1",
"tailwindcss": "^3.3.1" "tailwindcss": "^3.3.1"
}, },

View file

@ -1,28 +1,12 @@
--- ---
import { Image } from "astro:assets"; import { Image } from "astro:assets";
import type { User } from "~/env";
import { getUser } from "~/lib/user";
interface Props { const user = Astro.locals.user;
user?: User;
}
let user: User;
if (!Astro.props.user) {
const u = await getUser(Astro.request);
if (!u) {
return Astro.redirect("/auth/login");
}
user = u;
} else {
user = Astro.props.user;
}
--- ---
<div class="flex items-center justify-center"> <div class="flex items-center justify-center">
<Image <Image
src={user.image!} src={`https://cdn.discordapp.com/avatars/${user.discordId}/${user.avatar}.webp`}
class="mr-5 rounded-full" class="mr-5 rounded-full"
alt="icon" alt="icon"
width={64} width={64}
@ -30,6 +14,6 @@ if (!Astro.props.user) {
/> />
<h1 class="break-all py-12 text-5xl font-extrabold text-white"> <h1 class="break-all py-12 text-5xl font-extrabold text-white">
@{user.name} @{user.username}
</h1> </h1>
</div> </div>

View file

@ -1,10 +1,13 @@
/// <reference types="astro/client" /> /// <reference types="astro/client" />
import type { User as AuthCoreUser } from "@auth/core/types"; type D1Database = import("@cloudflare/workers-types").D1Database;
type ENV = {
export type User = AuthCoreUser & { GITHUB_APP_NAME: string;
global_name: string; DISCORD_CLIENT_ID: string;
discordAccessToken: string; DISCORD_CLIENT_SECRET: string;
DISCORD_BOT_TOKEN: string;
DISCORD_REDIRECT_URI: string;
DB: D1Database;
}; };
export interface Guild { export interface Guild {
@ -19,3 +22,15 @@ export interface MutualeGuild {
mutual: boolean; mutual: boolean;
guild: Guild; guild: Guild;
} }
type Runtime = import("@astrojs/cloudflare").Runtime<ENV>;
// https://github.com/withastro/astro/issues/7394#issuecomment-1975657601
declare namespace App {
interface Locals extends Runtime {
discord: import("arctic").Discord;
lucia: import("lucia").Lucia;
session: import("lucia").Session | null;
user: import("lucia").User | null;
}
}

View file

@ -0,0 +1,54 @@
import { Lucia } from "lucia";
import { D1Adapter } from "@lucia-auth/adapter-sqlite";
import { Discord } from "arctic";
export function initializeLucia(D1: D1Database) {
const adapter = new D1Adapter(D1, {
user: "user",
session: "session",
});
return new Lucia(adapter, {
sessionCookie: {
attributes: {
// set to `true` when using HTTPS
secure: import.meta.env.PROD,
},
},
getUserAttributes: (attributes) => {
return {
discordId: attributes.discord_id,
username: attributes.username,
avatar: attributes.avatar,
sensitive: {
accessToken: attributes.access_token,
refreshToken: attributes.refresh_token,
accessTokenExpiresAt: attributes.access_token_expiration,
},
};
},
});
}
export function initializeDiscord(
discordClientId: string,
discordClientSecret: string,
redirectUri: string
) {
return new Discord(discordClientId, discordClientSecret, redirectUri);
}
declare module "lucia" {
interface Register {
Lucia: ReturnType<typeof initializeLucia>;
DatabaseUserAttributes: DatabaseUserAttributes;
}
}
interface DatabaseUserAttributes {
discord_id: number;
username: string;
avatar: string;
access_token: string;
refresh_token: string;
access_token_expiration: number;
}

View file

@ -1,24 +1,25 @@
import type { Guild, MutualeGuild, User } from "~/env"; import type { Guild, MutualeGuild } from "~/env";
import { isUserEligible } from "./user"; import { isUserEligible } from "./user";
export async function getGuild( export async function getGuild(
user: User, user,
guildId: string guildId: string,
env
): Promise<Guild | undefined> { ): Promise<Guild | undefined> {
const guilds = await getUserGuilds(user); const guilds = await getUserGuilds(user);
const guild = guilds.find((g) => g.id === guildId); const guild = guilds.find((g) => g.id === guildId);
if (!guild || !(await isMutualGuild(guild))) return undefined; if (!guild || !(await isMutualGuild(guild, env))) return undefined;
return guild; return guild;
} }
export async function getUserGuilds(user: User): Promise<Guild[]> { export async function getUserGuilds(user): Promise<Guild[]> {
const discordApiGuildsResponse = await fetch( const discordApiGuildsResponse = await fetch(
"https://discord.com/api/v10/users/@me/guilds", "https://discord.com/api/v10/users/@me/guilds",
{ {
headers: { headers: {
Authorization: `Bearer ${user.discordAccessToken as string}`, Authorization: `Bearer ${user.sensitive.accessToken as string}`,
"Cache-Control": "max-age=300", "Cache-Control": "max-age=300",
}, },
} }
@ -28,7 +29,8 @@ export async function getUserGuilds(user: User): Promise<Guild[]> {
} }
export async function filterUserGuilds( export async function filterUserGuilds(
guilds: Guild[] guilds: Guild[],
env
): Promise<MutualeGuild[]> { ): Promise<MutualeGuild[]> {
const filtered = guilds const filtered = guilds
.filter(isUserEligible) .filter(isUserEligible)
@ -37,7 +39,7 @@ export async function filterUserGuilds(
const result: MutualeGuild[] = []; const result: MutualeGuild[] = [];
for (const guild of filtered) { for (const guild of filtered) {
const mutual = await isMutualGuild(guild); const mutual = await isMutualGuild(guild, env);
result.push({ mutual, guild }); result.push({ mutual, guild });
} }
@ -47,14 +49,12 @@ export async function filterUserGuilds(
return result; return result;
} }
export async function isMutualGuild(guild: Guild): Promise<boolean> { export async function isMutualGuild(guild: Guild, env): Promise<boolean> {
const res = await fetch( const res = await fetch(
`https://discord.com/api/v10/guilds/${guild.id}/members/${ `https://discord.com/api/v10/guilds/${guild.id}/members/${env.DISCORD_CLIENT_ID}`,
import.meta.env.DISCORD_CLIENT_ID
}`,
{ {
headers: { headers: {
Authorization: `Bot ${import.meta.env.DISCORD_BOT_TOKEN}`, Authorization: `Bot ${env.DISCORD_BOT_TOKEN}`,
}, },
} }
); );

View file

@ -1,12 +1,4 @@
import { getSession } from "auth-astro/server"; import type { Guild } from "~/env";
import type { Guild, User } from "~/env";
export async function getUser(req: Request): Promise<User | null> {
const session = await getSession(req);
if (!session || !session.user) return null;
return session.user as User;
}
// Checks if user has AMDINISTRATOR permissions in the guild // Checks if user has AMDINISTRATOR permissions in the guild
export function isUserEligible(guild: Guild): boolean { export function isUserEligible(guild: Guild): boolean {

View file

@ -0,0 +1,40 @@
import { initializeLucia, initializeDiscord } from "./lib/auth";
import { defineMiddleware } from "astro:middleware";
export const onRequest = defineMiddleware(async (context, next) => {
const lucia = initializeLucia(context.locals.runtime.env.DB);
context.locals.lucia = lucia;
const discord = initializeDiscord(
context.locals.runtime.env.DISCORD_CLIENT_ID,
context.locals.runtime.env.DISCORD_CLIENT_SECRET,
context.locals.runtime.env.DISCORD_REDIRECT_URI
);
context.locals.discord = discord;
const sessionId = context.cookies.get(lucia.sessionCookieName)?.value ?? null;
if (!sessionId) {
context.locals.user = null;
context.locals.session = null;
return next();
}
const { session, user } = await lucia.validateSession(sessionId);
if (session && session.fresh) {
const sessionCookie = lucia.createSessionCookie(session.id);
context.cookies.set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
}
if (!session) {
const sessionCookie = lucia.createBlankSessionCookie();
context.cookies.set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
}
context.locals.session = session;
context.locals.user = user;
return next();
});

View file

@ -1,9 +1,8 @@
import type { APIRoute } from "astro"; import type { APIRoute } from "astro";
import { filterUserGuilds, getUserGuilds } from "~/lib/guilds"; import { filterUserGuilds, getUserGuilds } from "~/lib/guilds";
import { getUser } from "~/lib/user";
export const GET: APIRoute = async ({ request }) => { export const GET: APIRoute = async ({ locals }) => {
const user = await getUser(request); const user = locals.user;
if (!user) { if (!user) {
return new Response(null, { return new Response(null, {
status: 401, status: 401,
@ -11,7 +10,7 @@ export const GET: APIRoute = async ({ request }) => {
} }
const guilds = await getUserGuilds(user); const guilds = await getUserGuilds(user);
const res = await filterUserGuilds(guilds); const res = await filterUserGuilds(guilds, locals.runtime.env);
return Response.json(res); return Response.json(res);
}; };

View file

@ -0,0 +1,100 @@
import { OAuth2RequestError } from "arctic";
import type { APIContext } from "astro";
import { generateIdFromEntropySize } from "lucia";
type UserRow = {
id: string;
};
export async function GET(context: APIContext): Promise<Response> {
const code = context.url.searchParams.get("code");
const state = context.url.searchParams.get("state");
const storedState = context.cookies.get("discord_oauth_state")?.value ?? null;
if (!code || !state || !storedState || state !== storedState) {
return new Response(null, {
status: 400,
});
}
try {
const tokens = await context.locals.discord.validateAuthorizationCode(code);
const disocrdUserResponse = await fetch(
"https://discord.com/api/users/@me",
{
headers: {
Authorization: `Bearer ${tokens.accessToken}`,
},
}
);
const discordUser: DiscordUser = await disocrdUserResponse.json();
const existingUser = await context.locals.runtime.env.DB.prepare(
"SELECT * FROM user WHERE discord_id = ?1"
)
.bind(discordUser.id)
.first<UserRow>();
if (existingUser) {
const session = await context.locals.lucia.createSession(
existingUser.id,
{}
);
const sessionCookie = context.locals.lucia.createSessionCookie(
session.id
);
context.cookies.set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
return context.redirect("/dashboard");
}
const userId = generateIdFromEntropySize(10); // 16 characters long
await context.locals.runtime.env.DB.prepare(
"INSERT INTO user (id, discord_id, username, avatar, access_token, access_token_expiration, refresh_token) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"
)
.bind(
userId,
discordUser.id,
discordUser.username,
discordUser.avatar,
tokens.accessToken,
tokens.accessTokenExpiresAt.getTime(),
tokens.refreshToken
)
.run();
const session = await context.locals.lucia.createSession(userId, {});
const sessionCookie = context.locals.lucia.createSessionCookie(session.id);
context.cookies.set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
return context.redirect("/dashboard");
} catch (e) {
console.error(e.message);
// the specific error message depends on the provider
if (e instanceof OAuth2RequestError) {
// invalid code
return new Response(null, {
status: 400,
});
}
return new Response(null, {
status: 500,
});
}
}
interface DiscordUser {
id: string;
username: string;
avatar: string;
}

View file

@ -1,15 +0,0 @@
---
import Layout from "~/layouts/Layout.astro";
export const prerender = true;
---
<Layout>
<script>
const { signIn } = await import("auth-astro/client");
signIn("discord", {
redirect: false,
callbackUrl: "/dashboard",
});
</script>
</Layout>

View file

@ -0,0 +1,20 @@
import { generateState } from "arctic";
import type { APIContext } from "astro";
export async function GET(context: APIContext): Promise<Response> {
const state = generateState();
const url = await context.locals.discord.createAuthorizationURL(state, {
scopes: ["identify", "guilds"],
});
context.cookies.set("discord_oauth_state", state, {
path: "/",
secure: import.meta.env.PROD,
httpOnly: true,
maxAge: 60 * 10,
sameSite: "lax",
});
return context.redirect(url.toString());
}

View file

@ -1,16 +0,0 @@
---
import Layout from "~/layouts/Layout.astro";
export const prerender = true;
---
<Layout>
<script>
const { signOut } = await import("auth-astro/client");
signOut({
// @ts-expect-error
redirect: false,
callbackUrl: "/",
});
</script>
</Layout>

View file

@ -0,0 +1,20 @@
import type { APIContext } from "astro";
export async function GET(context: APIContext): Promise<Response> {
if (!context.locals.session) {
return new Response(null, {
status: 401,
});
}
await context.locals.lucia.invalidateSession(context.locals.session.id);
const sessionCookie = context.locals.lucia.createBlankSessionCookie();
context.cookies.set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
return context.redirect("/");
}

View file

@ -1,15 +1,15 @@
--- ---
import { getGuild } from "~/lib/guilds"; import { getGuild } from "~/lib/guilds";
import { getUser, isUserEligible } from "~/lib/user"; import { isUserEligible } from "~/lib/user";
const { id } = Astro.params; const { id } = Astro.params;
const user = await getUser(Astro.request); const user = Astro.locals.user;
if (!user || !id) { if (!user || !id) {
return Astro.redirect("/auth/login"); return Astro.redirect("/auth/login");
} }
const guild = await getGuild(user, id); const guild = await getGuild(user, id, Astro.locals.runtime.env);
if (!guild) { if (!guild) {
return Astro.redirect("/dashboard"); return Astro.redirect("/dashboard");
} }

View file

@ -3,6 +3,10 @@ import Layout from "~/layouts/Layout.astro";
import Container from "~/components/Container.astro"; import Container from "~/components/Container.astro";
import GuildSelector from "~/components/preact/GuildSelector"; import GuildSelector from "~/components/preact/GuildSelector";
import UserInfo from "~/components/dashboard/UserInfo.astro"; import UserInfo from "~/components/dashboard/UserInfo.astro";
if (!Astro.locals.user) {
return Astro.redirect("/auth/login");
}
--- ---
<Layout> <Layout>

View file

@ -1,11 +1,12 @@
{ {
"extends": "astro/tsconfigs/base", "extends": "astro/tsconfigs/strictest",
"compilerOptions": { "compilerOptions": {
"strictNullChecks": true, "strictNullChecks": true,
"allowJs": true, "allowJs": true,
"baseUrl": ".", "baseUrl": ".",
"paths": { "paths": {
"~/*": ["src/*"] "~/*": ["src/*"]
} },
"types": ["./src/env.d.ts"]
} }
} }

11
apps/website/worker-configuration.d.ts vendored Normal file
View file

@ -0,0 +1,11 @@
// Generated by Wrangler on Sat Aug 03 2024 17:34:42 GMT+0200 (Central European Summer Time)
// by running `wrangler types`
interface Env {
PRO: string;
DISCORD_CLIENT_ID: string;
DISCORD_CLIENT_SECRET: string;
DISCORD_BOT_TOKEN: string;
DISCORD_REDIRECT_URI: string;
DB: D1Database;
}

View file

@ -0,0 +1,6 @@
name = "roles-bot"
[[d1_databases]]
binding = "DB" # i.e. available in your Worker on env.DB
database_name = "roles-bot-dashboard"
database_id = "fdc6f902-9142-44bf-9be9-b38d351ffd27"