import { verify } from 'jsonwebtoken';
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { COOKIE_NAME } from './app/constants/cookie';
import { cookies } from 'next/headers';
export async function middleware(req: NextRequest) {
const res = NextResponse.next()
const token = req.cookies.get(COOKIE_NAME);
if (!token) {
if (req.nextUrl.pathname.startsWith('/home')) {
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/login'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}
else{
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}
}
const user = JSON.parse(token.value)
if (user.role === "USER") {
if (req.nextUrl.pathname.startsWith('/adupload')) {
return NextResponse.rewrite(new URL('/home', req.url))
}
if (req.nextUrl.pathname.startsWith('/login')) {
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/home'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}
if (req.nextUrl.pathname.startsWith('/register')) {
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/home'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}
}
return res
}
export const config = {
matcher: [
'/home/:path*',
],
}