this repo has no description
at main 45 lines 1.3 kB view raw
1import { Logger } from "@aurabloom/common"; 2import { Elysia, t } from "elysia"; 3import { ensureActorExists, getBaseUrl } from "../federation/utils"; 4import { renewSession, validateSession } from "../utils/sessions"; 5 6const logger = new Logger("authMiddleware"); 7 8export const authMiddleware = new Elysia() 9 .derive({ as: "global" }, async ({ cookie: { session } }) => { 10 if (!session.value) return { user: null }; 11 12 const validSession = await validateSession(session.value); 13 if (!validSession) return { user: null }; 14 15 const renewDuration = 60 * 60 * 24 * 2; 16 const now = Math.floor(Date.now() / 1000); 17 if (validSession.expiresAt - now < renewDuration) 18 await renewSession(validSession.id); 19 20 try { 21 const baseUrl = getBaseUrl(); 22 await ensureActorExists(validSession.user.id, baseUrl); 23 } catch (error) { 24 logger.warn( 25 `failed to ensure federation actor for user with id ${validSession.user.id}`, 26 error, 27 ); 28 } 29 30 return { 31 user: { 32 id: validSession.user.id, 33 username: validSession.user.username, 34 }, 35 sessionId: validSession.id, 36 }; 37 }) 38 .resolve({ as: "scoped" }, ({ user, set, error }) => { 39 if (!user) { 40 set.status = 401; 41 return error(401, "unauthorized"); 42 } 43 44 return { user }; 45 });