import { createMiddleware, createServerFn } from "@tanstack/react-start"; import { redirect } from "@tanstack/react-router"; import { oauth } from "./atproto.server"; import { clearAppSession, useAppSession } from "./auth.server"; export const authMiddleware = createMiddleware({ type: 'function' }).server( async ({ next }) => { const session = await useAppSession(); if (!session.data) throw new Error('Unauthorized') return next() }, ) export const loginFn = createServerFn({ method: "POST" }) .validator((data: { handle: string }) => { if (typeof data.handle !== "string" || !data.handle.trim()) { throw Error("Invalid handle") } return data; }) .handler(async ({ data }) => { const url = await oauth.authorize(data.handle); throw redirect({ href: url.href }); }); export const getCurrentUserFn = createServerFn({ method: "GET" }) .middleware([authMiddleware]) .handler(async () => { const session = await useAppSession(); return session.data.did; }); export const logoutFn = createServerFn({ method: "POST" }) .middleware([authMiddleware]) .handler(async () => { await clearAppSession(); throw redirect({ reloadDocument: true }); });