defect fix for language and login - crm precedence then current session

This commit is contained in:
2026-04-08 12:17:28 +01:00
parent 56e854ca2b
commit 1b2f8e29c6
6 changed files with 169 additions and 62 deletions
@@ -40,8 +40,7 @@ const PersonalDetailsComplete = (props) => {
console.log("=============== pref lang", prefLang); console.log("=============== pref lang", prefLang);
setCookie(null, "pedw_locale", userLang, { setCookie(null, "pedw_locale", userLang, {
path: "/", path: "/"
maxAge: 60 * 60 * 24 * 365
}); });
console.log("Set cookie to:", userLang); console.log("Set cookie to:", userLang);
+5 -6
View File
@@ -64,7 +64,7 @@ const Header = (props) => {
"/myportal/contactus", "/myportal/contactus",
"/unsubscribe/[watchlistid]", "/unsubscribe/[watchlistid]",
"/unsubscribeall/[watchlistid]", "/unsubscribeall/[watchlistid]",
"/status", "/status"
]; ];
const hasContactLink = [ const hasContactLink = [
@@ -72,7 +72,7 @@ const Header = (props) => {
"/dns/help", "/dns/help",
"/dns/contact-us", "/dns/contact-us",
"/dns/applications", "/dns/applications",
"/dns/application-view", "/dns/application-view"
]; ];
let domainSwitch; let domainSwitch;
@@ -91,7 +91,7 @@ const Header = (props) => {
destroyCookie(null, "pedw_locale", { path: "/" }), destroyCookie(null, "pedw_locale", { path: "/" }),
destroyCookie(null, "pinsUser", { path: "/" }), destroyCookie(null, "pinsUser", { path: "/" }),
signOut({ signOut({
callbackUrl: locale == "cy" ? "/cy/allgofnodi" : "/logout", callbackUrl: locale == "cy" ? "/cy/allgofnodi" : "/logout"
})); }));
}; };
@@ -136,8 +136,7 @@ const Header = (props) => {
// Set cookie first // Set cookie first
setCookie(null, "pedw_locale", newLocale, { setCookie(null, "pedw_locale", newLocale, {
path: "/", path: "/"
maxAge: 60 * 60 * 24 * 365, // 1 year
}); });
// Then navigate with the new locale // Then navigate with the new locale
@@ -270,7 +269,7 @@ const mapDispatchToProps = (dispatch) => {
return { return {
setLogout: () => { setLogout: () => {
dispatch(setLogout()); dispatch(setLogout());
}, }
}; };
}; };
+79 -44
View File
@@ -15,9 +15,12 @@ import { PrismaClient } from "@prisma/client";
import NextAuth from "next-auth"; import NextAuth from "next-auth";
import EmailProvider from "next-auth/providers/email"; import EmailProvider from "next-auth/providers/email";
import { consoleLogger } from "../../../actions/core/logger"; import { consoleLogger } from "../../../actions/core/logger";
import { getPortalLogin } from "../../../actions/services/accountService";
const prisma = new PrismaClient(); const prisma = new PrismaClient();
const WELSH_LANGUAGE_CODE = 846040000;
const appendParamsAndPathToNewUrl = (fromUrl, toUrl) => { const appendParamsAndPathToNewUrl = (fromUrl, toUrl) => {
const fromUrlObj = new URL(fromUrl); const fromUrlObj = new URL(fromUrl);
const params = fromUrlObj.searchParams; const params = fromUrlObj.searchParams;
@@ -34,14 +37,64 @@ const appendParamsAndPathToNewUrl = (fromUrl, toUrl) => {
return toUrlObj.toString(); return toUrlObj.toString();
}; };
const resolveLocale = (req) => const resolveRequestLocale = (req) =>
req?.query?.locale || req?.query?.locale ||
req?.body?.locale || req?.body?.locale ||
req?.cookies?.pedw_locale || req?.cookies?.pedw_locale ||
"en"; "en";
const resolveCrmLocale = async (email) => {
if (!email) return null;
try {
const portalUserObj = await getPortalLogin(email);
const preferredLanguage =
portalUserObj?.value?.[0]?.pinswg_preferredlanguage;
if (preferredLanguage === WELSH_LANGUAGE_CODE) {
return "cy";
}
if (preferredLanguage != null) {
return "en";
}
return null;
} catch (error) {
consoleLogger(error);
return null;
}
};
const resolveEffectiveLocale = async (req, email) => {
const crmLocale = await resolveCrmLocale(email);
if (crmLocale) return crmLocale;
return resolveRequestLocale(req);
};
const buildLocalizedVerificationUrl = ({ url, email, effectiveLocale }) => {
const { host, protocol, searchParams } = new URL(url);
const baseDomain = `${protocol}//${host}`;
const newURL =
effectiveLocale === "cy"
? baseDomain +
"/api/auth/callback/email?callbackUrl=" +
encodeURIComponent(baseDomain + "/cy") +
"&token=" +
searchParams.get("token") +
"&email=" +
encodeURIComponent(email) +
"&locale=" +
effectiveLocale
: url;
return appendParamsAndPathToNewUrl(url, newURL);
};
const authOptions = (req, res) => { const authOptions = (req, res) => {
const locale = resolveLocale(req); const requestLocale = resolveRequestLocale(req);
return { return {
providers: [ providers: [
@@ -50,7 +103,10 @@ const authOptions = (req, res) => {
name: "emailAPI", name: "emailAPI",
type: "email", type: "email",
async sendVerificationRequest({ identifier: email, url }) { async sendVerificationRequest({ identifier: email, url }) {
const { host, protocol, searchParams } = new URL(url); const effectiveLocale = await resolveEffectiveLocale(
req,
email
);
console.log( console.log(
"============================================================\n", "============================================================\n",
@@ -58,23 +114,11 @@ const authOptions = (req, res) => {
"============================================================\n" "============================================================\n"
); );
const baseDomain = `${protocol}//${host}`; const formURL = buildLocalizedVerificationUrl({
const effectiveLocale = resolveLocale(req); url,
email,
const newURL = effectiveLocale
effectiveLocale === "cy" });
? baseDomain +
"/api/auth/callback/email?callbackUrl=" +
encodeURIComponent(baseDomain + "/cy") +
"&token=" +
searchParams.get("token") +
"&email=" +
encodeURIComponent(email) +
"&locale=" +
effectiveLocale
: url;
const formURL = appendParamsAndPathToNewUrl(url, newURL);
console.log( console.log(
"============================================================\n", "============================================================\n",
@@ -90,12 +134,13 @@ const authOptions = (req, res) => {
EmailProvider({ EmailProvider({
maxAge: 2 * 60 * 60, maxAge: 2 * 60 * 60,
async sendVerificationRequest({ identifier: email, url }) { async sendVerificationRequest({ identifier: email, url }) {
const { host, protocol, searchParams } = new URL(url);
const baseDomain = `${protocol}//${host}`;
const templateId = "b1b5704b-9bb8-4deb-a75c-d887ca902661"; const templateId = "b1b5704b-9bb8-4deb-a75c-d887ca902661";
const templateIdcy = "0614ce53-cd5f-421f-a1a5-8c8486a9113a"; const templateIdcy = "0614ce53-cd5f-421f-a1a5-8c8486a9113a";
const effectiveLocale = resolveLocale(req);
const effectiveLocale = await resolveEffectiveLocale(
req,
email
);
console.log( console.log(
"============================================================\n", "============================================================\n",
@@ -103,20 +148,11 @@ const authOptions = (req, res) => {
"============================================================\n" "============================================================\n"
); );
const newURL = const formURL = buildLocalizedVerificationUrl({
effectiveLocale === "cy" url,
? baseDomain + email,
"/api/auth/callback/email?callbackUrl=" + effectiveLocale
encodeURIComponent(baseDomain + "/cy") + });
"&token=" +
searchParams.get("token") +
"&email=" +
encodeURIComponent(email) +
"&locale=" +
effectiveLocale
: url;
const formURL = appendParamsAndPathToNewUrl(url, newURL);
console.log( console.log(
"============================================================\n", "============================================================\n",
@@ -178,11 +214,11 @@ const authOptions = (req, res) => {
} }
}, },
pages: { pages: {
signIn: (locale === "cy" ? "/cy" : "") + "/auth/signin", signIn: (requestLocale === "cy" ? "/cy" : "") + "/auth/signin",
error: (locale === "cy" ? "/cy" : "") + "/auth/error", error: (requestLocale === "cy" ? "/cy" : "") + "/auth/error",
verifyRequest: verifyRequest:
(locale === "cy" ? "/cy" : "") + "/auth/verify-request", (requestLocale === "cy" ? "/cy" : "") + "/auth/verify-request",
newUser: (locale === "cy" ? "/cy" : "") + "/account/register" newUser: (requestLocale === "cy" ? "/cy" : "") + "/account/register"
}, },
callbacks: { callbacks: {
session: async (session, user) => { session: async (session, user) => {
@@ -196,9 +232,8 @@ const authOptions = (req, res) => {
if (url.startsWith("/")) return `${baseUrl}${url}`; if (url.startsWith("/")) return `${baseUrl}${url}`;
if (new URL(url).origin === baseUrl) return url; if (new URL(url).origin === baseUrl) return url;
const effectiveLocale = resolveLocale(req);
const newUrl = const newUrl =
effectiveLocale === "cy" requestLocale === "cy"
? process.env.CY_API_ROOT ? process.env.CY_API_ROOT
: process.env.NEXTAUTH_URL; : process.env.NEXTAUTH_URL;
+43
View File
@@ -0,0 +1,43 @@
import { getPortalLogin } from "../../../actions/services/accountService";
import { consoleLogger } from "../../../actions/core/logger";
const WELSH_LANGUAGE_CODE = 846040000;
const resolveRequestLocale = (req) =>
req?.query?.locale ||
req?.body?.locale ||
req?.cookies?.pedw_locale ||
"en";
export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ message: "Method not allowed" });
}
const email = String(req.body?.email || "")
.trim()
.toLowerCase();
const sessionLocale = resolveRequestLocale(req);
if (!email) {
return res.status(200).json({ locale: sessionLocale });
}
try {
const portalUserObj = await getPortalLogin(email);
const preferredLanguage =
portalUserObj?.value?.[0]?.pinswg_preferredlanguage;
const locale =
preferredLanguage === WELSH_LANGUAGE_CODE
? "cy"
: preferredLanguage != null
? "en"
: sessionLocale;
return res.status(200).json({ locale });
} catch (error) {
consoleLogger(error);
return res.status(200).json({ locale: sessionLocale });
}
}
+1 -1
View File
@@ -64,7 +64,7 @@ export default async function ApiProxy(req, res) {
const queryUrl = const queryUrl =
"contacts?$filter=emailaddress1 eq '" + "contacts?$filter=emailaddress1 eq '" +
emailAddress + emailAddress +
"' and statuscode eq 1&$count=true&$select=emailaddress1,contactid,yomifullname,firstname,lastname"; "' and statuscode eq 1&$count=true&$select=pinswg_preferredlanguage,emailaddress1,contactid,yomifullname,firstname,lastname";
const relayPolicy = RELAY_POLICY_STRICT_LOGIN; const relayPolicy = RELAY_POLICY_STRICT_LOGIN;
+40 -9
View File
@@ -19,17 +19,48 @@ const SignIn = (props) => {
event.preventDefault(); event.preventDefault();
setButtonDisabled(true); setButtonDisabled(true);
const currentLocale = lang || "en"; try {
const url = new URL(event.target.callbackUrl.value); const email = String(event.target.email.value || "").trim();
url.searchParams.set("locale", currentLocale); const currentLocale = lang || "en";
setCookie(null, "pedw_locale", currentLocale, { const response = await fetch("/api/auth/resolve-locale", {
path: "/", method: "POST",
maxAge: 60 * 60 * 24 * 365 headers: {
}); "Content-Type": "application/json"
},
body: JSON.stringify({
email,
locale: currentLocale
})
});
event.target.callbackUrl.value = url.toString(); const data = await response.json();
event.target.submit(); const resolvedLocale =
data?.locale === "cy" || data?.locale === "en"
? data.locale
: currentLocale;
const url = new URL(event.target.callbackUrl.value);
url.searchParams.set("locale", resolvedLocale);
setCookie(null, "pedw_locale", resolvedLocale, {
path: "/"
});
event.target.callbackUrl.value = url.toString();
event.target.submit();
} catch (error) {
const fallbackLocale = lang || "en";
const url = new URL(event.target.callbackUrl.value);
url.searchParams.set("locale", fallbackLocale);
setCookie(null, "pedw_locale", fallbackLocale, {
path: "/"
});
event.target.callbackUrl.value = url.toString();
event.target.submit();
}
}; };
return ( return (