|
|
@@ -15,6 +15,8 @@ import { ensurePrefix, withoutSuffix } from '@/utils/string'
|
|
|
|
|
|
// Constants
|
|
|
const HOME_PAGE_URL = '/dashboards/crm'
|
|
|
+const adminRoutes = ['/admin']; // 假設這些是需要 admin 權限的路由
|
|
|
+
|
|
|
|
|
|
const getLocale = request => {
|
|
|
// Try to get locale from URL
|
|
|
@@ -31,7 +33,9 @@ const getLocale = request => {
|
|
|
const locales = i18n.locales
|
|
|
|
|
|
// Use negotiator and intl-localematcher to get best locale
|
|
|
- const languages = new Negotiator({ headers: negotiatorHeaders }).languages(locales)
|
|
|
+ const languages = new Negotiator({
|
|
|
+ headers: negotiatorHeaders
|
|
|
+ }).languages(locales)
|
|
|
const locale = matchLocale(languages, locales, i18n.defaultLocale)
|
|
|
|
|
|
return locale
|
|
|
@@ -64,6 +68,22 @@ export default withAuth(
|
|
|
|
|
|
// If the user is logged in, `token` will be an object containing the user's details
|
|
|
const token = request.nextauth.token
|
|
|
+ console.log('withAuth middleware token:')
|
|
|
+ console.log(token)
|
|
|
+
|
|
|
+ // 獲取用戶角色,假設 token 中包含了 role 資訊
|
|
|
+ const userRole = token?.role;
|
|
|
+
|
|
|
+ const isAdminRoute = adminRoutes.some(route => {
|
|
|
+ const langPrefix = locale ? `/${locale}` : '';
|
|
|
+ return pathname.startsWith(`${langPrefix}${route}`);
|
|
|
+ });
|
|
|
+ console.log('isAdminRoute: ' + isAdminRoute)
|
|
|
+ console.log('userRole: ' + userRole)
|
|
|
+ if (isAdminRoute && userRole !== 'admin') {
|
|
|
+ // 如果不是 admin 但試圖訪問 admin 路由,重定向到登入頁或主頁
|
|
|
+ return NextResponse.redirect(new URL('/login', request.url));
|
|
|
+ }
|
|
|
|
|
|
// Check if the user is logged in
|
|
|
const isUserLoggedIn = !!token
|
|
|
@@ -82,7 +102,9 @@ export default withAuth(
|
|
|
let redirectUrl = '/login'
|
|
|
|
|
|
if (!(pathname === '/' || pathname === `/${locale}`)) {
|
|
|
- const searchParamsStr = new URLSearchParams({ redirectTo: withoutSuffix(pathname, '/') }).toString()
|
|
|
+ const searchParamsStr = new URLSearchParams({
|
|
|
+ redirectTo: withoutSuffix(pathname, '/')
|
|
|
+ }).toString()
|
|
|
|
|
|
redirectUrl += `?${searchParamsStr}`
|
|
|
}
|
|
|
@@ -107,6 +129,7 @@ export default withAuth(
|
|
|
},
|
|
|
{
|
|
|
callbacks: {
|
|
|
+ //authorized: ({ token }) => !!token
|
|
|
authorized: () => {
|
|
|
// This is a work-around for handling redirect on auth pages.
|
|
|
// We return true here so that the middleware function above
|