@auth/nextjs
Version:
Authentication for Next.js.
77 lines (76 loc) • 3.12 kB
JavaScript
import { Auth } from "@auth/core";
import { NextResponse } from "next/server";
async function getAuth(headers, config) {
var _a;
// TODO: Handle URL correctly (NEXTAUTH_URL, request host, protocol, custom path, etc.)
const req = new Request("http://n/api/auth/session", {
headers: { cookie: headers.get("cookie") ?? "" },
});
config.trustHost = true;
if (config.callbacks) {
(_a = config.callbacks).session ?? (_a.session = ({ session, user, token }) => ({
expires: session.expires,
auth: user ?? token,
}));
}
const response = await Auth(req, config);
return response.json();
}
export function initAuth(config) {
return (...args) => {
// TODO: use `next/headers` when it's available in Middleware too
// if (!args.length) return getAuth($headers(), config)
if (!args.length)
return getAuth(new Headers(), config);
if (args[0] instanceof Headers)
return getAuth(args[0], config);
if (args[0] instanceof Request) {
// export { auth as default } from "auth"
const req = args[0];
const ev = args[1];
return authMiddleware([req, ev], config);
}
// import { auth } from "auth"
// export default auth((req) => { console.log(req.auth) }})
const userMiddleware = args[0];
return async (...args) => {
return authMiddleware(args, config, userMiddleware);
};
};
}
async function authMiddleware(args, config, userMiddleware) {
const request = args[0];
// TODO: pass `next/headers` when it's available
const { data: auth = null, expires = null } = (await getAuth(request.headers, config)) ?? {};
const authorized = config.callbacks?.authorized
? await config.callbacks.authorized({ request, auth, expires })
: true;
let response = NextResponse.next();
if (authorized instanceof Response) {
// User returned a custom response, like redirecting to a page or 401, respect it
response = authorized;
}
else if (userMiddleware) {
// Execute user's middleware with the augmented request
const augmentedReq = request;
augmentedReq.auth = auth;
response =
(await userMiddleware(augmentedReq, args[1])) ?? NextResponse.next();
}
else if (!authorized) {
// Redirect to signin page by default if not authorized
// TODO: Support custom signin page
request.nextUrl.pathname = "/api/auth/signin";
response = NextResponse.redirect(request.nextUrl);
}
// We will update the session cookie if it exists,
// so that the session expiry is extended
const finalResponse = new NextResponse(response?.body, response);
// TODO: respect config/prefix/chunking etc.
const name = "next-auth.session-token";
const val = request.cookies.get(name)?.value;
// TODO: respect config/prefix/chunking etc.
if (val)
finalResponse.cookies.set(name, val, { expires: new Date(expires) });
return finalResponse;
}