Guest User

Untitled

a guest
May 22nd, 2024
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { NextRequest, NextResponse } from 'next/server';
  2. import jwt from 'jsonwebtoken';
  3.  
  4. // Replace with a mechanism to securely load your JWT secret
  5. // (e.g., environment variables, dedicated secrets management)
  6. const JWT_SECRET = process.env.JWT_SECRET!;
  7.  
  8. if (!JWT_SECRET) {
  9.   throw new Error('Missing JWT_SECRET environment variable');
  10. }
  11.  
  12. export function middleware(req: NextRequest) {
  13.   const { pathname } = req.nextUrl;
  14.  
  15.   console.log('Checking token for:', pathname); // Log the requested path
  16.  
  17.   // Exclude specific paths from token check (e.g., login, signup, public assets)
  18.   const excludedPaths = ['/login', '/signup', '/public/'];
  19.   if (excludedPaths.includes(pathname)) {
  20.     return NextResponse.next();
  21.   }
  22.  
  23.   const cookies = req.cookies;
  24.   const token = cookies.get('token')?.value; // Extract the value from RequestCookie
  25.  
  26.   console.log('Found token:', !!token); // Log if a token is found
  27.  
  28.   // Validate token if it exists
  29.   if (token) {
  30.     try {
  31.       const decoded = jwt.verify(token, JWT_SECRET);
  32.  
  33.       // Handle potentially missing username property:
  34.       if (typeof decoded === 'string') {
  35.         console.error('Invalid token structure: Missing username');
  36.         return NextResponse.redirect(new URL('/signup', req.url)); // Redirect on invalid structure
  37.       }
  38.  
  39.       console.log('Valid token for:', decoded.username || 'Unknown username'); // Log username or 'Unknown username'
  40.  
  41.       return NextResponse.next(); // Allow access if valid token
  42.     } catch (error) {
  43.       console.error('Invalid token:', error);
  44.     }
  45.   }
  46.  
  47.   // Redirect to signup if token is missing or invalid
  48.   console.log('Redirecting to signup (no valid token)'); // Log reason for redirect
  49.   return NextResponse.redirect(new URL('/signup', req.url));
  50. }
  51.  
  52. export const config = {
  53.   matcher: ['/workspace'], // Match all routes under /protected
  54. };
  55.  
Advertisement
Add Comment
Please, Sign In to add comment