cosmic-authentication
Version:
Authentication library for cosmic.new. Designed to be used and deployed on cosmic.new
73 lines (72 loc) • 3.17 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAuthMiddleware = createAuthMiddleware;
const server_1 = require("next/server");
const auth_1 = require("../lib/auth");
// Default auth configuration
const DEFAULT_CONFIG = {
loginPath: process.env.NEXT_PUBLIC_AUTH_LOGIN_PATH || 'https://auth.cosmic.new/signin',
clientId: process.env.NEXT_PUBLIC_CLIENT_ID || '',
protectedRoutes: []
};
function createAuthMiddleware(userConfig = {}) {
// Merge user config with defaults
const config = Object.assign(Object.assign({}, DEFAULT_CONFIG), userConfig);
return async function middleware(request) {
const { pathname } = request.nextUrl;
// Check if the requested path is protected
const isProtectedRoute = config.protectedRoutes.some(route => pathname === route || pathname.startsWith(`${route}/`));
// Skip auth check for non-protected routes
if (!isProtectedRoute) {
return server_1.NextResponse.next();
}
try {
// Check authentication status
const statusResponse = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/auth/status`, {
headers: {
cookie: request.headers.get('cookie') || ''
},
cache: 'no-store',
credentials: 'same-origin'
});
if (statusResponse.ok) {
const data = await statusResponse.json();
if (data.authenticated) {
// Forward any cookies that may have been set during refresh
const response = server_1.NextResponse.next();
const setCookieHeader = statusResponse.headers.get('set-cookie');
if (setCookieHeader) {
response.headers.set('Set-Cookie', setCookieHeader);
}
return response;
}
}
// Authentication failed - redirect to login
return redirectToLogin(request, config);
}
catch (err) {
console.error('Authentication check error:', err);
return redirectToLogin(request, config);
}
};
}
function redirectToLogin(request, config) {
const loginUrl = new URL(config.loginPath);
loginUrl.searchParams.set('client_id', config.clientId);
loginUrl.searchParams.set('redirect_url', `${process.env.NEXT_PUBLIC_BASE_URL}/api/auth/callback`);
const response = server_1.NextResponse.redirect(loginUrl.toString());
// Store the current URL for return after login
const returnUrl = request.nextUrl.pathname + request.nextUrl.search;
const isProduction = process.env.NODE_ENV === 'production';
response.cookies.set(auth_1.RETURN_URL_COOKIE, returnUrl, {
httpOnly: true,
secure: isProduction,
sameSite: isProduction ? 'none' : 'lax',
maxAge: 10 * 60, // 10 minutes
path: '/'
});
// Clear auth cookies
response.cookies.delete(auth_1.accessToken_COOKIE_NAME);
response.cookies.delete(auth_1.refreshToken_COOKIE_NAME);
return response;
}