Atproto AMA app
1import { redirect } from "@solidjs/router";
2import { getCookie } from "vinxi/http";
3import { getSession, SESSION_COOKIE } from "~/lib/session";
4import { UnauthorizedError } from "~/lib/errors";
5
6export { RouteError, NotFoundError, ForbiddenError, UnauthorizedError } from "~/lib/errors";
7
8/**
9 * Reads + validates the current session. Throws `UnauthorizedError` so callers
10 * can either let the root `ErrorBoundary` handle it or catch and rethrow a
11 * `redirect(...)` for UI flows.
12 */
13export async function requireSession() {
14 "use server";
15 const sessionId = getCookie(SESSION_COOKIE);
16 if (!sessionId) throw new UnauthorizedError();
17 const session = await getSession(sessionId);
18 if (!session) throw new UnauthorizedError();
19 return session;
20}
21
22export async function requireAuth() {
23 "use server";
24 try {
25 const session = await requireSession();
26 return session.user;
27 } catch {
28 throw redirect("/");
29 }
30}
31
32export async function requireNotOwner(targetHandle: string) {
33 "use server";
34 const user = await requireAuth();
35 if (user.handle === targetHandle) {
36 throw redirect(`/${targetHandle}`);
37 }
38 return user;
39}
40
41export async function requireOwner(targetHandle: string) {
42 "use server";
43 const user = await requireAuth();
44 if (user.handle !== targetHandle) {
45 throw redirect(`/${targetHandle}`);
46 }
47 return user;
48}