Fix admin authentication cookie handling
- Updated verifyAdminAuth to check for adminToken cookie in addition to Bearer token - Added fallback to parse cookie from request headers when cookies() API fails - This fixes admin dashboard login issues where authentication was failing 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { verify, sign } from 'jsonwebtoken';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret-key';
|
||||
|
||||
@@ -29,12 +30,34 @@ export interface AdminUser {
|
||||
|
||||
export async function verifyAdminAuth(request: NextRequest): Promise<AdminUser | null> {
|
||||
try {
|
||||
let token: string | null = null;
|
||||
|
||||
// First try to get token from Authorization header
|
||||
const authHeader = request.headers.get('authorization');
|
||||
if (!authHeader?.startsWith('Bearer ')) {
|
||||
return null;
|
||||
if (authHeader?.startsWith('Bearer ')) {
|
||||
token = authHeader.substring(7);
|
||||
}
|
||||
|
||||
const token = authHeader.substring(7);
|
||||
// If no Authorization header, try to get token from cookie
|
||||
if (!token) {
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
token = cookieStore.get('adminToken')?.value || null;
|
||||
} catch (error) {
|
||||
// If cookies() fails (e.g., in middleware), try to get cookie from request headers
|
||||
const cookieHeader = request.headers.get('cookie');
|
||||
if (cookieHeader) {
|
||||
const matches = cookieHeader.match(/adminToken=([^;]+)/);
|
||||
if (matches) {
|
||||
token = matches[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let payload: any;
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user