@scayle/storefront-nuxt
Version:
Nuxt integration for the SCAYLE Commerce Engine and Storefront API
42 lines (41 loc) • 1.33 kB
JavaScript
import { Buffer } from "node:buffer";
import {
getRequestHeaders,
defineEventHandler,
setResponseStatus,
setResponseHeader
} from "h3";
import { HttpStatusCode } from "@scayle/storefront-core";
import { useRuntimeConfig } from "#imports";
const authenticationFailed = (event) => {
setResponseHeader(
event,
"WWW-Authenticate",
'Basic realm="Authentication required"'
);
setResponseStatus(event, HttpStatusCode.UNAUTHORIZED);
return "Authentication required";
};
export const eventHandlerWithBasicAuth = (handler, auth) => defineEventHandler(async (event) => {
const headers = getRequestHeaders(event);
if (!headers.authorization) {
return authenticationFailed(event);
}
const b64auth = headers.authorization.split(" ")[1] || "";
const decodedAuthHeader = Buffer.from(b64auth, "base64").toString();
if (decodedAuthHeader !== auth) {
return authenticationFailed(event);
}
return await handler(event);
});
export const eventHandlerWithCacheAuth = (handler) => defineEventHandler(async (event) => {
const config = useRuntimeConfig();
const auth = config.storefront.cache?.auth;
if (!auth || !auth.username || !auth.password) {
return await handler(event);
}
return await eventHandlerWithBasicAuth(
handler,
`${auth.username}:${auth.password}`
)(event);
});