cloudapp-dev / nextjs14-middleware-basic-auth

0 stars 0 forks source link

Is this repo up to date? #1

Open mksglu opened 3 months ago

mksglu commented 3 months ago

Is this repo up to date

cloudapp-dev commented 3 months ago

Hi @mksglu , You were right, the repo was out of sync. I did a commit with the missing files (middleware.ts and basicauth API route).

mksglu commented 3 months ago

@cloudapp-dev Thanks,

It's my middleware.ts

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const [AUTH_USER, AUTH_PASS] = (process.env.HTTP_BASIC_AUTH || ':').split(':');

// HTTP Basic Auth Middleware for Challenge
export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Redirect to /dashboard if the path is /
  if (pathname === '/') {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  // Protect the /auth/signup route with basic auth
  if (pathname.startsWith('/auth/signup')) {
    if (!isAuthenticated(request)) {
      return new NextResponse('Authentication required', {
        status: 401,
        headers: { 'WWW-Authenticate': 'Basic' }
      });
    }
  }

  const response = NextResponse.next();
  response.headers.set('x-current-path', pathname);

  return response;
}

// Check HTTP Basic Auth header if present
function isAuthenticated(req: NextRequest) {
  const authheader =
    req.headers.get('authorization') || req.headers.get('Authorization');

  if (!authheader) {
    return false;
  }

  const auth = Buffer.from(authheader.split(' ')[1], 'base64')
    .toString()
    .split(':');
  const user = auth[0];
  const pass = auth[1];

  return user === AUTH_USER && pass === AUTH_PASS;
}

export const config = {
  matcher: ['/', '/dashboard/:path*', '/auth/signup']
};

Hope it's helpful someone.

cloudapp-dev commented 3 months ago

Hi @mksglu , Great, thank you for sharing. Can I use your code for a blog post on www.cloudapp.dev? It's very interesting and useful for others.