Implement company provisioning codes and session tweaks

This commit is contained in:
Esdras Renan 2025-10-15 20:45:25 -03:00
parent 0fb9bf59b2
commit 2cba553efa
28 changed files with 1407 additions and 534 deletions

View file

@ -16,6 +16,18 @@ export async function middleware(request: NextRequest) {
const session = await getCookieCache(request)
if (!session?.user) {
const hasSessionCookie = Boolean(request.cookies.get("better-auth.session-token"))
const hasRefreshCookie =
Boolean(request.cookies.get("better-auth.refresh-token")) ||
Boolean(request.cookies.get("better-auth.refresh-token-v2"))
if (hasSessionCookie || hasRefreshCookie) {
const refreshed = await attemptSessionRefresh(request)
if (refreshed) {
return refreshed
}
}
const redirectUrl = new URL("/login", request.url)
redirectUrl.searchParams.set("callbackUrl", pathname + search)
return NextResponse.redirect(redirectUrl)
@ -42,3 +54,43 @@ export const config = {
// Evita executar para assets e imagens estáticas
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|icon.png).*)"],
}
async function attemptSessionRefresh(request: NextRequest): Promise<NextResponse | null> {
try {
const refreshUrl = new URL("/api/auth/get-session", request.url)
const response = await fetch(refreshUrl, {
method: "GET",
headers: {
cookie: request.headers.get("cookie") ?? "",
},
})
if (!response.ok) {
return null
}
const data = await response.json().catch(() => null)
if (!data?.user) {
return null
}
const redirect = NextResponse.redirect(request.nextUrl)
const setCookieHeaders =
typeof response.headers.raw === "function"
? response.headers.raw()["set-cookie"] ?? []
: []
if (setCookieHeaders.length === 0) {
const single = response.headers.get("set-cookie")
if (single) setCookieHeaders.push(single)
}
for (const cookie of setCookieHeaders) {
redirect.headers.append("set-cookie", cookie)
}
return redirect
} catch {
return null
}
}