source: server/telefunc/ctx.ts@ 1d7e8fe

main
Last change on this file since 1d7e8fe was be22289, checked in by Tome <gjorgievtome@…>, 5 months ago

Minor refactoring

  • Property mode set to 100644
File size: 1.2 KB
RevLine 
[c30935a]1import { Abort, getContext } from "telefunc";
2import * as drizzleQueries from "../../database/drizzle/queries";
3
4export function ctx() {
5 return getContext();
6}
7
[6196d60]8export function parseSessionUserId(sessionUserId: unknown): number | undefined {
9 if (typeof sessionUserId !== "string" && typeof sessionUserId !== "number") return undefined;
[c30935a]10 const n = Number(sessionUserId);
[6196d60]11 return Number.isInteger(n) && n > 0 ? n : undefined;
[c30935a]12}
13
14export function getAuthState() {
15 const c = ctx();
16 const userId = parseSessionUserId(c.session?.user?.id);
17 return {
18 isLoggedIn: Boolean(userId),
19 userId: userId ?? null,
20 username: c.session?.user?.name ?? null,
[016481f]21 isAdmin: c.session?.user?.isAdmin,
[c30935a]22 session: c.session,
23 };
24}
25
[be22289]26export function requireUser() {
27 const c = ctx();
28 const userId = parseSessionUserId(c.session?.user?.id);
29 if (!userId) throw Abort();
30 return { c, userId };
31}
32
[c30935a]33export async function requireAdmin() {
34 const { c, userId } = requireUser();
35
[8de343e]36 if(!c.session?.user?.isAdmin) throw Abort();
[898cf68]37
38 const isAdmin = await drizzleQueries.isAdmin(c.db, userId);
[c30935a]39 if (!isAdmin) throw Abort();
[898cf68]40
[c30935a]41 return { c, userId };
42}
Note: See TracBrowser for help on using the repository browser.