feat: migrate auth stack and admin portal
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
parent
ff674d5bb5
commit
7946b8d017
46 changed files with 2564 additions and 178 deletions
|
|
@ -1,18 +1,51 @@
|
|||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { getCookieCache } from "better-auth/cookies"
|
||||
|
||||
export function middleware(req: NextRequest) {
|
||||
const url = req.nextUrl.clone();
|
||||
const isPublic = url.pathname.startsWith("/login") || url.pathname.startsWith("/_next") || url.pathname.startsWith("/api") || url.pathname.startsWith("/favicon");
|
||||
if (isPublic) return NextResponse.next();
|
||||
const cookie = req.cookies.get("demoUser")?.value;
|
||||
if (!cookie) {
|
||||
const redirect = NextResponse.redirect(new URL("/login", req.url));
|
||||
return redirect;
|
||||
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()
|
||||
}
|
||||
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 = {
|
||||
matcher: ["/:path*"],
|
||||
};
|
||||
runtime: "nodejs",
|
||||
matcher: ["/(.*)"],
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue