also looking at this
chore: wip stx improvements
#1649
241 files
+19022
-1323
| @@ -0,0 +1,48 @@ | ||
| 1 | import type { User } from './types' | |
| 2 | import { getSession } from './session' | |
| 3 | ||
| 4 | export interface MiddlewareResult { | |
| 5 | authenticated: boolean | |
| 6 | user?: { userId: string | number, data: Record<string, unknown> } | |
| 7 | redirect?: string | |
| 8 | } | |
| 9 | ||
| 10 | export function authMiddleware( | |
| 11 | findUser?: (userId: string | number) => Promise<User | null>, | |
| 12 | ): (sessionId: string | undefined) => Promise<MiddlewareResult> { | |
| 13 | return async (sessionId: string | undefined): Promise<MiddlewareResult> => { | |
| 14 | if (!sessionId) { | |
| 15 | return { authenticated: false, redirect: '/login' } | |
| 16 | } | |
| 17 | ||
| 18 | const session = getSession(sessionId) | |
| 19 | if (!session) { | |
| 20 | return { authenticated: false, redirect: '/login' } | |
| 21 | } | |
| 22 | ||
| 23 | if (findUser) { | |
| 24 | const user = await findUser(session.userId) | |
| 25 | if (!user) { | |
| 26 | return { authenticated: false, redirect: '/login' } | |
| 27 | } | |
| 28 | } | |
| 29 | ||
| 30 | return { | |
| 31 | authenticated: true, | |
| 32 | user: { userId: session.userId, data: session.data }, | |
| 33 | } | |
| 34 | } | |
| 35 | } | |
| 36 | ||
| 37 | export function guestMiddleware(): (sessionId: string | undefined) => MiddlewareResult { | |
| 38 | return (sessionId: string | undefined): MiddlewareResult => { | |
| 39 | if (sessionId) { | |
| 40 | const session = getSession(sessionId) | |
| 41 | if (session) { | |
| 42 | return { authenticated: true, redirect: '/dashboard' } | |
| 43 | } | |
| 44 | } | |
| 45 | ||
| 46 | return { authenticated: false } | |
| 47 | } | |
| 48 | } | |