- Updated next-auth dependency in package.json to version 5.0.0-beta.29. - Refactored create-admin script to use a valid email format. - Implemented authentication middleware for various API routes to enforce access control. - Refactored API route handlers to improve readability and maintainability. - Enhanced error handling in authentication error page. - Added detailed tests for authentication flow, including protected routes and NextAuth endpoints.
76 lines
1.9 KiB
JavaScript
76 lines
1.9 KiB
JavaScript
import { auth } from "@/lib/auth"
|
|
import { NextResponse } from "next/server"
|
|
|
|
// Role hierarchy for permission checking
|
|
const ROLE_HIERARCHY = {
|
|
'admin': 4,
|
|
'project_manager': 3,
|
|
'user': 2,
|
|
'read_only': 1
|
|
}
|
|
|
|
export function withAuth(handler, options = {}) {
|
|
return async (req, context) => {
|
|
try {
|
|
const session = await auth(req)
|
|
|
|
// Check if user is authenticated
|
|
if (!session?.user) {
|
|
return NextResponse.json(
|
|
{ error: "Authentication required" },
|
|
{ status: 401 }
|
|
)
|
|
}
|
|
|
|
// Check role-based permissions (without database access)
|
|
if (options.requiredRole && !hasPermission(session.user.role, options.requiredRole)) {
|
|
return NextResponse.json(
|
|
{ error: "Insufficient permissions" },
|
|
{ status: 403 }
|
|
)
|
|
}
|
|
|
|
// Add user info to request
|
|
req.user = {
|
|
id: session.user.id,
|
|
email: session.user.email,
|
|
name: session.user.name,
|
|
role: session.user.role
|
|
}
|
|
|
|
// Call the original handler
|
|
return await handler(req, context)
|
|
} catch (error) {
|
|
console.error("Auth middleware error:", error)
|
|
return NextResponse.json(
|
|
{ error: "Internal server error" },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
export function hasPermission(userRole, requiredRole) {
|
|
return ROLE_HIERARCHY[userRole] >= ROLE_HIERARCHY[requiredRole]
|
|
}
|
|
|
|
// Helper for read-only operations
|
|
export function withReadAuth(handler) {
|
|
return withAuth(handler, { requiredRole: 'read_only' })
|
|
}
|
|
|
|
// Helper for user-level operations
|
|
export function withUserAuth(handler) {
|
|
return withAuth(handler, { requiredRole: 'user' })
|
|
}
|
|
|
|
// Helper for project manager operations
|
|
export function withManagerAuth(handler) {
|
|
return withAuth(handler, { requiredRole: 'project_manager' })
|
|
}
|
|
|
|
// Helper for admin operations
|
|
export function withAdminAuth(handler) {
|
|
return withAuth(handler, { requiredRole: 'admin' })
|
|
}
|