22081 welsh signin flow

This commit is contained in:
2026-03-18 14:10:54 +00:00
parent 860291e1e6
commit e3bb321eae
2 changed files with 70 additions and 202 deletions
+50 -130
View File
@@ -15,67 +15,34 @@ 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 { getPreferredLanguage } from "../../../actions/services/accountService";
const prisma = new PrismaClient(); 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 appendParamsAndPathToNewUrl = (fromUrl, toUrl) => {
const fromUrlObj = new URL(fromUrl); // Parse the source URL const fromUrlObj = new URL(fromUrl);
const params = fromUrlObj.searchParams; // Extract the query parameters const params = fromUrlObj.searchParams;
const toUrlObj = new URL(toUrl); // Parse the new domain URL const toUrlObj = new URL(toUrl);
toUrlObj.pathname = fromUrlObj.pathname; // Copy the path from the source URL toUrlObj.pathname = fromUrlObj.pathname;
// Append only the parameters that don't already exist in the destination URL
params.forEach((value, key) => { params.forEach((value, key) => {
if (!toUrlObj.searchParams.has(key)) { if (!toUrlObj.searchParams.has(key)) {
// Check if the parameter already exists
toUrlObj.searchParams.append(key, value); toUrlObj.searchParams.append(key, value);
} }
}); });
return toUrlObj.toString(); // Return the full new URL as a string return toUrlObj.toString();
}; };
const authOptions = (locale, req, res) => { const resolveLocale = (req) =>
//console.log(req.query.callbackUrl); req?.query?.locale ||
// let newURL = parseUrl( req?.body?.locale ||
// locale == "cy" req?.cookies?.pedw_locale ||
// ? "https://" + process.env.I18N_DOMAIN + ":3000" "en";
// : process.env.NEXTAUTH_URL
// ); const authOptions = (req, res) => {
// console.log("which locale", locale); const locale = resolveLocale(req);
// console.log("which referer", req.body);
// console.log("cookie locale", req.cookies["pedw_locale"]);
return { return {
providers: [ providers: [
{ {
@@ -83,29 +50,19 @@ const authOptions = (locale, req, res) => {
name: "emailAPI", name: "emailAPI",
type: "email", type: "email",
async sendVerificationRequest({ identifier: email, url }) { async sendVerificationRequest({ identifier: email, url }) {
const { host, port, protocol, token, searchParams } = const { host, protocol, searchParams } = new URL(url);
new URL(url);
console.log( console.log(
"============================================================\n", "============================================================\n",
"verification url API: " + url + "\n", "verification url API: " + url + "\n",
"============================================================\n" "============================================================\n"
); );
const baseDomain = `${protocol}//${host}`; const baseDomain = `${protocol}//${host}`;
const emailAddress = email; const effectiveLocale = resolveLocale(req);
const prefLang = await getPreferredLanguage(emailAddress);
const registeredPrefLanguage = const newURL =
prefLang.value.length > 0 effectiveLocale === "cy"
? prefLang.value[0].pinswg_preferredlanguage ===
846040000
? "cy"
: "en"
: "en";
const effectiveLocale = registeredPrefLanguage ?? locale;
let newURL =
effectiveLocale == "cy"
? baseDomain + ? baseDomain +
"/api/auth/callback/email?callbackUrl=" + "/api/auth/callback/email?callbackUrl=" +
encodeURIComponent(baseDomain + "/cy") + encodeURIComponent(baseDomain + "/cy") +
@@ -117,7 +74,7 @@ const authOptions = (locale, req, res) => {
effectiveLocale effectiveLocale
: url; : url;
let formURL = appendParamsAndPathToNewUrl(url, newURL); const formURL = appendParamsAndPathToNewUrl(url, newURL);
console.log( console.log(
"============================================================\n", "============================================================\n",
@@ -131,19 +88,14 @@ const authOptions = (locale, req, res) => {
} }
}, },
EmailProvider({ EmailProvider({
maxAge: 2 * 60 * 60, //10 * 60, // Magic links are valid for 10 min only maxAge: 2 * 60 * 60,
async sendVerificationRequest({ identifier: email, url }) { async sendVerificationRequest({ identifier: email, url }) {
const { host, port, protocol, token, searchParams } = const { host, protocol, searchParams } = new URL(url);
new URL(url);
const baseDomain = `${protocol}//${host}`; 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 emailAddress = email; const effectiveLocale = resolveLocale(req);
const queryLocale = req?.query?.locale || req?.body?.locale;
const cookieLocale = req.cookies["pedw_locale"];
let locale = queryLocale || cookieLocale || "en";
console.log( console.log(
"============================================================\n", "============================================================\n",
@@ -151,19 +103,8 @@ const authOptions = (locale, req, res) => {
"============================================================\n" "============================================================\n"
); );
const prefLang = await getPreferredLanguage(emailAddress); const newURL =
effectiveLocale === "cy"
const registeredPrefLanguage =
prefLang.value.length > 0
? prefLang.value[0].pinswg_preferredlanguage ===
846040000
? "cy"
: "en"
: "en";
const effectiveLocale = registeredPrefLanguage ?? locale;
let newURL =
effectiveLocale == "cy"
? baseDomain + ? baseDomain +
"/api/auth/callback/email?callbackUrl=" + "/api/auth/callback/email?callbackUrl=" +
encodeURIComponent(baseDomain + "/cy") + encodeURIComponent(baseDomain + "/cy") +
@@ -175,7 +116,7 @@ const authOptions = (locale, req, res) => {
effectiveLocale effectiveLocale
: url; : url;
let formURL = appendParamsAndPathToNewUrl(url, newURL); const formURL = appendParamsAndPathToNewUrl(url, newURL);
console.log( console.log(
"============================================================\n", "============================================================\n",
@@ -184,16 +125,11 @@ const authOptions = (locale, req, res) => {
); );
const personalisation = { const personalisation = {
"emailAddress": email, emailAddress: email,
"signInLink": formURL, signInLink: formURL,
// locale == "cy" linkExpiry: 2 * 60 * 60
// ? url.split("&token")[0] +
// "/cy&token" +
// url.split("&token")[1]
// : url,
"linkExpiry": 2 * 60 * 60
}; };
const reference = "PEDW-SIGNIN"; const reference = "PEDW-SIGNIN";
var NotifyClient = var NotifyClient =
@@ -205,15 +141,15 @@ const authOptions = (locale, req, res) => {
await notifyClient await notifyClient
.sendEmail( .sendEmail(
effectiveLocale == "cy" ? templateIdcy : templateId, effectiveLocale === "cy"
emailAddress, ? templateIdcy
: templateId,
email,
{ {
personalisation: personalisation, personalisation,
reference: reference reference
// emailReplyToId: emailReplyToId,
} }
) )
//.then((response) => console.log(response))
.catch((error) => consoleLogger(error)); .catch((error) => consoleLogger(error));
} }
}) })
@@ -227,7 +163,7 @@ const authOptions = (locale, req, res) => {
theme: "dark", theme: "dark",
debug: true, debug: true,
maxAge: 30 * 60, maxAge: 30 * 60,
updateAge: 5 * 60 // 24 hours updateAge: 5 * 60
}, },
cookies: { cookies: {
callbackUrl: { callbackUrl: {
@@ -240,11 +176,11 @@ const authOptions = (locale, req, res) => {
} }
}, },
pages: { pages: {
signIn: (locale == "cy" ? "/cy" : "") + "/auth/signin", signIn: (locale === "cy" ? "/cy" : "") + "/auth/signin",
error: (locale == "cy" ? "/cy" : "") + "/auth/error", // Error code passed in query string as ?error= error: (locale === "cy" ? "/cy" : "") + "/auth/error",
verifyRequest: verifyRequest:
(locale == "cy" ? "/cy" : "") + "/auth/verify-request", // (used for check email message) (locale === "cy" ? "/cy" : "") + "/auth/verify-request",
newUser: (locale == "cy" ? "/cy" : "") + "/account/register" // New users will be directed here on first sign in (leave the property out if not of interest) newUser: (locale === "cy" ? "/cy" : "") + "/account/register"
}, },
callbacks: { callbacks: {
session: async (session, user) => { session: async (session, user) => {
@@ -253,28 +189,19 @@ const authOptions = (locale, req, res) => {
}, },
redirect({ url, baseUrl }) { redirect({ url, baseUrl }) {
//debugger;
console.log("baseurl:", url, baseUrl); 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; if (url.startsWith("/")) return `${baseUrl}${url}`;
let newUrl = if (new URL(url).origin === baseUrl) return url;
locale == "cy"
const effectiveLocale = resolveLocale(req);
const newUrl =
effectiveLocale === "cy"
? process.env.CY_API_ROOT ? process.env.CY_API_ROOT
: process.env.NEXTAUTH_URL; : process.env.NEXTAUTH_URL;
const updatedUrl = appendParamsAndPathToNewUrl( const updatedUrl = appendParamsAndPathToNewUrl(url, newUrl);
originalUrl,
newUrl
);
console.log(updatedUrl); console.log(updatedUrl);
//return baseUrl;
console.log("the url:", updatedUrl);
return updatedUrl; return updatedUrl;
} }
} }
@@ -282,14 +209,7 @@ const authOptions = (locale, req, res) => {
}; };
const NextAuthPEDW = (req, res) => { const NextAuthPEDW = (req, res) => {
//console.log("----------", authOptions(req.cookies["pedw_locale"])); return NextAuth(req, res, authOptions(req, res));
//console.log("----------",
return NextAuth(
req,
res,
authOptions(req.cookies["pedw_locale"], req, res)
);
}; };
export default NextAuthPEDW; export default NextAuthPEDW;
+20 -72
View File
@@ -7,55 +7,28 @@ import CookieBanner from "../../components/cookieBanner";
import Footer from "../../components/footer"; import Footer from "../../components/footer";
import Header from "../../components/header"; import Header from "../../components/header";
import ServiceBanner from "../../components/servicebanner"; import ServiceBanner from "../../components/servicebanner";
import { getPreferredLanguage } from "../../actions/services/accountService";
import { setCookie } from "nookies"; import { setCookie } from "nookies";
const SignIn = (props) => { const SignIn = (props) => {
let { t, lang } = useTranslation(); let { t, lang } = useTranslation();
const { footerLinks, pages, csrfToken, callbackUrl } = props; 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 [buttonDisabled, setButtonDisabled] = useState(false);
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
setButtonDisabled(true); 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 { setCookie(null, "pedw_locale", currentLocale, {
const res = await getPreferredLanguage(encodeURIComponent(email)); path: "/",
const data = await res; maxAge: 60 * 60 * 24 * 365
});
const userLang = event.target.callbackUrl.value = url.toString();
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.submit(); event.target.submit();
}; };
@@ -97,11 +70,7 @@ const SignIn = (props) => {
action="/api/auth/signin/email" action="/api/auth/signin/email"
onSubmit={handleSubmit} onSubmit={handleSubmit}
> >
<div <div className="govuk-form-group ">
className={
"govuk-form-group "
}
>
<input <input
className="govuk-input" className="govuk-input"
name="csrfToken" name="csrfToken"
@@ -129,7 +98,7 @@ const SignIn = (props) => {
</label> </label>
<input <input
className="govuk-input govuk-!-width-three-quarters" className="govuk-input govuk-!-width-three-quarters"
type="email" type="email"
id="email" id="email"
name="email" name="email"
@@ -175,44 +144,31 @@ export async function getServerSideProps(context) {
} }
const csrfToken = await getCsrfToken(context); const csrfToken = await getCsrfToken(context);
console.log(
"\n//////////////////////\n",
"Sign in callbackurl: " + context.query.callbackUrl,
context.locale,
"\n//////////////////////\n"
);
let formURL = context.req.headers.host;
//console.log("formUrl:", formURL);
let formURL = context.req.headers.host;
formURL = typeof formURL == "undefined" ? null : formURL; formURL = typeof formURL == "undefined" ? null : formURL;
let protocol = "http"; let protocol = "http";
if (context.req.headers["x-forwarded-proto"]) { if (context.req.headers["x-forwarded-proto"]) {
protocol = context.req.headers["x-forwarded-proto"]; protocol = context.req.headers["x-forwarded-proto"];
} } else if (context.req.connection.encrypted) {
// Otherwise, check if the connection is encrypted (for https)
else if (context.req.connection.encrypted) {
protocol = "https"; protocol = "https";
} }
formURL = protocol + "://" + formURL; formURL = protocol + "://" + formURL;
console.log("Protocol:", protocol);
console.log("locale:", context.locale);
const appendParamsAndPathToNewUrl = (fromUrl, toUrl) => { const appendParamsAndPathToNewUrl = (fromUrl, toUrl) => {
const fromUrlObj = new URL(fromUrl); // Parse the source URL const fromUrlObj = new URL(fromUrl);
const params = fromUrlObj.searchParams; // Extract the query parameters const params = fromUrlObj.searchParams;
const toUrlObj = new URL(toUrl); // Parse the new domain URL const toUrlObj = new URL(toUrl);
toUrlObj.pathname = fromUrlObj.pathname; // Copy the path from the source URL toUrlObj.pathname = fromUrlObj.pathname;
// Append the query parameters to the new URL
params.forEach((value, key) => params.forEach((value, key) =>
toUrlObj.searchParams.append(key, value) toUrlObj.searchParams.append(key, value)
); );
return toUrlObj.toString(); // Return the full new URL as a string return toUrlObj.toString();
}; };
typeof context.query.callbackUrl != "undefined" && typeof context.query.callbackUrl != "undefined" &&
@@ -221,19 +177,11 @@ export async function getServerSideProps(context) {
formURL formURL
)); ));
//formURL = appendParamsAndPathToNewUrl(context.query.callbackUrl, formURL); const url = new URL(formURL);
url.searchParams.set("locale", context.locale || "en");
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());
return { return {
props: { csrfToken: csrfToken, callbackUrl: url.toString() } props: { csrfToken, callbackUrl: url.toString() }
}; };
} }