middleware.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { withAuth } from "next-auth/middleware"
  2. import { NextResponse } from "next/server"
  3. export default withAuth(
  4. function middleware(req) {
  5. // Si el usuario no está autenticado y está intentando acceder a rutas protegidas
  6. if (!req.nextauth.token && req.nextUrl.pathname !== "/auth/login") {
  7. // Redirigir al login
  8. return NextResponse.redirect(new URL("/auth/login", req.url))
  9. }
  10. // Si el usuario está autenticado pero está en la página de login
  11. if (req.nextauth.token && req.nextUrl.pathname === "/auth/login") {
  12. // Redirigir al dashboard
  13. return NextResponse.redirect(new URL("/dashboard", req.url))
  14. }
  15. // Verificar roles específicos para rutas de admin
  16. if (req.nextUrl.pathname.startsWith("/admin")) {
  17. if (req.nextauth.token?.role !== "DOCTOR") {
  18. return NextResponse.redirect(new URL("/dashboard", req.url))
  19. }
  20. }
  21. return NextResponse.next()
  22. },
  23. {
  24. callbacks: {
  25. authorized: ({ token, req }) => {
  26. // Permitir acceso a rutas públicas
  27. if (req.nextUrl.pathname === "/auth/login" ||
  28. req.nextUrl.pathname === "/" ||
  29. req.nextUrl.pathname.startsWith("/api/auth")) {
  30. return true
  31. }
  32. // Para todas las demás rutas, requerir token válido
  33. return !!token
  34. },
  35. },
  36. }
  37. )
  38. // Configurar qué rutas debe proteger el middleware
  39. export const config = {
  40. matcher: [
  41. /*
  42. * Coincidir con todas las rutas de solicitud excepto las que comienzan con:
  43. * - api/auth (rutas de autenticación de NextAuth)
  44. * - _next/static (archivos estáticos)
  45. * - _next/image (archivos de optimización de imágenes)
  46. * - favicon.ico (favicon)
  47. * - public (archivos públicos)
  48. */
  49. '/((?!api/auth|_next/static|_next/image|favicon.ico|public).*)',
  50. ],
  51. }