|
| 1 | +// --------------------------------------------------------------------------- |
| 2 | +// Auth handlers — login, callback, logout, me |
| 3 | +// --------------------------------------------------------------------------- |
| 4 | + |
| 5 | +import { makeUserStore } from "@executor/storage-postgres"; |
| 6 | +import { |
| 7 | + getAuthorizationUrl, |
| 8 | + authenticateWithCode, |
| 9 | + authenticateRequest, |
| 10 | + getLogoutUrl, |
| 11 | + makeSessionCookie, |
| 12 | + clearSessionCookie, |
| 13 | +} from "../auth/workos"; |
| 14 | +import type { DrizzleDb } from "../services/db"; |
| 15 | + |
| 16 | +export const createAuthHandlers = (db: DrizzleDb) => { |
| 17 | + const userStore = makeUserStore(db); |
| 18 | + |
| 19 | + const getBaseUrl = (): string => { |
| 20 | + if (process.env.APP_URL) return process.env.APP_URL; |
| 21 | + const port = process.env.PORT ?? "3000"; |
| 22 | + return `http://localhost:${port}`; |
| 23 | + }; |
| 24 | + |
| 25 | + return { |
| 26 | + login: async (_request: Request): Promise<Response> => { |
| 27 | + const redirectUri = `${getBaseUrl()}/auth/callback`; |
| 28 | + const url = getAuthorizationUrl(redirectUri); |
| 29 | + return Response.redirect(url, 302); |
| 30 | + }, |
| 31 | + |
| 32 | + callback: async (request: Request): Promise<Response> => { |
| 33 | + const url = new URL(request.url); |
| 34 | + const code = url.searchParams.get("code"); |
| 35 | + if (!code) { |
| 36 | + return new Response("Missing code parameter", { status: 400 }); |
| 37 | + } |
| 38 | + |
| 39 | + try { |
| 40 | + const result = await authenticateWithCode(code); |
| 41 | + const workosUser = result.user; |
| 42 | + |
| 43 | + // Upsert user |
| 44 | + const user = await userStore.upsertUser({ |
| 45 | + id: workosUser.id, |
| 46 | + email: workosUser.email, |
| 47 | + name: `${workosUser.firstName ?? ""} ${workosUser.lastName ?? ""}`.trim() || undefined, |
| 48 | + avatarUrl: workosUser.profilePictureUrl ?? undefined, |
| 49 | + }); |
| 50 | + |
| 51 | + // Check for pending invitations |
| 52 | + const pendingInvitations = await userStore.getPendingInvitations(user.email); |
| 53 | + let teamId: string; |
| 54 | + |
| 55 | + if (pendingInvitations.length > 0) { |
| 56 | + const invitation = pendingInvitations[0]!; |
| 57 | + await userStore.acceptInvitation(invitation.id); |
| 58 | + await userStore.addMember(invitation.teamId, user.id, "member"); |
| 59 | + teamId = invitation.teamId; |
| 60 | + } else { |
| 61 | + const teams = await userStore.getTeamsForUser(user.id); |
| 62 | + if (teams.length > 0) { |
| 63 | + teamId = teams[0]!.teamId; |
| 64 | + } else { |
| 65 | + const team = await userStore.createTeam(`${user.name ?? user.email}'s Team`); |
| 66 | + await userStore.addMember(team.id, user.id, "owner"); |
| 67 | + teamId = team.id; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + // Store teamId in a separate cookie (WorkOS sealed session doesn't carry app-specific data) |
| 72 | + const sealedSession = result.sealedSession; |
| 73 | + if (!sealedSession) { |
| 74 | + return new Response("Failed to create session", { status: 500 }); |
| 75 | + } |
| 76 | + |
| 77 | + return new Response(null, { |
| 78 | + status: 302, |
| 79 | + headers: [ |
| 80 | + ["Location", "/"], |
| 81 | + ["Set-Cookie", makeSessionCookie(sealedSession)], |
| 82 | + ["Set-Cookie", `executor_team=${teamId}; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800`], |
| 83 | + ], |
| 84 | + }); |
| 85 | + } catch (error) { |
| 86 | + console.error("Auth callback error:", error); |
| 87 | + return new Response("Authentication failed", { status: 500 }); |
| 88 | + } |
| 89 | + }, |
| 90 | + |
| 91 | + logout: async (request: Request): Promise<Response> => { |
| 92 | + const logoutUrl = await getLogoutUrl(request); |
| 93 | + const headers: [string, string][] = [ |
| 94 | + ["Set-Cookie", clearSessionCookie()], |
| 95 | + ["Set-Cookie", "executor_team=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"], |
| 96 | + ]; |
| 97 | + |
| 98 | + if (logoutUrl) { |
| 99 | + headers.push(["Location", logoutUrl]); |
| 100 | + return new Response(null, { status: 302, headers }); |
| 101 | + } |
| 102 | + |
| 103 | + headers.push(["Location", "/login"]); |
| 104 | + return new Response(null, { status: 302, headers }); |
| 105 | + }, |
| 106 | + |
| 107 | + me: async (request: Request): Promise<Response> => { |
| 108 | + const auth = await authenticateRequest(request); |
| 109 | + if (!auth) { |
| 110 | + return Response.json({ error: "Not authenticated" }, { status: 401 }); |
| 111 | + } |
| 112 | + |
| 113 | + const user = await userStore.getUser(auth.userId); |
| 114 | + if (!user) { |
| 115 | + return Response.json({ error: "User not found" }, { status: 401 }); |
| 116 | + } |
| 117 | + |
| 118 | + // Read teamId from cookie |
| 119 | + const teamId = parseCookie(request.headers.get("cookie"), "executor_team"); |
| 120 | + const team = teamId ? await userStore.getTeam(teamId) : null; |
| 121 | + |
| 122 | + return Response.json({ |
| 123 | + user: { |
| 124 | + id: user.id, |
| 125 | + email: user.email, |
| 126 | + name: user.name, |
| 127 | + avatarUrl: user.avatarUrl, |
| 128 | + }, |
| 129 | + team: team ? { id: team.id, name: team.name } : null, |
| 130 | + }); |
| 131 | + }, |
| 132 | + }; |
| 133 | +}; |
| 134 | + |
| 135 | +const parseCookie = (cookieHeader: string | null, name: string): string | null => { |
| 136 | + if (!cookieHeader) return null; |
| 137 | + const match = cookieHeader |
| 138 | + .split(";") |
| 139 | + .map((c) => c.trim()) |
| 140 | + .find((c) => c.startsWith(`${name}=`)); |
| 141 | + if (!match) return null; |
| 142 | + return match.slice(name.length + 1) || null; |
| 143 | +}; |
0 commit comments