@oberoncms/core
Version:
OberonCMS is a cloud deployable CMS written in typescript based on the Puck visual editor
111 lines (110 loc) • 2.98 kB
JavaScript
import { randomBytes } from "crypto";
import NextAuth from "next-auth";
import { AccessDenied } from "@auth/core/errors";
import { name, version } from "../package.json.js";
const masterEmail = process.env.MASTER_EMAIL || null;
const withCallback = (url) => {
const withCallback2 = new URL(url);
withCallback2.pathname = "/cms/login";
const callbackUrl = new URL(
withCallback2.searchParams.get("callbackUrl") || "/cms"
);
callbackUrl.pathname = "/cms";
withCallback2.searchParams.set("callbackUrl", callbackUrl.toString());
return withCallback2.toString();
};
const authPlugin = (adapter) => {
const nextAuth = NextAuth({
basePath: "/cms/api/auth",
pages: {
signIn: "/cms/login"
},
providers: [
{
id: "email",
type: "email",
from: "notused",
server: {},
maxAge: 4 * 60 * 60,
name: "Email",
options: {},
generateVerificationToken: () => {
return parseInt(randomBytes(3).toString("hex"), 16).toString().slice(0, 6);
},
sendVerificationRequest: async ({
identifier: email,
url: baseUrl,
token
}) => {
const url = withCallback(baseUrl);
await adapter.sendVerificationRequest({
email,
url,
token
});
}
}
],
session: {
strategy: "jwt"
},
adapter,
callbacks: {
async signIn(props) {
var _a;
const { user, profile } = props;
if ((user == null ? void 0 : user.email) && masterEmail && user.email === masterEmail) {
user.role = "admin";
return true;
}
if (user == null ? void 0 : user.role) {
return true;
}
if ((profile == null ? void 0 : profile.email_verified) && profile.email && await ((_a = adapter.getUserByEmail) == null ? void 0 : _a.call(adapter, profile.email))) {
return true;
}
return false;
},
jwt({ token, user }) {
if (user) {
const role = user.email === masterEmail ? "admin" : user.role;
token.role = role;
}
return token;
},
session({ session, token }) {
session.user.role = token.role;
return session;
}
}
});
return {
name: `${name}/auth`,
version,
handlers: {
auth: () => nextAuth.handlers
},
adapter: {
getCurrentUser: async () => {
const session = await nextAuth.auth();
return (session == null ? void 0 : session.user) || null;
},
signOut: async () => {
await nextAuth.signOut();
},
signIn: async ({ email }) => {
try {
await nextAuth.signIn("email", { redirect: false, email });
} catch (error) {
if (error instanceof AccessDenied) {
return;
}
throw error;
}
}
}
};
};
export {
authPlugin
};