sistema-de-chamados/middleware.ts

51 lines
1.6 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server"
import { getCookieCache } from "better-auth/cookies"
const PUBLIC_PATHS = [/^\/login$/, /^\/api\/auth/, /^\/_next\//, /^\/favicon/]
const CUSTOMER_ALLOWED_PATHS = [/^\/portal(?:$|\/)/, /^\/api\/auth/, /^\/_next\//, /^\/favicon/]
const ADMIN_ONLY_PATHS = [/^\/admin(?:$|\/)/]
const PORTAL_HOME = "/portal"
const APP_HOME = "/dashboard"
export async function middleware(request: NextRequest) {
const { pathname, search } = request.nextUrl
if (PUBLIC_PATHS.some((pattern) => pattern.test(pathname))) {
return NextResponse.next()
}
const session = await getCookieCache(request)
if (!session?.user) {
const redirectUrl = new URL("/login", request.url)
redirectUrl.searchParams.set("callbackUrl", pathname + search)
return NextResponse.redirect(redirectUrl)
}
const role = (session.user as { role?: string })?.role?.toLowerCase() ?? "agent"
if (role === "customer") {
const canAccess = CUSTOMER_ALLOWED_PATHS.some((pattern) => pattern.test(pathname))
if (!canAccess) {
const redirectUrl = new URL(PORTAL_HOME, request.url)
redirectUrl.searchParams.set("callbackUrl", pathname + search)
return NextResponse.redirect(redirectUrl)
}
} else {
if (pathname.startsWith(PORTAL_HOME)) {
return NextResponse.redirect(new URL(APP_HOME, request.url))
}
const isAdmin = role === "admin"
if (!isAdmin && ADMIN_ONLY_PATHS.some((pattern) => pattern.test(pathname))) {
return NextResponse.redirect(new URL(APP_HOME, request.url))
}
}
return NextResponse.next()
}
export const config = {
runtime: "nodejs",
matcher: ["/(.*)"],
}