Files
nextgo/proxy.ts
Beyhan Oğur 9eb7aea821 first commit
2026-04-26 22:15:25 +03:00

72 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { NextRequest, NextResponse } from 'next/server'
import type { JWT } from 'next-auth/jwt'
import { getToken } from 'next-auth/jwt'
import {
applySessionCookie,
encodeSessionJwt,
fetchRefreshedBackendJwt,
shouldRefreshBackendToken,
} from '@/lib/backend-jwt-refresh'
const PUBLIC_PATHS = ['/auth/login', '/auth/register']
const secret = process.env.NEXTAUTH_SECRET ?? process.env.AUTH_SECRET
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
const isPublic = PUBLIC_PATHS.some((p) => pathname.startsWith(p))
let token = (await getToken({
req: request,
secret,
})) as JWT | null
let refreshedJwt: string | null = null
if (token && shouldRefreshBackendToken(token)) {
const next = await fetchRefreshedBackendJwt(token)
if (next) {
refreshedJwt = await encodeSessionJwt(next)
token = next as JWT
}
}
const hasBackendAccessToken =
typeof token?.accessToken === 'string' && token.accessToken.length > 0
const isLoggedIn = !!token && hasBackendAccessToken
const withCookie = (res: NextResponse) => {
if (refreshedJwt) applySessionCookie(res.cookies, refreshedJwt)
return res
}
// Giriş yapmış kullanıcı auth sayfasına gitmesin
if (isPublic && isLoggedIn) {
return withCookie(NextResponse.redirect(new URL('/admin/users', request.url)))
}
// Herkese açık sayfalara izin ver
if (isPublic) {
return withCookie(NextResponse.next())
}
// Token varsa devam et
if (isLoggedIn) {
return withCookie(NextResponse.next())
}
// Oturum yok → login
const loginUrl = new URL('/auth/login', request.url)
loginUrl.searchParams.set('from', pathname)
return withCookie(NextResponse.redirect(loginUrl))
}
export const config = {
matcher: [
/*
* Auth sayfaları, static dosyalar ve API route'ları hariç her şeyi yakala
*/
'/((?!_next/static|_next/image|favicon.ico|api/).*)',
],
}