diff --git a/pages/api/auth/[...nextauth].js b/pages/api/auth/[...nextauth].js index dfd544c0..75939546 100644 --- a/pages/api/auth/[...nextauth].js +++ b/pages/api/auth/[...nextauth].js @@ -15,67 +15,34 @@ import { PrismaClient } from "@prisma/client"; import NextAuth from "next-auth"; import EmailProvider from "next-auth/providers/email"; import { consoleLogger } from "../../../actions/core/logger"; -import { getPreferredLanguage } from "../../../actions/services/accountService"; const prisma = new PrismaClient(); -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 appendParamsAndPathToNewUrl = (fromUrl, toUrl) => { - const fromUrlObj = new URL(fromUrl); // Parse the source URL - const params = fromUrlObj.searchParams; // Extract the query parameters + const fromUrlObj = new URL(fromUrl); + const params = fromUrlObj.searchParams; - const toUrlObj = new URL(toUrl); // Parse the new domain URL - toUrlObj.pathname = fromUrlObj.pathname; // Copy the path from the source URL + const toUrlObj = new URL(toUrl); + toUrlObj.pathname = fromUrlObj.pathname; - // Append only the parameters that don't already exist in the destination URL params.forEach((value, key) => { if (!toUrlObj.searchParams.has(key)) { - // Check if the parameter already exists toUrlObj.searchParams.append(key, value); } }); - return toUrlObj.toString(); // Return the full new URL as a string + return toUrlObj.toString(); }; -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 - // ); - // console.log("which locale", locale); - // console.log("which referer", req.body); - // console.log("cookie locale", req.cookies["pedw_locale"]); +const resolveLocale = (req) => + req?.query?.locale || + req?.body?.locale || + req?.cookies?.pedw_locale || + "en"; + +const authOptions = (req, res) => { + const locale = resolveLocale(req); + return { providers: [ { @@ -83,29 +50,19 @@ const authOptions = (locale, req, res) => { name: "emailAPI", type: "email", async sendVerificationRequest({ identifier: email, url }) { - const { host, port, protocol, token, searchParams } = - new URL(url); + const { host, protocol, searchParams } = new URL(url); + console.log( "============================================================\n", "verification url API: " + url + "\n", "============================================================\n" ); + const baseDomain = `${protocol}//${host}`; - const emailAddress = email; - const prefLang = await getPreferredLanguage(emailAddress); + const effectiveLocale = resolveLocale(req); - const registeredPrefLanguage = - prefLang.value.length > 0 - ? prefLang.value[0].pinswg_preferredlanguage === - 846040000 - ? "cy" - : "en" - : "en"; - - const effectiveLocale = registeredPrefLanguage ?? locale; - - let newURL = - effectiveLocale == "cy" + const newURL = + effectiveLocale === "cy" ? baseDomain + "/api/auth/callback/email?callbackUrl=" + encodeURIComponent(baseDomain + "/cy") + @@ -117,7 +74,7 @@ const authOptions = (locale, req, res) => { effectiveLocale : url; - let formURL = appendParamsAndPathToNewUrl(url, newURL); + const formURL = appendParamsAndPathToNewUrl(url, newURL); console.log( "============================================================\n", @@ -131,19 +88,14 @@ const authOptions = (locale, req, res) => { } }, EmailProvider({ - maxAge: 2 * 60 * 60, //10 * 60, // Magic links are valid for 10 min only + maxAge: 2 * 60 * 60, async sendVerificationRequest({ identifier: email, url }) { - const { host, port, protocol, token, searchParams } = - new URL(url); + const { host, protocol, searchParams } = new URL(url); const baseDomain = `${protocol}//${host}`; const templateId = "b1b5704b-9bb8-4deb-a75c-d887ca902661"; const templateIdcy = "0614ce53-cd5f-421f-a1a5-8c8486a9113a"; - const emailAddress = email; - - const queryLocale = req?.query?.locale || req?.body?.locale; - const cookieLocale = req.cookies["pedw_locale"]; - let locale = queryLocale || cookieLocale || "en"; + const effectiveLocale = resolveLocale(req); console.log( "============================================================\n", @@ -151,19 +103,8 @@ const authOptions = (locale, req, res) => { "============================================================\n" ); - const prefLang = await getPreferredLanguage(emailAddress); - - const registeredPrefLanguage = - prefLang.value.length > 0 - ? prefLang.value[0].pinswg_preferredlanguage === - 846040000 - ? "cy" - : "en" - : "en"; - - const effectiveLocale = registeredPrefLanguage ?? locale; - let newURL = - effectiveLocale == "cy" + const newURL = + effectiveLocale === "cy" ? baseDomain + "/api/auth/callback/email?callbackUrl=" + encodeURIComponent(baseDomain + "/cy") + @@ -175,7 +116,7 @@ const authOptions = (locale, req, res) => { effectiveLocale : url; - let formURL = appendParamsAndPathToNewUrl(url, newURL); + const formURL = appendParamsAndPathToNewUrl(url, newURL); console.log( "============================================================\n", @@ -184,16 +125,11 @@ const authOptions = (locale, req, res) => { ); const personalisation = { - "emailAddress": email, - "signInLink": formURL, - // locale == "cy" - // ? url.split("&token")[0] + - // "/cy&token" + - // url.split("&token")[1] - // : url, - - "linkExpiry": 2 * 60 * 60 + emailAddress: email, + signInLink: formURL, + linkExpiry: 2 * 60 * 60 }; + const reference = "PEDW-SIGNIN"; var NotifyClient = @@ -205,15 +141,15 @@ const authOptions = (locale, req, res) => { await notifyClient .sendEmail( - effectiveLocale == "cy" ? templateIdcy : templateId, - emailAddress, + effectiveLocale === "cy" + ? templateIdcy + : templateId, + email, { - personalisation: personalisation, - reference: reference - // emailReplyToId: emailReplyToId, + personalisation, + reference } ) - //.then((response) => console.log(response)) .catch((error) => consoleLogger(error)); } }) @@ -227,7 +163,7 @@ const authOptions = (locale, req, res) => { theme: "dark", debug: true, maxAge: 30 * 60, - updateAge: 5 * 60 // 24 hours + updateAge: 5 * 60 }, cookies: { callbackUrl: { @@ -240,11 +176,11 @@ const authOptions = (locale, req, res) => { } }, pages: { - signIn: (locale == "cy" ? "/cy" : "") + "/auth/signin", - error: (locale == "cy" ? "/cy" : "") + "/auth/error", // Error code passed in query string as ?error= + signIn: (locale === "cy" ? "/cy" : "") + "/auth/signin", + error: (locale === "cy" ? "/cy" : "") + "/auth/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) + (locale === "cy" ? "/cy" : "") + "/auth/verify-request", + newUser: (locale === "cy" ? "/cy" : "") + "/account/register" }, callbacks: { session: async (session, user) => { @@ -253,28 +189,19 @@ const authOptions = (locale, req, res) => { }, 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; - const originalUrl = url; - let newUrl = - locale == "cy" + if (url.startsWith("/")) return `${baseUrl}${url}`; + if (new URL(url).origin === baseUrl) return url; + + const effectiveLocale = resolveLocale(req); + const newUrl = + effectiveLocale === "cy" ? process.env.CY_API_ROOT : process.env.NEXTAUTH_URL; - const updatedUrl = appendParamsAndPathToNewUrl( - originalUrl, - newUrl - ); + const updatedUrl = appendParamsAndPathToNewUrl(url, newUrl); console.log(updatedUrl); - - //return baseUrl; - - console.log("the url:", updatedUrl); return updatedUrl; } } @@ -282,14 +209,7 @@ const authOptions = (locale, req, res) => { }; const NextAuthPEDW = (req, res) => { - //console.log("----------", authOptions(req.cookies["pedw_locale"])); - - //console.log("----------", - return NextAuth( - req, - res, - authOptions(req.cookies["pedw_locale"], req, res) - ); + return NextAuth(req, res, authOptions(req, res)); }; export default NextAuthPEDW; diff --git a/pages/auth/signin.js b/pages/auth/signin.js index 941e2775..b0113660 100644 --- a/pages/auth/signin.js +++ b/pages/auth/signin.js @@ -7,55 +7,28 @@ import CookieBanner from "../../components/cookieBanner"; import Footer from "../../components/footer"; import Header from "../../components/header"; import ServiceBanner from "../../components/servicebanner"; -import { getPreferredLanguage } from "../../actions/services/accountService"; import { setCookie } from "nookies"; const SignIn = (props) => { let { t, lang } = useTranslation(); const { footerLinks, pages, csrfToken, callbackUrl } = props; - let formURL = - new URL(window.location.href).protocol + - "//" + - new URL(window.location.href).hostname + - ":" + - new URL(window.location.href).port + - "/api/auth/signin/email"; - const [buttonDisabled, setButtonDisabled] = useState(false); const handleSubmit = async (event) => { event.preventDefault(); setButtonDisabled(true); - const email = event.target.email.value; + const currentLocale = lang || "en"; + const url = new URL(event.target.callbackUrl.value); + url.searchParams.set("locale", currentLocale); - try { - const res = await getPreferredLanguage(encodeURIComponent(email)); - const data = await res; + setCookie(null, "pedw_locale", currentLocale, { + path: "/", + maxAge: 60 * 60 * 24 * 365 + }); - const userLang = - data.value.length > 0 - ? data.value[0].pinswg_preferredlanguage === 846040000 - ? "cy" - : "en" - : "en"; - - // Modify callbackUrl hidden input to add/update lang param - const url = new URL(event.target.callbackUrl.value); - url.searchParams.set("locale", userLang); - - setCookie(null, "pedw_locale", userLang, { - path: "/", - maxAge: 60 * 60 * 24 * 365 - }); - - event.target.callbackUrl.value = url.toString(); - } catch (error) { - console.error("Failed to get preferred language", error); - } - - // Submit form after updating callbackUrl + event.target.callbackUrl.value = url.toString(); event.target.submit(); }; @@ -97,11 +70,7 @@ const SignIn = (props) => { action="/api/auth/signin/email" onSubmit={handleSubmit} > -
+
{ { - const fromUrlObj = new URL(fromUrl); // Parse the source URL - const params = fromUrlObj.searchParams; // Extract the query parameters + const fromUrlObj = new URL(fromUrl); + const params = fromUrlObj.searchParams; - const toUrlObj = new URL(toUrl); // Parse the new domain URL - toUrlObj.pathname = fromUrlObj.pathname; // Copy the path from the source URL + const toUrlObj = new URL(toUrl); + toUrlObj.pathname = fromUrlObj.pathname; - // Append the query parameters to the new URL params.forEach((value, key) => toUrlObj.searchParams.append(key, value) ); - return toUrlObj.toString(); // Return the full new URL as a string + return toUrlObj.toString(); }; typeof context.query.callbackUrl != "undefined" && @@ -221,19 +177,11 @@ export async function getServerSideProps(context) { formURL )); - //formURL = appendParamsAndPathToNewUrl(context.query.callbackUrl, formURL); - - const url = new URL(formURL); // base URL - - const params = new URLSearchParams(url.search); - params.append("locale", context.locale); - - url.search = params.toString(); - - console.log("========== callback: ", url.toString()); + const url = new URL(formURL); + url.searchParams.set("locale", context.locale || "en"); return { - props: { csrfToken: csrfToken, callbackUrl: url.toString() } + props: { csrfToken, callbackUrl: url.toString() } }; }