Openstatus www.openstatus.dev
at 4c0f4c00a38753a5d0dfd7e7b7b7706dec6f1503 74 lines 2.3 kB view raw
1import { NextResponse } from "next/server"; 2 3import { auth } from "@/lib/auth"; 4 5import { db, eq } from "@openstatus/db"; 6import { user, usersToWorkspaces, workspace } from "@openstatus/db/src/schema"; 7import { getCurrency } from "@openstatus/db/src/schema/plan/utils"; 8 9export default auth(async (req) => { 10 const url = req.nextUrl.clone(); 11 const response = NextResponse.next(); 12 13 const continent = req.headers.get("x-vercel-ip-continent") || "NA"; 14 const country = req.headers.get("x-vercel-ip-country") || "US"; 15 const currency = getCurrency({ continent, country }); 16 17 // NOTE: used in the pricing table to display the currency based on user's location 18 response.cookies.set("x-currency", currency); 19 20 if (url.pathname.includes("api/trpc")) { 21 return response; 22 } 23 24 if (!req.auth && url.pathname !== "/login") { 25 console.log("User not authenticated, redirecting to login"); 26 const newURL = new URL("/login", req.url); 27 const encodedSearchParams = `${url.pathname}${url.search}`; 28 29 if (encodedSearchParams) { 30 newURL.searchParams.append("redirectTo", encodedSearchParams); 31 } 32 33 return NextResponse.redirect(newURL); 34 } 35 36 if (req.auth && url.pathname === "/login") { 37 const redirectTo = url.searchParams.get("redirectTo"); 38 console.log("User authenticated, redirecting to", redirectTo); 39 if (redirectTo) { 40 const redirectToUrl = new URL(redirectTo, req.url); 41 return NextResponse.redirect(redirectToUrl); 42 } 43 } 44 45 const hasWorkspaceSlug = req.cookies.has("workspace-slug"); 46 47 if (req.auth?.user?.id && !hasWorkspaceSlug) { 48 const [query] = await db 49 .select() 50 .from(usersToWorkspaces) 51 .innerJoin(user, eq(user.id, usersToWorkspaces.userId)) 52 .innerJoin(workspace, eq(workspace.id, usersToWorkspaces.workspaceId)) 53 .where(eq(user.id, Number.parseInt(req.auth.user.id))) 54 .all(); 55 56 if (!query) { 57 console.error(">> Should not happen, no workspace found for user"); 58 } 59 60 response.cookies.set("workspace-slug", query.workspace.slug); 61 } 62 63 if (!req.auth && hasWorkspaceSlug) { 64 response.cookies.delete("workspace-slug"); 65 } 66 67 return response; 68}); 69 70export const config = { 71 matcher: [ 72 "/((?!api|assets|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)", 73 ], 74};