/** * @swagger * /api/auth/[...nextauth]: * get: * summary: Phase 2 * tags: [Login] * description: NextAuth * responses: * 200: * description: Success */ import NextAuth from "next-auth"; import EmailProvider from "next-auth/providers/email"; import { PrismaAdapter } from "@next-auth/prisma-adapter"; import { PrismaClient } from "@prisma/client"; import nodemailer from "nodemailer"; import { consoleLogger } from "../../../actions"; import { useRouter } from "next/router"; import nookies from "nookies"; import { getCsrfToken } from "next-auth/react"; const prisma = new PrismaClient(); // For more information on each option (and a full list of options) go to // https://next-auth.js.org/configuration/options // export default NextAuth({ // // https://next-auth.js.org/configuration/providers // providers: [ // EmailProvider({ // // server: { // // host: process.env.EMAIL_SERVER_HOST, // // port: process.env.EMAIL_SERVER_PORT, // // auth: { // // user: process.env.EMAIL_SERVER_USER, // // pass: process.env.EMAIL_SERVER_PASSWORD, // // }, // // }, // // from: process.env.EMAIL_FROM, // maxAge: 10 * 60, // Magic links are valid for 10 min only // async sendVerificationRequest({ // identifier: email, // url, // provider: { server, from }, // }) { // const { host } = new URL(url); // const templateId = "b1b5704b-9bb8-4deb-a75c-d887ca902661"; // const emailAddress = email; // const personalisation = { // "emailAddress": email, // "signInLink": url, // "linkExpiry": 10 * 60, // }; // const reference = "PEDW-SIGNIN"; // var NotifyClient = // require("notifications-node-client").NotifyClient; // const notifyClient = new NotifyClient( // process.env.NOTIFY_API_KEY // ); // await notifyClient // .sendEmail(templateId, emailAddress, { // personalisation: personalisation, // reference: reference, // // emailReplyToId: emailReplyToId, // }) // //.then((response) => console.log(response)) // .catch((err) => consoleLogger(err)); // }, // }), // ], // adapter: PrismaAdapter(prisma), // secret: process.env.SECRET, // session: { // jwt: true, // pages: {}, // theme: "dark", // debug: true, // }, // pages: { // signIn: "/auth/signin", // //signOut: "/auth/signout", // error: "/auth/error", // Error code passed in query string as ?error= // verifyRequest: "/auth/verify-request", // (used for check email message) // newUser: "/account/register", // New users will be directed here on first sign in (leave the property out if not of interest) // }, // callbacks: { // session: async (session, user) => { // //console.log(user); // return Promise.resolve(session); // }, // }, // }); const parseUrl = (url) => { const defaultUrl = new URL( $( (locale == "cy" ? process.env.CY_API_ROOT : process.env.NEXTAUTH_URL) + `/api/auth` ) ); if (url && !url.startsWith("http")) { url = `https://${url}`; } const _url = new URL(url ?? defaultUrl); const path = (_url.pathname === "/" ? defaultUrl.pathname : _url.pathname) // Remove trailing slash .replace(/\/$/, ""); const base = `${_url.origin}${path}`; return { origin: _url.origin, host: _url.host, path, base, toString: () => base, }; }; const authOptions = (locale, req, res) => { //console.log(req.query.callbackUrl); // let newURL = parseUrl( // locale == "cy" // ? "https://" + process.env.I18N_DOMAIN + ":3000" // : process.env.NEXTAUTH_URL // ); return { providers: [ { id: "emailAPI", name: "emailAPI", type: "email", async sendVerificationRequest({ identifier: email, url }) { const { host, port, protocol, token, searchParams } = new URL(url); console.log( "============================================================\n", "verification url API: " + url + "\n", "============================================================\n" ); return res .writeHead(200, { "Content-Type": "application/json" }) .json({ url: url }); }, }, EmailProvider({ maxAge: 10 * 60, // Magic links are valid for 10 min only async sendVerificationRequest({ identifier: email, url }) { const { host, port, protocol, token, searchParams } = new URL(url); const templateId = "b1b5704b-9bb8-4deb-a75c-d887ca902661"; const templateIdcy = "0614ce53-cd5f-421f-a1a5-8c8486a9113a"; const emailAddress = email; console.log( "============================================================\n", "verification url: " + url + "\n", "============================================================\n" ); let newURL = locale == "cy" ? process.env.CY_API_ROOT : process.env.NEXTAUTH_URL; //console.log(newURL, searchParams.get("token")); const personalisation = { "emailAddress": email, "signInLink": url, "linkExpiry": 10 * 60, }; const reference = "PEDW-SIGNIN"; var NotifyClient = require("notifications-node-client").NotifyClient; const notifyClient = new NotifyClient( process.env.NOTIFY_API_KEY ); await notifyClient .sendEmail( locale == "cy" ? templateIdcy : templateId, emailAddress, { personalisation: personalisation, reference: reference, // emailReplyToId: emailReplyToId, } ) //.then((response) => console.log(response)) .catch((err) => consoleLogger(err)); }, }), ], adapter: PrismaAdapter(prisma), secret: process.env.NEXTAUTH_SECRET, session: { strategy: "database", jwt: true, pages: {}, theme: "dark", debug: true, maxAge: 30 * 60, updateAge: 5 * 60, // 24 hours }, cookies: { callbackUrl: { name: `__Secure-next-auth.callback-url`, options: { sameSite: "lax", path: "/", secure: true, }, }, }, pages: { signIn: (locale == "cy" ? "/cy" : "") + "/auth/signin", //signOut: "/logout/signout", error: (locale == "cy" ? "/cy" : "") + "/auth/error", // Error code passed in query string as ?error= verifyRequest: (locale == "cy" ? "/cy" : "") + "/auth/verify-request", // (used for check email message) newUser: (locale == "cy" ? "/cy" : "") + "/account/register", // New users will be directed here on first sign in (leave the property out if not of interest) }, callbacks: { session: async (session, user) => { console.log("callback in auth", session, user); return Promise.resolve(session); }, // redirect({ url, baseUrl }) { // debugger; // console.log("baseurl:", url, baseUrl); // // Allows relative callback URLs // if (url.startsWith("/")) return `${baseUrl}${url}`; // // Allows callback URLs on the same origin // else if (new URL(url).origin === baseUrl) return url; // // let newURL = // // locale == "cy" // // ? process.env.CY_API_ROOT // // : process.env.NEXTAUTH_URL; // //return baseUrl; // // return newURL; // }, }, }; }; const NextAuthPEDW = (req, res) => { //console.log("----------", authOptions(req.cookies["pedw_locale"])); //console.log("----------", return NextAuth( req, res, authOptions(req.cookies["pedw_locale"], req, res) ); }; export default NextAuthPEDW;