| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- import { withAuth } from "next-auth/middleware"
- import { NextResponse } from "next/server"
- export default withAuth(
- function middleware(req) {
- // Si el usuario no está autenticado y está intentando acceder a rutas protegidas
- if (!req.nextauth.token && req.nextUrl.pathname !== "/auth/login") {
- // Redirigir al login
- return NextResponse.redirect(new URL("/auth/login", req.url))
- }
- // Si el usuario está autenticado pero está en la página de login
- if (req.nextauth.token && req.nextUrl.pathname === "/auth/login") {
- // Redirigir al dashboard
- return NextResponse.redirect(new URL("/dashboard", req.url))
- }
- // Verificar roles específicos para rutas de admin
- if (req.nextUrl.pathname.startsWith("/admin")) {
- if (req.nextauth.token?.role !== "DOCTOR") {
- return NextResponse.redirect(new URL("/dashboard", req.url))
- }
- }
- return NextResponse.next()
- },
- {
- callbacks: {
- authorized: ({ token, req }) => {
- // Permitir acceso a rutas públicas
- if (req.nextUrl.pathname === "/auth/login" ||
- req.nextUrl.pathname === "/" ||
- req.nextUrl.pathname.startsWith("/api/auth")) {
- return true
- }
-
- // Para todas las demás rutas, requerir token válido
- return !!token
- },
- },
- }
- )
- // Configurar qué rutas debe proteger el middleware
- export const config = {
- matcher: [
- /*
- * Coincidir con todas las rutas de solicitud excepto las que comienzan con:
- * - api/auth (rutas de autenticación de NextAuth)
- * - _next/static (archivos estáticos)
- * - _next/image (archivos de optimización de imágenes)
- * - favicon.ico (favicon)
- * - public (archivos públicos)
- */
- '/((?!api/auth|_next/static|_next/image|favicon.ico|public).*)',
- ],
- }
|