Merged PR 2315: Auth stabilistatiion and hardening

Related work items: #23020
This commit is contained in:
Robert Bond
2026-05-14 08:55:49 +00:00
parent d295a507ac
commit d0b2fd077a
41 changed files with 1462 additions and 418 deletions
@@ -169,20 +169,28 @@ export const addStatements = (options, ctx) => {
}; };
export const addFinalComments = (options, ctx) => { export const addFinalComments = (options, ctx) => {
const canSubmitFinalComments = const canSubmitFinalCommentsDefault =
ctx.isSelectedAppellant || ctx.isSelectedAppellant ||
ctx.isSelectedAgent || ctx.isSelectedAgent ||
ctx.isSelectedInterestedParty || ctx.isSelectedInterestedParty ||
ctx.isLPA; ctx.isLPA;
const canSubmitFinalComments = ctx.isDNS
? ctx.isLPA
: canSubmitFinalCommentsDefault;
const isSpecialistNonHearing = const isSpecialistNonHearing =
ctx.specialistProcess !== SPECIALIST_PROCESS.HEARING; ctx.specialistProcess !== SPECIALIST_PROCESS.HEARING;
const finalCommentsWindowStart = ctx.isDNS
? ctx.startDate
: ctx.statementDueDate;
const canAdd = const canAdd =
canSubmitFinalComments && canSubmitFinalComments &&
isWithinWindow( isWithinWindow(
ctx.now, ctx.now,
ctx.statementDueDate, finalCommentsWindowStart,
ctx.finalCommentsDueDate ctx.finalCommentsDueDate
) && ) &&
(ctx.appealType !== APPEAL_TYPES.HOUSEHOLDER || isSpecialistNonHearing); (ctx.appealType !== APPEAL_TYPES.HOUSEHOLDER || isSpecialistNonHearing);
+2 -10
View File
@@ -7,7 +7,7 @@ import { connect } from "react-redux";
import Banner from "../components/banner"; import Banner from "../components/banner";
import { setLogout } from "../store/accountDetails/action"; import { setLogout } from "../store/accountDetails/action";
import { signOut } from "next-auth/react"; import { performPortalSignOut } from "../lib/auth/sessionClient";
const Header = (props) => { const Header = (props) => {
let { t, lang } = useTranslation(); let { t, lang } = useTranslation();
@@ -84,15 +84,7 @@ const Header = (props) => {
} }
const handleLogout = () => { const handleLogout = () => {
console.info("////////////\n" + "logout" + "\n////////////"); performPortalSignOut(locale);
(window.localStorage.clear(),
destroyCookie(null, "next-auth.csrf-token", { path: "/" }),
destroyCookie(null, "next-auth.callback-url", { path: "/" }),
destroyCookie(null, "pedw_locale", { path: "/" }),
destroyCookie(null, "pinsUser", { path: "/" }),
signOut({
callbackUrl: locale == "cy" ? "/cy/allgofnodi" : "/logout"
}));
}; };
//const switchLocale = locale === "en" ? "cy" : "en"; //const switchLocale = locale === "en" ? "cy" : "en";
+2 -10
View File
@@ -2,7 +2,6 @@ import { signOut } from "next-auth/react";
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { destroyCookie } from "nookies";
import TimeOut from "../components/timeout"; import TimeOut from "../components/timeout";
import AwaitingSubmissionFromBlob from "./myportal/awaitingsubmissionfromblob"; import AwaitingSubmissionFromBlob from "./myportal/awaitingsubmissionfromblob";
@@ -17,6 +16,7 @@ import MySubmittedReps from "./myportal/mysubmittedrepresentations";
import ServiceBanner from "./myportal/servicebanner"; import ServiceBanner from "./myportal/servicebanner";
import { JSONPath as jsonpath } from "jsonpath-plus"; import { JSONPath as jsonpath } from "jsonpath-plus";
import transLookup from "../data/lookuptranslations.json"; import transLookup from "../data/lookuptranslations.json";
import { performPortalSignOut } from "../lib/auth/sessionClient";
const MyPortal = (props) => { const MyPortal = (props) => {
const { showFileUpload, showLoginCheck, docsOffline } = props; const { showFileUpload, showLoginCheck, docsOffline } = props;
@@ -26,15 +26,7 @@ const MyPortal = (props) => {
const { locale } = router; const { locale } = router;
const handleLogout = () => { const handleLogout = () => {
console.info("////////////\n" + "logout" + "\n////////////"); performPortalSignOut({ locale, signOutFn: signOut });
(window.localStorage.clear(),
destroyCookie(null, "next-auth.csrf-token", { path: "/" }),
destroyCookie(null, "next-auth.callback-url", { path: "/" }),
destroyCookie(null, "pedw_locale", { path: "/" }),
destroyCookie(null, "pinsUser", { path: "/" }),
signOut({
callbackUrl: locale == "cy" ? "/cy/allgofnodi" : "/logout"
}));
}; };
const isLPA = const isLPA =
+3 -13
View File
@@ -1,8 +1,7 @@
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import router from "next/router"; import router from "next/router";
import Link from "next/link"; import Link from "next/link";
import { destroyCookie } from "nookies"; import { performPortalSignOut } from "../../lib/auth/sessionClient";
import { signOut } from "next-auth/react";
const ServiceBanner = (props) => { const ServiceBanner = (props) => {
props = props.props; props = props.props;
@@ -19,23 +18,14 @@ const ServiceBanner = (props) => {
}; };
const handleLogout = (locale) => { const handleLogout = (locale) => {
console.info("////////////\n" + "logout" + "\n////////////"); performPortalSignOut(locale);
window.localStorage.clear(),
destroyCookie(null, "next-auth.csrf-token"),
{ path: "/" },
destroyCookie(null, "next-auth.callback-url", { path: "/" }),
destroyCookie(null, "pedw_locale", { path: "/" }),
destroyCookie(null, "pinsUser", { path: "/" }),
signOut({
callbackUrl: locale == "cy" ? "/cy/allgofnodi" : "/logout",
});
}; };
const portalLogoLink = [ const portalLogoLink = [
"/myportal/[appealtypes]", "/myportal/[appealtypes]",
"/newappeal", "/newappeal",
"/newappeal/[appealtypes]", "/newappeal/[appealtypes]",
"/myportal/representation", "/myportal/representation"
]; ];
return ( return (
<div className="servicebanner myportal govuk-!-margin-bottom-4"> <div className="servicebanner myportal govuk-!-margin-bottom-4">
+5 -14
View File
@@ -1,10 +1,9 @@
import { signOut } from "next-auth/react";
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { destroyCookie } from "nookies";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useIdleTimer } from "react-idle-timer"; import { useIdleTimer } from "react-idle-timer";
import TimeoutModal from "./timeoutmodal"; import TimeoutModal from "./timeoutmodal";
import { performPortalSignOut } from "../../lib/auth/sessionClient";
const TimeOut = (props) => { const TimeOut = (props) => {
let { t } = useTranslation(); let { t } = useTranslation();
@@ -20,15 +19,7 @@ const TimeOut = (props) => {
const onIdle = () => { const onIdle = () => {
setState("Idle"); setState("Idle");
console.info("////////////\n" + "logout" + "\n////////////"); performPortalSignOut(locale);
window.localStorage.clear(),
destroyCookie(null, "next-auth.csrf-token", { path: "/" }),
destroyCookie(null, "next-auth.callback-url", { path: "/" }),
destroyCookie(null, "pedw_locale", { path: "/" }),
destroyCookie(null, "pinsUser", { path: "/" }),
signOut({
callbackUrl: locale == "cy" ? "/cy/allgofnodi" : "/logout",
});
setOpen(false); setOpen(false);
}; };
@@ -48,7 +39,7 @@ const TimeOut = (props) => {
onPrompt, onPrompt,
timeout, timeout,
promptBeforeIdle, promptBeforeIdle,
throttle: 500, throttle: 500
}); });
useEffect(() => { useEffect(() => {
@@ -89,14 +80,14 @@ const TimeOut = (props) => {
<div <div
className={open ? "modal fade show" : "modal fade"} className={open ? "modal fade show" : "modal fade"}
style={{ style={{
display: open ? "flex" : "none", display: open ? "flex" : "none"
}} }}
> >
<div className="modal-dialog"> <div className="modal-dialog">
<div className="modal-content"> <div className="modal-content">
<h3> <h3>
{t("common:login-modal-message", { {t("common:login-modal-message", {
remaining: remaining, remaining: remaining
})} })}
</h3> </h3>
<button <button
+34
View File
@@ -0,0 +1,34 @@
# Auth & Session Reliability Notes
Last updated: 2026-05-13
## Known issue
Users are intermittently prompted to sign in again despite apparently valid prior session state.
## Confirmed risk contributors in code
1. Duplicated logout/cookie clearing logic across multiple components.
2. Mixed callback cookie names in runtime history (`next-auth.callback-url` and `__Secure-next-auth.callback-url`).
3. Redirect URL parsing that could fail hard on malformed/unexpected URL inputs.
4. Hard SSR redirects to `/auth/signin` on missing/transient upstream account/contact states.
## Stabilisation changes started
- Added `lib/auth/sessionClient.js`:
- normalized cookie/session artifact cleanup
- shared signed-out callback path by locale
- shared `performPortalSignOut(...)` helper
- Adopted helper in:
- `components/timeout/index.js`
- `components/myportal/servicebanner.js`
- `components/header.js`
- Updated NextAuth callback locale detection to check both callback cookie variants.
- Hardened NextAuth URL append and redirect parsing fallbacks.
## Remaining auth hardening backlog
1. Migrate remaining logout implementations to shared helper.
2. Add request-correlation-safe auth diagnostics (no secrets/tokens).
3. Evaluate session TTL/update strategy (`maxAge`, `updateAge`) with production evidence.
4. Add env validation checks for `NEXTAUTH_URL`, `CY_API_ROOT`, proxy/header assumptions.
+38
View File
@@ -0,0 +1,38 @@
# Current Platform State (PEDW) — feature/restart-from-sips
Last updated: 2026-05-13
## Summary
PEDW is in a **late-stage refactor stabilization** phase.
- New Appeal refactor stream (Slices 18) is complete per tracker/state docs.
- Representations stream remains structurally complex and only partially decomposed.
- Platform architecture direction remains valid: bounded, behaviour-preserving slices.
## What is complete
- New Appeal slice stream documented complete (`context/refactor-tracker.md`, `context/newappeal-refactor-current-state.md`).
- Significant route/breadcrumb decomposition and helper extraction completed.
- Broad endpoint contract hardening completed across key clusters.
## What is incomplete
- Auth/session reliability hardening (intermittent re-signin prompts).
- SSR loader resilience normalization across myportal/representation/new appeal.
- Logging hardening consistency in auth/file/account-sensitive paths.
- Remaining decomposition hotspots (`components/elements/index.js`, representation flow internals).
## Operational risk profile (current)
Top active risks:
1. Auth/session intermittency (callback/cookie/SSR timing interplay).
2. Fragile nested state assumptions in loader-heavy paths.
3. Production log noise and inconsistent redaction patterns.
4. Manual effort burden for EN/CY parity and journey regression checks.
## Notes on stale/legacy guidance
- Some context docs still describe pre-refactor representation baseline; treat those as historical unless updated by active slice evidence.
- Legacy commented code remains in active files (especially journey files) and should be treated as cleanup debt, not source-of-truth runtime behaviour.
@@ -0,0 +1,29 @@
# Performance & Stability Baseline (Phase 1)
Last updated: 2026-05-13
## Baseline observations
### Performance
- Loader-heavy pages (myportal/representation/new appeal) perform multiple external calls per SSR request.
- Form XML is read/normalized repeatedly from disk in SSR path.
- Some large components still combine orchestration + rendering, increasing rerender work.
### Stability
- Several SSR/data paths assume nested API response shapes without guard rails.
- Representation resume/new loader had crash/redirect fragility around missing contact/representation objects.
- Logging noise can mask actionable failure signals.
## Changes started in this phase
1. Added in-memory XML cache in `lib/forms/readFormXml.js` (safe, process-local).
2. Added null/redirect guards in `lib/representation/pageLoaders.js` for missing user/contact and missing representation entry.
3. Began auth-path de-duplication and redirect hardening (see auth reliability doc).
## Next baseline improvements
1. Add guarded defaults in remaining loader paths (`loadNewAppealPage`, myportal page loaders).
2. Introduce structured non-sensitive SSR failure telemetry for dependency failures.
3. Expand bounded concurrency/parallelism where safe and contract-preserving.
+62
View File
@@ -0,0 +1,62 @@
# Phase 1 Stabilisation Plan (Execution Start)
Last updated: 2026-05-14
## Goal
Reduce operational risk without changing PEDW business behaviour.
## Priority order
1. **Auth/session reliability**
2. **SSR/data-loading resilience**
3. **Logging/observability hardening**
4. **Low-risk performance improvements**
## Slice plan
### Slice P0.1 (started)
- Centralize client-side signout/cookie cleanup into shared helper.
- Replace duplicated logout logic in timeout and portal/header surfaces.
Status: completed across timeout, header, service banner, myportal, furtherdetails, and auth error paths.
### Slice P0.2 (started)
- Harden NextAuth redirect/locale callback handling.
- Add safer URL parsing fallback behaviour.
Status: completed with callback-cookie parity support and redacted diagnostics.
### Slice P1.1 (started)
- Add defensive null and redirect handling in representation SSR loader path.
Status: expanded to new appeal, myportal appeal, and representation loader guard hardening.
### Slice P3.1 (started)
- Add in-memory XML read cache for form XML to reduce repeated disk read/normalization cost.
Status: completed.
## Immediate slices status (updated)
1. Add defensive wrappers for external dependency failures in new-appeal/myportal/representation SSR loaders (fallback redirects + safe defaults).
- Status: completed.
2. Expand focused tests around loader negative paths (missing query/session/cookie/search result branches).
- Status: completed with dedicated phase22 suites for newappeal, myportal, and representation loaders.
3. Add lightweight diagnostics for SSR loader dependency failures (redacted, non-sensitive).
- Status: completed.
4. Reduce remaining low-value commented legacy blocks in active flow files where behaviour is already covered by tests.
- Status: completed for active myportal case-ticket page path.
## Next recommended Phase 1 closure slices
1. Add targeted loader-dependency-failure tests (thrown service errors -> safe redirect) for newappeal/myportal/representation loaders.
- Status: in progress (newappeal + myportal dependency-failure tests added; representation search-miss redirect coverage added).
2. Perform a focused pass on remaining active flow files for stale commented code/debug remnants and remove where behaviour is covered.
- Status: in progress (myportal case-ticket path completed; further active-flow pass still open).
3. Refresh current-platform-state/auth-session-reliability notes with latest implemented slices and residual risks.
- Status: not started.
+47
View File
@@ -0,0 +1,47 @@
import { destroyCookie } from "nookies";
import { signOut } from "next-auth/react";
const AUTH_COOKIE_CANDIDATES = [
"next-auth.csrf-token",
"next-auth.callback-url",
"__Secure-next-auth.callback-url",
"pedw_locale",
"pinsUser"
];
export const buildSignedOutCallbackUrl = (locale) =>
locale === "cy" ? "/cy/allgofnodi" : "/logout";
const resolveSignOutArgs = (args) => {
if (typeof args === "string") {
return {
locale: args,
callbackUrl: undefined,
signOutFn: signOut
};
}
return {
locale: args?.locale,
callbackUrl: args?.callbackUrl,
signOutFn: args?.signOutFn || signOut
};
};
export const clearSessionArtifacts = () => {
if (typeof window !== "undefined") {
window.localStorage.clear();
}
AUTH_COOKIE_CANDIDATES.forEach((cookieName) => {
destroyCookie(null, cookieName, { path: "/" });
});
};
export const performPortalSignOut = async (args) => {
const { locale, callbackUrl, signOutFn } = resolveSignOutArgs(args);
clearSessionArtifacts();
return signOutFn({
callbackUrl: callbackUrl || buildSignedOutCallbackUrl(locale)
});
};
+10
View File
@@ -2,6 +2,8 @@
import fs from "fs"; import fs from "fs";
import path from "path"; import path from "path";
const xmlCache = new Map();
/** /**
* Reads /data/formsxml/{appealtypes}.xml and normalises it. * Reads /data/formsxml/{appealtypes}.xml and normalises it.
* Returns { xmlStr } or throws on missing file. * Returns { xmlStr } or throws on missing file.
@@ -12,6 +14,12 @@ export function readFormXml(appealtypes) {
const configDirectory = path.resolve(process.cwd(), "data/formsxml"); const configDirectory = path.resolve(process.cwd(), "data/formsxml");
const filePath = path.join(configDirectory, `${appealtypes}.xml`); const filePath = path.join(configDirectory, `${appealtypes}.xml`);
const cacheKey = filePath;
const cached = xmlCache.get(cacheKey);
if (cached) {
return { xmlStr: cached, filePath, fromCache: true };
}
let xmlStr = fs.readFileSync(filePath, "utf8"); let xmlStr = fs.readFileSync(filePath, "utf8");
// Keep existing normalisation behaviour // Keep existing normalisation behaviour
@@ -20,5 +28,7 @@ export function readFormXml(appealtypes) {
xmlStr = xmlStr.replace(/> <"/g, "><"); xmlStr = xmlStr.replace(/> <"/g, "><");
xmlStr = xmlStr.toString(); xmlStr = xmlStr.toString();
xmlCache.set(cacheKey, xmlStr);
return { xmlStr, filePath }; return { xmlStr, filePath };
} }
+84 -12
View File
@@ -11,7 +11,7 @@ import {
getProgressFromBlob getProgressFromBlob
} from "../../actions/services/documentService"; } from "../../actions/services/documentService";
import { getPersonalAccount } from "../../actions/services/accountService"; import { getPersonalAccount } from "../../actions/services/accountService";
import { getIP } from "../../actions/core/logger"; import { consoleLogger, getIP } from "../../actions/core/logger";
import { readFormXml } from "../forms/readFormXml"; import { readFormXml } from "../forms/readFormXml";
import { requireQueryParams } from "../routing/requireQueryParams"; import { requireQueryParams } from "../routing/requireQueryParams";
@@ -32,11 +32,27 @@ export async function loadMyPortalAppealPage(ctx) {
"casereference" "casereference"
]); ]);
if (!required.ok) { if (!required.ok) {
consoleLogger({
name: "MyPortalAppealLoaderMissingQuery",
message:
"loadMyPortalAppealPage missing required query params; redirecting",
hasAppealType: !!query?.appealtypes,
hasAppealTypeId: !!query?.apt,
hasCaseReference: !!query?.casereference
});
return { redirect: required.redirect }; return { redirect: required.redirect };
} }
const session = await getSession(ctx); const session = await getSession(ctx);
if (!session) { if (!session || !session?.user?.id || !session?.user?.email) {
consoleLogger({
name: "MyPortalAppealLoaderMissingSession",
message:
"loadMyPortalAppealPage missing session identity; redirecting to signin",
hasSession: !!session,
hasUserId: !!session?.user?.id,
hasUserEmail: !!session?.user?.email
});
return { return {
redirect: { redirect: {
destination: "/auth/signin", destination: "/auth/signin",
@@ -50,21 +66,60 @@ export async function loadMyPortalAppealPage(ctx) {
const loggedInUserIdent = session.user.id; const loggedInUserIdent = session.user.id;
const loggedInUserEmail = session.user.email; const loggedInUserEmail = session.user.email;
const accountDetails = await getPersonalAccount(loggedInUser); if (!loggedInUser) {
consoleLogger({
name: "MyPortalAppealLoaderMissingPinsUserCookie",
message:
"loadMyPortalAppealPage missing pinsUser cookie; redirecting to signin"
});
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
}
// Fetch config + blob assets in parallel // Fetch config + blob assets in parallel
const [appealTypeData, mandatoryFieldsData, pickListData, blobList] = let appealTypeData;
await Promise.all([ let mandatoryFieldsData;
let pickListData;
let blobList;
let blobProgress;
let accountDetails;
try {
[
appealTypeData,
mandatoryFieldsData,
pickListData,
blobList,
blobProgress,
accountDetails
] = await Promise.all([
getAppealsTypesForNewAppeal(), getAppealsTypesForNewAppeal(),
getMandatoryFields(query.appealtypes), getMandatoryFields(query.appealtypes),
getPickLists(query.appealtypes), getPickLists(query.appealtypes),
getFilesFromBlob(loggedInUserIdent, query.casereference) getFilesFromBlob(loggedInUserIdent, query.casereference),
getProgressFromBlob(loggedInUserIdent, query.casereference),
getPersonalAccount(loggedInUser)
]); ]);
} catch (_error) {
const blobProgress = await getProgressFromBlob( consoleLogger({
loggedInUserIdent, name: "MyPortalAppealLoaderDependencyFailure",
query.casereference message:
); "loadMyPortalAppealPage dependency fetch failed; redirecting to /myportal",
appealType: query?.appealtypes,
hasCaseReference: !!query?.casereference,
error: _error?.message
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
// Optional: awaiting-submission view setup when query.key exists // Optional: awaiting-submission view setup when query.key exists
let awaitingSubmissionFromBlob = null; let awaitingSubmissionFromBlob = null;
@@ -74,7 +129,24 @@ export async function loadMyPortalAppealPage(ctx) {
); );
} }
const { xmlStr } = readFormXml(query.appealtypes); let xmlStr = "";
try {
xmlStr = readFormXml(query.appealtypes).xmlStr;
} catch (_error) {
consoleLogger({
name: "MyPortalAppealLoaderXmlReadFailure",
message:
"loadMyPortalAppealPage XML read failed; redirecting to /myportal",
appealType: query?.appealtypes,
error: _error?.message
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
return { return {
session, session,
+1 -1
View File
@@ -1,5 +1,5 @@
export const mergeWithExistingFilesList = (buildAppealFilesArray, values) => { export const mergeWithExistingFilesList = (buildAppealFilesArray, values) => {
return values.hasOwnProperty("filesList") return Object.prototype.hasOwnProperty.call(values, "filesList")
? (buildAppealFilesArray.concat(values.filesList), ? (buildAppealFilesArray.concat(values.filesList),
buildAppealFilesArray.filter(function (item, idx) { buildAppealFilesArray.filter(function (item, idx) {
return item.name; return item.name;
+89 -8
View File
@@ -7,7 +7,7 @@ import {
} from "../../actions/services/referenceDataService"; } from "../../actions/services/referenceDataService";
import { getProgressFromBlob } from "../../actions/services/documentService"; import { getProgressFromBlob } from "../../actions/services/documentService";
import { getPersonalAccount } from "../../actions/services/accountService"; import { getPersonalAccount } from "../../actions/services/accountService";
import { getIP } from "../../actions/core/logger"; import { consoleLogger, getIP } from "../../actions/core/logger";
import { readFormXml } from "../forms/readFormXml"; import { readFormXml } from "../forms/readFormXml";
import { requireQueryParams } from "../routing/requireQueryParams"; import { requireQueryParams } from "../routing/requireQueryParams";
@@ -29,6 +29,28 @@ export async function loadNewAppealPage(ctx) {
const session = await getSession(ctx); const session = await getSession(ctx);
if (!session) { if (!session) {
consoleLogger({
name: "NewAppealLoaderAuthGuard",
reasonCode: "NO_SESSION",
message: "loadNewAppealPage missing session; redirecting to signin"
});
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
}
if (!session?.user?.id || !session?.user?.email) {
consoleLogger({
name: "NewAppealLoaderAuthGuard",
reasonCode: "NO_SESSION_USER",
message:
"loadNewAppealPage missing session user identity; redirecting to signin",
hasSessionUserId: !!session?.user?.id,
hasSessionUserEmail: !!session?.user?.email
});
return { return {
redirect: { redirect: {
destination: "/auth/signin", destination: "/auth/signin",
@@ -42,17 +64,76 @@ export async function loadNewAppealPage(ctx) {
const loggedInUserIdent = session.user.id; const loggedInUserIdent = session.user.id;
const loggedInUserEmail = session.user.email; const loggedInUserEmail = session.user.email;
const [appealTypeData, mandatoryFieldsData, pickListData] = if (!loggedInUser) {
await Promise.all([ consoleLogger({
name: "NewAppealLoaderAuthGuard",
reasonCode: "NO_PINSUSER_COOKIE",
message:
"loadNewAppealPage missing pinsUser cookie identity; redirecting to signin"
});
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
}
let appealTypeData;
let mandatoryFieldsData;
let pickListData;
let blobProgress;
let accountDetails;
try {
[
appealTypeData,
mandatoryFieldsData,
pickListData,
blobProgress,
accountDetails
] = await Promise.all([
getAppealsTypesForNewAppeal(), getAppealsTypesForNewAppeal(),
getMandatoryFields(query.appealtypes), getMandatoryFields(query.appealtypes),
getPickLists(query.appealtypes) getPickLists(query.appealtypes),
getProgressFromBlob(loggedInUserIdent, query.id),
getPersonalAccount(loggedInUser)
]); ]);
} catch (_error) {
consoleLogger({
name: "NewAppealLoaderDependencyFailure",
message:
"loadNewAppealPage dependency fetch failed; redirecting to /myportal",
appealType: query?.appealtypes,
hasCaseId: !!query?.id,
error: _error?.message
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
const blobProgress = await getProgressFromBlob(loggedInUserIdent, query.id); let xmlStr = "";
const accountDetails = await getPersonalAccount(loggedInUser); try {
xmlStr = readFormXml(query.appealtypes).xmlStr;
const { xmlStr } = readFormXml(query.appealtypes); } catch (_error) {
consoleLogger({
name: "NewAppealLoaderXmlReadFailure",
message:
"loadNewAppealPage XML read failed; redirecting to /myportal",
appealType: query?.appealtypes,
error: _error?.message
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
return { return {
session, session,
+121 -45
View File
@@ -9,6 +9,7 @@ import {
} from "../../actions/services/caseService"; } from "../../actions/services/caseService";
import { getRepsFromBlob } from "../../actions/services/documentService"; import { getRepsFromBlob } from "../../actions/services/documentService";
import { getBasicSearch } from "../../actions/services/searchService"; import { getBasicSearch } from "../../actions/services/searchService";
import { consoleLogger } from "../../actions/core/logger";
import { import {
getFormCollectionByID, getFormCollectionByID,
getSearchDetails getSearchDetails
@@ -41,7 +42,7 @@ const getDetails = (resultsObj, detailsType) => {
detailsType == "mySubmittedReps" ? resultsObj : resultsObj.value; detailsType == "mySubmittedReps" ? resultsObj : resultsObj.value;
if (detailsType == "myRepresentations") { if (detailsType == "myRepresentations") {
const repsObj = resultsObj.map((searchDetail, index) => { resultsObj.map((searchDetail) => {
detailsArr.push( detailsArr.push(
getCase(searchDetail["incidentID"]).then((data) => { getCase(searchDetail["incidentID"]).then((data) => {
let caseID = ""; let caseID = "";
@@ -75,19 +76,21 @@ const getDetails = (resultsObj, detailsType) => {
} }
let detArr = Promise.all(detailsArr); let detArr = Promise.all(detailsArr);
console.log(detArr);
return detArr; return detArr;
}; };
export const loadRepresentationBootstrap = async ({ ctx }) => { export const loadRepresentationBootstrap = async ({ ctx }) => {
const { query } = ctx; const { query } = ctx;
console.log("The query", query);
let thisSession = await getSession(ctx); let thisSession = await getSession(ctx);
let loggedInUser = {}; let loggedInUser = null;
if (!thisSession) { if (!thisSession) {
console.log("not has sesssion......."); consoleLogger({
name: "RepresentationLoaderMissingSession",
message:
"loadRepresentationBootstrap missing session; redirecting to signin"
});
return { return {
redirect: { redirect: {
destination: "/auth/signin", destination: "/auth/signin",
@@ -95,22 +98,28 @@ export const loadRepresentationBootstrap = async ({ ctx }) => {
} }
}; };
} else { } else {
[loggedInUser] = await Promise.all([ loggedInUser = await getPortalLogin(thisSession.user.email);
await getPortalLogin(thisSession.user.email) loggedInUser = loggedInUser?.value?.[0]?.contactid || null;
]); }
console.log( if (!loggedInUser) {
"=====//////////=====", consoleLogger({
thisSession, name: "RepresentationLoaderMissingContact",
thisSession.user.email, message:
loggedInUser "loadRepresentationBootstrap missing CRM contact id; redirecting to signin",
); hasSessionEmail: !!thisSession?.user?.email
loggedInUser = loggedInUser.value[0].contactid; });
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
} }
const [accountDetails, myRepresentations] = await Promise.all([ const [accountDetails, myRepresentations] = await Promise.all([
await getPersonalAccount(loggedInUser), getPersonalAccount(loggedInUser),
await getRepsFromBlob(thisSession.user.id) getRepsFromBlob(thisSession.user.id)
]); ]);
const myRepresentationsDetails = await getDetails( const myRepresentationsDetails = await getDetails(
@@ -118,10 +127,8 @@ export const loadRepresentationBootstrap = async ({ ctx }) => {
"myRepresentations" "myRepresentations"
); );
console.log(accountDetails);
const isLPA = const isLPA =
accountDetails[ accountDetails?.[
"pinswg_typeofinvolvement@OData.Community.Display.V1.FormattedValue" "pinswg_typeofinvolvement@OData.Community.Display.V1.FormattedValue"
] == "LPA" ] == "LPA"
? true ? true
@@ -148,9 +155,22 @@ export const loadExistingRepresentation = async ({ store, ctx, bootstrap }) => {
isLPA isLPA
} = bootstrap; } = bootstrap;
console.log("is lpa?:", isLPA);
const searchResultsObj = await getBasicSearch(query.case); const searchResultsObj = await getBasicSearch(query.case);
if (!searchResultsObj?.value?.[0]) {
consoleLogger({
name: "RepresentationExistingMissingSearchResult",
message:
"loadExistingRepresentation missing search result; redirecting to myportal",
hasCaseQuery: !!query?.case
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
const searchDetailsObj = await getSearchDetails(searchResultsObj); const searchDetailsObj = await getSearchDetails(searchResultsObj);
store.dispatch(setSearchResults(searchResultsObj)); store.dispatch(setSearchResults(searchResultsObj));
@@ -164,11 +184,26 @@ export const loadExistingRepresentation = async ({ store, ctx, bootstrap }) => {
} }
const result = findObjectByKeyValue( const result = findObjectByKeyValue(
myRepresentations.value, myRepresentations?.value || [],
"repfile_name", "repfile_name",
query.created query.created
); );
if (!result) {
consoleLogger({
name: "RepresentationExistingMissingBlobEntry",
message:
"loadExistingRepresentation missing representation blob entry; redirecting to myportal",
hasCreatedQuery: !!query?.created
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
store.dispatch( store.dispatch(
setCurrentReference({ setCurrentReference({
"ticketnumber": "ticketnumber":
@@ -206,6 +241,21 @@ export const loadNewRepresentation = async ({ store, ctx, bootstrap }) => {
const { thisSession, accountDetails } = bootstrap; const { thisSession, accountDetails } = bootstrap;
const searchResultsObj = await getBasicSearch(query.case); const searchResultsObj = await getBasicSearch(query.case);
if (!searchResultsObj?.value?.[0]) {
consoleLogger({
name: "RepresentationNewMissingSearchResult",
message:
"loadNewRepresentation missing search result; redirecting to myportal",
hasCaseQuery: !!query?.case
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
const searchDetailsObj = await getSearchDetails(searchResultsObj); const searchDetailsObj = await getSearchDetails(searchResultsObj);
store.dispatch(setContainerID(thisSession.user.id)); store.dispatch(setContainerID(thisSession.user.id));
@@ -219,31 +269,26 @@ export const loadNewRepresentation = async ({ store, ctx, bootstrap }) => {
}) })
); );
console.log(
accountDetails,
"===================== is nrw",
accountDetails.emailaddress1.includes(process.env.NRWDOMAIN),
"===================== "
);
store.dispatch( store.dispatch(
setCurrentReference({ setCurrentReference({
"isNRW": "isNRW":
accountDetails.emailaddress1.includes(process.env.NRWDOMAIN) || accountDetails?.emailaddress1?.includes(
false, process.env.NRWDOMAIN
"ticketnumber": searchResultsObj.value[0].ticketnumber, ) || false,
"currentReference": searchResultsObj.value[0].title, "ticketnumber": searchResultsObj?.value?.[0]?.ticketnumber,
"currentReference": searchResultsObj?.value?.[0]?.title,
"currentType": "myRepresentations", "currentType": "myRepresentations",
"incidentid": searchResultsObj.value[0].incidentid, "incidentid": searchResultsObj?.value?.[0]?.incidentid,
"appealType": searchResultsObj.value[0].pinswg_appealcasetype, "appealType": searchResultsObj?.value?.[0]?.pinswg_appealcasetype,
"specialistProcess": "specialistProcess":
searchDetailsObj[0].value[0].pinswg_speacialistcaseprocess != searchDetailsObj?.[0]?.value?.[0]
null || ?.pinswg_speacialistcaseprocess != null ||
searchDetailsObj[0].value[0].pinswg_specialistcaseprocess != searchDetailsObj?.[0]?.value?.[0]
null ?.pinswg_specialistcaseprocess != null
? searchDetailsObj[0].value[0] ? searchDetailsObj?.[0]?.value?.[0]
.pinswg_speacialistcaseprocess || .pinswg_speacialistcaseprocess ||
searchDetailsObj[0].value[0].pinswg_specialistcaseprocess searchDetailsObj?.[0]?.value?.[0]
.pinswg_specialistcaseprocess
: "" : ""
}) })
); );
@@ -259,15 +304,46 @@ export const loadNewRepresentation = async ({ store, ctx, bootstrap }) => {
}; };
export const loadRepresentationPage = async ({ store, ctx }) => { export const loadRepresentationPage = async ({ store, ctx }) => {
const { query } = ctx;
if (!query?.case) {
consoleLogger({
name: "RepresentationLoaderMissingCaseQuery",
message:
"loadRepresentationPage missing case query; redirecting to myportal"
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
if (
Object.prototype.hasOwnProperty.call(query, "state") &&
!query?.created
) {
consoleLogger({
name: "RepresentationLoaderMissingCreatedQuery",
message:
"loadRepresentationPage missing created query for state flow; redirecting to myportal"
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
const bootstrap = await loadRepresentationBootstrap({ ctx }); const bootstrap = await loadRepresentationBootstrap({ ctx });
if (bootstrap?.redirect) { if (bootstrap?.redirect) {
return bootstrap; return bootstrap;
} }
const { query } = ctx; if (Object.prototype.hasOwnProperty.call(query, "state")) {
if (query.hasOwnProperty("state")) {
return loadExistingRepresentation({ store, ctx, bootstrap }); return loadExistingRepresentation({ store, ctx, bootstrap });
} }
+73 -55
View File
@@ -14,35 +14,41 @@ import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client"; 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, redactSensitive } from "../../../actions/core/logger";
import { getPortalLogin } from "../../../actions/services/accountService"; import { getPortalLogin } from "../../../actions/services/accountService";
const prisma = new PrismaClient(); const prisma = new PrismaClient();
const WELSH_LANGUAGE_CODE = 846040000; const WELSH_LANGUAGE_CODE = 846040000;
const appendParamsAndPathToNewUrl = (fromUrl, toUrl) => { const authDiagnostic = (event, metadata = {}) => {
const fromUrlObj = new URL(fromUrl); try {
const params = fromUrlObj.searchParams; const safeMeta = JSON.parse(JSON.stringify(metadata));
console.info(`[auth][${event}]`, redactSensitive(safeMeta));
const toUrlObj = new URL(toUrl); } catch (_error) {
toUrlObj.pathname = fromUrlObj.pathname; console.info(`[auth][${event}]`);
}
params.forEach((value, key) => {
if (!toUrlObj.searchParams.has(key)) {
toUrlObj.searchParams.append(key, value);
}
});
return toUrlObj.toString();
}; };
// const resolveRequestLocale = (req) => { const appendParamsAndPathToNewUrl = (fromUrl, toUrl) => {
// const locale = try {
// req?.body?.locale || req?.query?.locale || req?.cookies?.pedw_locale; const fromUrlObj = new URL(fromUrl);
const params = fromUrlObj.searchParams;
// return locale === "cy" ? "cy" : "en"; const toUrlObj = new URL(toUrl);
// }; toUrlObj.pathname = fromUrlObj.pathname;
params.forEach((value, key) => {
if (!toUrlObj.searchParams.has(key)) {
toUrlObj.searchParams.append(key, value);
}
});
return toUrlObj.toString();
} catch (_error) {
return toUrl;
}
};
const resolveCrmLocale = async (email) => { const resolveCrmLocale = async (email) => {
if (!email) return null; if (!email) return null;
@@ -69,9 +75,20 @@ const resolveCrmLocale = async (email) => {
const resolveEffectiveLocale = async (req, email) => { const resolveEffectiveLocale = async (req, email) => {
const crmLocale = await resolveCrmLocale(email); const crmLocale = await resolveCrmLocale(email);
if (crmLocale) return crmLocale; if (crmLocale) {
authDiagnostic("effective-locale.crm", {
locale: crmLocale,
hasEmail: !!email
});
return crmLocale;
}
return resolveRequestLocale(req); const requestLocale = resolveRequestLocale(req);
authDiagnostic("effective-locale.request", {
locale: requestLocale,
hasEmail: !!email
});
return requestLocale;
}; };
const buildLocalizedVerificationUrl = ({ url, email, effectiveLocale }) => { const buildLocalizedVerificationUrl = ({ url, email, effectiveLocale }) => {
@@ -117,19 +134,35 @@ const getLocaleFromCallbackUrl = (callbackUrl) => {
const resolveRequestLocale = (req) => { const resolveRequestLocale = (req) => {
const directLocale = const directLocale =
req?.body?.locale || req?.query?.locale || req?.cookies?.pedw_locale; req?.query?.locale || req?.body?.locale || req?.cookies?.pedw_locale;
if (directLocale === "cy") return "cy"; if (directLocale === "cy") {
if (directLocale === "en") return "en"; authDiagnostic("request-locale.direct", { locale: "cy" });
return "cy";
}
if (directLocale === "en") {
authDiagnostic("request-locale.direct", { locale: "en" });
return "en";
}
const callbackLocale = const callbackLocale =
getLocaleFromCallbackUrl(req?.body?.callbackUrl) || getLocaleFromCallbackUrl(req?.body?.callbackUrl) ||
getLocaleFromCallbackUrl(req?.query?.callbackUrl) || getLocaleFromCallbackUrl(req?.query?.callbackUrl) ||
getLocaleFromCallbackUrl(req?.cookies?.["next-auth.callback-url"]) ||
getLocaleFromCallbackUrl( getLocaleFromCallbackUrl(
req?.cookies?.["__Secure-next-auth.callback-url"] req?.cookies?.["__Secure-next-auth.callback-url"]
); );
return callbackLocale === "cy" ? "cy" : "en"; const resolved = callbackLocale === "cy" ? "cy" : "en";
authDiagnostic("request-locale.callback-fallback", {
locale: resolved,
hasBodyCallback: !!req?.body?.callbackUrl,
hasQueryCallback: !!req?.query?.callbackUrl,
hasLegacyCookieCallback: !!req?.cookies?.["next-auth.callback-url"],
hasSecureCookieCallback:
!!req?.cookies?.["__Secure-next-auth.callback-url"]
});
return resolved;
}; };
const authOptions = (req, res) => { const authOptions = (req, res) => {
@@ -147,24 +180,12 @@ const authOptions = (req, res) => {
email email
); );
console.log(
"============================================================\n",
"verification url API: " + url + "\n",
"============================================================\n"
);
const formURL = buildLocalizedVerificationUrl({ const formURL = buildLocalizedVerificationUrl({
url, url,
email, email,
effectiveLocale effectiveLocale
}); });
console.log(
"============================================================\n",
"new verification url----: " + formURL + "\n",
"============================================================\n"
);
return res return res
.writeHead(200, { "Content-Type": "application/json" }) .writeHead(200, { "Content-Type": "application/json" })
.json({ url: formURL }); .json({ url: formURL });
@@ -181,24 +202,12 @@ const authOptions = (req, res) => {
email email
); );
console.log(
"============================================================\n",
"verification url----: " + url + "\n",
"============================================================\n"
);
const formURL = buildLocalizedVerificationUrl({ const formURL = buildLocalizedVerificationUrl({
url, url,
email, email,
effectiveLocale effectiveLocale
}); });
console.log(
"============================================================\n",
"new verification url----: " + formURL + "\n",
"============================================================\n"
);
const personalisation = { const personalisation = {
emailAddress: email, emailAddress: email,
signInLink: formURL, signInLink: formURL,
@@ -261,15 +270,21 @@ const authOptions = (req, res) => {
}, },
callbacks: { callbacks: {
session: async (session, user) => { session: async (session, user) => {
console.log("callback in auth", session, user);
return Promise.resolve(session); return Promise.resolve(session);
}, },
redirect({ url, baseUrl }) { redirect({ url, baseUrl }) {
console.log("baseurl:", url, baseUrl);
if (url.startsWith("/")) return `${baseUrl}${url}`; if (url.startsWith("/")) return `${baseUrl}${url}`;
if (new URL(url).origin === baseUrl) return url;
try {
if (new URL(url).origin === baseUrl) return url;
} catch (_error) {
authDiagnostic("redirect.invalid-url", {
baseUrl,
hasUrl: !!url
});
return baseUrl;
}
const newUrl = const newUrl =
requestLocale === "cy" requestLocale === "cy"
@@ -277,7 +292,10 @@ const authOptions = (req, res) => {
: process.env.NEXTAUTH_URL; : process.env.NEXTAUTH_URL;
const updatedUrl = appendParamsAndPathToNewUrl(url, newUrl); const updatedUrl = appendParamsAndPathToNewUrl(url, newUrl);
console.log(updatedUrl); authDiagnostic("redirect.external-rewrite", {
locale: requestLocale,
targetOrigin: newUrl
});
return updatedUrl; return updatedUrl;
} }
} }
@@ -156,10 +156,10 @@ export default async function ApiProxy(req, res) {
queryUrl = queryUrl =
"pinswg_sipses?$count=true&$expand=pinswg_sipscase&$filter=_pinswg_projecttype_value eq " + "pinswg_sipses?$count=true&$expand=pinswg_sipscase&$filter=_pinswg_projecttype_value eq " +
searchString.projecttype + searchString.projecttype +
(searchString.hasOwnProperty("q") (Object.prototype.hasOwnProperty.call(searchString, "q")
? " and contains(pinswg_projectname, '" + searchString.q + "')" ? " and contains(pinswg_projectname, '" + searchString.q + "')"
: "") + : "") +
(searchString.hasOwnProperty("lpa") (Object.prototype.hasOwnProperty.call(searchString, "lpa")
? " and _pinswg_associatedlpa_value eq " + ? " and _pinswg_associatedlpa_value eq " +
searchString.lpa + searchString.lpa +
" " " "
+1 -1
View File
@@ -162,7 +162,7 @@ export default async function ApiProxy(req, res) {
"@odata.count": coordsObj["@odata.count"] "@odata.count": coordsObj["@odata.count"]
}; };
return req.query.hasOwnProperty("fordmw") return Object.prototype.hasOwnProperty.call(req.query, "fordmw")
? respondSuccess(res, updatedData) ? respondSuccess(res, updatedData)
: respondSuccess(res, coordsObj); : respondSuccess(res, coordsObj);
} catch (error) { } catch (error) {
+4 -1
View File
@@ -136,7 +136,10 @@ export default async function handler(req, res) {
return blobList; return blobList;
}; };
reqBodyobj = reqBodyobj?.hasOwnProperty("filesList") reqBodyobj = Object.prototype.hasOwnProperty.call(
reqBodyobj || {},
"filesList"
)
? cleanFilesList(reqBodyobj) ? cleanFilesList(reqBodyobj)
: reqBodyobj; : reqBodyobj;
+4 -8
View File
@@ -7,10 +7,10 @@ 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 { destroyCookie, setCookie } from "nookies";
import { useEffect } from "react"; import { useEffect } from "react";
import { getCsrfToken } from "next-auth/react"; import { getCsrfToken } from "next-auth/react";
import { clearSessionArtifacts } from "../../lib/auth/sessionClient";
const Error = (props) => { const Error = (props) => {
let { t, lang } = useTranslation(); let { t, lang } = useTranslation();
@@ -19,11 +19,7 @@ const Error = (props) => {
const { error } = useRouter().query; const { error } = useRouter().query;
useEffect(() => { useEffect(() => {
window.localStorage.clear(), clearSessionArtifacts();
destroyCookie(null, "next-auth.csrf-token", { path: "/" }),
destroyCookie(null, "next-auth.callback-url", { path: "/" }),
destroyCookie(null, "pedw_locale", { path: "/" }),
destroyCookie(null, "pinsUser", { path: "/" });
}, []); }, []);
const errors = { const errors = {
@@ -37,7 +33,7 @@ const Error = (props) => {
EmailSignin: t("auth:auth-error-EmailSignin-label"), EmailSignin: t("auth:auth-error-EmailSignin-label"),
CredentialsSignin: t("auth:auth-error-CredentialsSignin-label"), CredentialsSignin: t("auth:auth-error-CredentialsSignin-label"),
Verification: t("auth:auth-error-Verification-label"), Verification: t("auth:auth-error-Verification-label"),
default: t("auth:auth-error-default-label"), default: t("auth:auth-error-default-label")
}; };
const errorMessage = error && (errors[error] ?? errors.default); const errorMessage = error && (errors[error] ?? errors.default);
@@ -89,7 +85,7 @@ const Error = (props) => {
export async function getServerSideProps(context) { export async function getServerSideProps(context) {
const csrfToken = await getCsrfToken(context); const csrfToken = await getCsrfToken(context);
return { return {
props: { csrfToken }, props: { csrfToken }
}; };
} }
+1 -3
View File
@@ -141,9 +141,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
if (thisSession) { if (thisSession) {
console.log(" has sesssion......."); console.log(" has sesssion.......");
[loggedInUser] = await Promise.all([ loggedInUser = await getPortalLogin(thisSession.user.email);
await getPortalLogin(thisSession.user.email)
]);
loggedInUser = loggedInUser.value[0].contactid; loggedInUser = loggedInUser.value[0].contactid;
+2 -4
View File
@@ -112,9 +112,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
if (thisSession) { if (thisSession) {
console.log(" has sesssion......."); console.log(" has sesssion.......");
[loggedInUser] = await Promise.all([ loggedInUser = await getPortalLogin(thisSession.user.email);
await getPortalLogin(thisSession.user.email)
]);
loggedInUser = loggedInUser.value[0].contactid; loggedInUser = loggedInUser.value[0].contactid;
@@ -163,7 +161,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
: "pinswg_siteaddressline1"; : "pinswg_siteaddressline1";
store.dispatch( store.dispatch(
req.headers.hasOwnProperty("referer") Object.prototype.hasOwnProperty.call(req.headers, "referer")
? req.headers.referer.indexOf("?") > -1 ? req.headers.referer.indexOf("?") > -1
? setSearch(req.headers.referer.split("?")[1]) ? setSearch(req.headers.referer.split("?")[1])
: setSearch( : setSearch(
+9 -3
View File
@@ -141,7 +141,10 @@ const RenderMultiline = ({
className={className} className={className}
{...input} {...input}
maxLength={ maxLength={
custom.hasOwnProperty("maxFieldLength") Object.prototype.hasOwnProperty.call(
custom,
"maxFieldLength"
)
? custom.maxFieldLength ? custom.maxFieldLength
? custom.maxFieldLength ? custom.maxFieldLength
: 800 : 800
@@ -190,14 +193,17 @@ const RenderTextfield = ({
name={id || name} name={id || name}
id={id || name} id={id || name}
maxLength={ maxLength={
custom.hasOwnProperty("maxFieldLength") Object.prototype.hasOwnProperty.call(
custom,
"maxFieldLength"
)
? custom.maxFieldLength ? custom.maxFieldLength
? custom.maxFieldLength ? custom.maxFieldLength
: 100 : 100
: 200 : 200
} }
pattern={ pattern={
custom.hasOwnProperty("pattern") Object.prototype.hasOwnProperty.call(custom, "pattern")
? custom.pattern ? custom.pattern
: undefined : undefined
} }
+1 -3
View File
@@ -144,9 +144,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
if (thisSession) { if (thisSession) {
console.log(" has sesssion......."); console.log(" has sesssion.......");
[loggedInUser] = await Promise.all([ loggedInUser = await getPortalLogin(thisSession.user.email);
await getPortalLogin(thisSession.user.email)
]);
loggedInUser = loggedInUser.value[0].contactid; loggedInUser = loggedInUser.value[0].contactid;
+4 -8
View File
@@ -3,23 +3,19 @@ import { signOut } from "next-auth/react";
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import Head from "next/head"; import Head from "next/head";
import Link from "next/link"; import Link from "next/link";
import { destroyCookie } from "nookies"; import { useRouter } from "next/router";
import CookieBanner from "../components/cookieBanner"; 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 { performPortalSignOut } from "../lib/auth/sessionClient";
const FourOhFour = (props) => { const FourOhFour = (props) => {
let { t, lang } = useTranslation(); let { t, lang } = useTranslation();
const { footerLinks, pages } = props; const { footerLinks, pages } = props;
const { locale } = useRouter();
const handleLogout = () => { const handleLogout = () => {
console.info("////////////\n" + "logout" + "\n////////////"); performPortalSignOut({ locale, callbackUrl: "/", signOutFn: signOut });
window.localStorage.clear(),
destroyCookie(null, "next-auth.csrf-token", { path: "/" }),
destroyCookie(null, "next-auth.callback-url", { path: "/" }),
destroyCookie(null, "pedw_locale", { path: "/" }),
destroyCookie(null, "pinsUser", { path: "/" }),
signOut({ callbackUrl: "/" });
}; };
return ( return (
+7 -7
View File
@@ -140,7 +140,7 @@ const Home = (props) => {
export const getServerSideProps = wrapper.getServerSideProps( export const getServerSideProps = wrapper.getServerSideProps(
(store) => async (ctx) => { (store) => async (ctx) => {
const { query, req, res } = ctx; const { query, req } = ctx;
getIP(req); getIP(req);
const searchResultsObj = await getAddressSearch(query); const searchResultsObj = await getAddressSearch(query);
const searchDetailsObj = searchResultsObj; const searchDetailsObj = searchResultsObj;
@@ -168,14 +168,14 @@ export const getServerSideProps = wrapper.getServerSideProps(
const [accountDetails, searchResultsObj, watchedCases] = const [accountDetails, searchResultsObj, watchedCases] =
await Promise.all([ await Promise.all([
await getPersonalAccount(loggedInUser), getPersonalAccount(loggedInUser),
await getAdvancedSearch(query), getAdvancedSearch(query),
await getWatchedCases(loggedInUser) getWatchedCases(loggedInUser)
]); ]);
const [searchDetailsObj, watchedCasesDetails] = await Promise.all([ const [searchDetailsObj, watchedCasesDetails] = await Promise.all([
await getSearchDetails(searchResultsObj), getSearchDetails(searchResultsObj),
await getDetails(watchedCases, "myWatchedCases") getDetails(watchedCases, "myWatchedCases")
]); ]);
store.dispatch(setAccountDetails(accountDetails)); store.dispatch(setAccountDetails(accountDetails));
@@ -203,7 +203,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
const getDetails = (resultsObj, detailsType) => { const getDetails = (resultsObj, detailsType) => {
let detailsArr = []; let detailsArr = [];
resultsObj = resultsObj.value; resultsObj = resultsObj.value;
const detailsObj = resultsObj.map((searchDetail, index) => { const detailsObj = resultsObj.map((searchDetail) => {
if (searchDetail.pinswg_appealcasetype == null) { if (searchDetail.pinswg_appealcasetype == null) {
console.log( console.log(
detailsType != "myWatchedCases" detailsType != "myWatchedCases"
+87 -19
View File
@@ -2,7 +2,7 @@ import useTranslation from "next-translate/useTranslation";
import Head from "next/head"; import Head from "next/head";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { getIP } from "../../actions/core/logger"; import { consoleLogger, getIP } from "../../actions/core/logger";
import { import {
getPersonalAccount, getPersonalAccount,
getPortalLogin getPortalLogin
@@ -46,7 +46,6 @@ const Home = (props) => {
let { t, lang } = useTranslation(); let { t, lang } = useTranslation();
const router = useRouter(); const router = useRouter();
const { locale } = router;
const { appealtypes } = router.query; const { appealtypes } = router.query;
return ( return (
@@ -79,44 +78,98 @@ const Home = (props) => {
export const getServerSideProps = wrapper.getServerSideProps( export const getServerSideProps = wrapper.getServerSideProps(
(store) => async (ctx) => { (store) => async (ctx) => {
const { query, req, res } = ctx; const { query, req } = ctx;
getIP(req); getIP(req);
console.log("query-", query); console.log("query-", query);
//console.log("search array:", Object.entries(query)); //console.log("search array:", Object.entries(query));
const { cookies } = req;
const showLoginCheck = process.env.SHOWLOGIN || false; const showLoginCheck = process.env.SHOWLOGIN || false;
let thisSession = await getSession(ctx); let thisSession = await getSession(ctx);
let loggedInUser = await getPortalLogin(thisSession.user.email);
if (!thisSession) { if (!thisSession) {
console.log("not has sesssion......."); consoleLogger({
name: "MyPortalAdvancedSearchResultsAuthGuard",
reasonCode: "NO_SESSION",
message:
"advancedsearchresults loader missing session; redirecting to signin"
});
return { return {
redirect: { redirect: {
destination: "/auth/signin", destination: "/auth/signin",
permanent: false permanent: false
} }
}; };
} else { }
if (!thisSession?.user?.email || !thisSession?.user?.id) {
consoleLogger({
name: "MyPortalAdvancedSearchResultsAuthGuard",
reasonCode: "NO_SESSION_USER",
message:
"advancedsearchresults loader missing session user identity; redirecting to signin",
hasSessionUserEmail: !!thisSession?.user?.email,
hasSessionUserId: !!thisSession?.user?.id
});
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
}
let loggedInUser;
try {
const loggedInUserLookup = await getPortalLogin(
thisSession.user.email
);
loggedInUser = loggedInUserLookup?.value?.[0]?.contactid;
} catch (error) {
consoleLogger({
name: "MyPortalAdvancedSearchResultsAuthGuard",
reasonCode: "UPSTREAM_FAILURE",
message:
"advancedsearchresults loader portal login lookup failed; redirecting to signin",
error: error?.message
});
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
}
if (!loggedInUser) {
consoleLogger({
name: "MyPortalAdvancedSearchResultsAuthGuard",
reasonCode: "CONTACT_LOOKUP_FAILED",
message:
"advancedsearchresults loader missing CRM contact id; redirecting to signin"
});
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
}
try {
thisSession != false && thisSession != false &&
store.dispatch(setContainerID(thisSession.user.id)); store.dispatch(setContainerID(thisSession.user.id));
loggedInUser = await getPortalLogin(thisSession.user.email);
loggedInUser = loggedInUser.value[0].contactid;
const [accountDetails, watchedCases] = await Promise.all([ const [accountDetails, watchedCases] = await Promise.all([
await getPersonalAccount(loggedInUser), getPersonalAccount(loggedInUser),
await getWatchedCases(loggedInUser) getWatchedCases(loggedInUser)
]); ]);
console.log(accountDetails); console.log(accountDetails);
const [watchedCasesDetails] = await Promise.all([ const watchedCasesDetails = await getDetails(
await getDetails(watchedCases, "myWatchedCases") watchedCases,
]); "myWatchedCases"
);
const showLoginCheck = process.env.SHOWLOGIN || false; const showLoginCheck = process.env.SHOWLOGIN || false;
const showReps = process.env.SHOWREPRESENTATIONS || false; const showReps = process.env.SHOWREPRESENTATIONS || false;
@@ -127,7 +180,22 @@ export const getServerSideProps = wrapper.getServerSideProps(
store.dispatch(setWatchedCasesDetails(watchedCasesDetails)); store.dispatch(setWatchedCasesDetails(watchedCasesDetails));
store.dispatch(setSearch(Object.entries(query))); store.dispatch(setSearch(Object.entries(query)));
store.dispatch(setLoggedInUserId(loggedInUser)); store.dispatch(setLoggedInUserId(loggedInUser));
} catch (error) {
consoleLogger({
name: "MyPortalAdvancedSearchResultsAuthGuard",
reasonCode: "UPSTREAM_FAILURE",
message:
"advancedsearchresults loader dependency failure; redirecting to signin",
error: error?.message
});
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
} }
return { return {
props: { props: {
showLoginCheck: showLoginCheck showLoginCheck: showLoginCheck
@@ -139,7 +207,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
const getDetails = (resultsObj, detailsType) => { const getDetails = (resultsObj, detailsType) => {
let detailsArr = []; let detailsArr = [];
resultsObj = resultsObj.value; resultsObj = resultsObj.value;
const detailsObj = resultsObj.map((searchDetail, index) => { const detailsObj = resultsObj.map((searchDetail) => {
if (searchDetail.pinswg_appealcasetype == null) { if (searchDetail.pinswg_appealcasetype == null) {
console.log( console.log(
detailsType != "myWatchedCases" detailsType != "myWatchedCases"
+65 -112
View File
@@ -2,7 +2,7 @@ import useTranslation from "next-translate/useTranslation";
import Head from "next/head"; import Head from "next/head";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { getIP } from "../../../actions/core/logger"; import { consoleLogger, getIP } from "../../../actions/core/logger";
import { import {
getPersonalAccount, getPersonalAccount,
getPortalLogin getPortalLogin
@@ -61,17 +61,10 @@ import ServiceBanner from "../../../components/myportal/servicebanner";
import TimeOut from "../../../components/timeout"; import TimeOut from "../../../components/timeout";
const CaseHome = (props) => { const CaseHome = (props) => {
const { const { footerLinks } = props;
footerLinks, useTranslation();
pages,
setSearchResults,
setSearchDetails,
searchResultsObj
} = props;
let { t, lang } = useTranslation();
const router = useRouter(); const router = useRouter();
const { locale } = router;
const { ticketnumber } = router.query; const { ticketnumber } = router.query;
return ( return (
@@ -94,9 +87,6 @@ const CaseHome = (props) => {
props={props} props={props}
myCases={props.myCases.myCases} myCases={props.myCases.myCases}
myCasesDetails={props.myCases.myCasesDetails} myCasesDetails={props.myCases.myCasesDetails}
// directSearchResultsObj={
// props.searchResultsObj.searchResultsObj
// }
searchResultsObj={ searchResultsObj={
props.searchResultsObj.searchResultsObj props.searchResultsObj.searchResultsObj
} }
@@ -150,28 +140,44 @@ const CaseHome = (props) => {
export const getServerSideProps = wrapper.getServerSideProps( export const getServerSideProps = wrapper.getServerSideProps(
(store) => async (ctx) => { (store) => async (ctx) => {
const { query, req, res } = ctx; const { query, req } = ctx;
getIP(req); getIP(req);
const { cookies } = req;
console.log(cookies); consoleLogger({
console.log("the query :", query.ticketnumber); name: "MyPortalCaseTicketLoaderStart",
message: "myportal case ticket loader invoked",
console.log("viewkey: " + (query.hasOwnProperty("key") ? "yes" : "no")); hasTicketNumber: !!query?.ticketnumber,
hasViewKey: Object.prototype.hasOwnProperty.call(query, "key")
});
const showLoginCheck = process.env.SHOWLOGIN || false; const showLoginCheck = process.env.SHOWLOGIN || false;
let thisSession = await getSession(ctx); const thisSession = await getSession(ctx);
let loggedInUser = {}; let loggedInUser = {};
if (thisSession) { if (thisSession) {
console.log(" has sesssion......."); loggedInUser = await getPortalLogin(thisSession.user.email);
[loggedInUser] = await Promise.all([
await getPortalLogin(thisSession.user.email)
]);
loggedInUser = loggedInUser.value[0].contactid; loggedInUser = loggedInUser?.value?.[0]?.contactid;
if (!loggedInUser) {
consoleLogger({
name: "MyPortalCaseTicketMissingContact",
message:
"myportal case ticket loader missing CRM contact id; redirecting to signin",
hasSessionEmail: !!thisSession?.user?.email
});
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
}
} else { } else {
console.log("not has sesssion......."); consoleLogger({
name: "MyPortalCaseTicketMissingSession",
message:
"myportal case ticket loader missing session; redirecting to signin"
});
return { return {
redirect: { redirect: {
destination: "/auth/signin", destination: "/auth/signin",
@@ -191,22 +197,24 @@ export const getServerSideProps = wrapper.getServerSideProps(
store.dispatch(setAccountDetails(accountDetails)); store.dispatch(setAccountDetails(accountDetails));
store.dispatch(setLoggedInUserId(loggedInUser)); store.dispatch(setLoggedInUserId(loggedInUser));
let developmentQuery = query.ticketnumber; const developmentQuery = query.ticketnumber;
const pattern = /CAS-\d{5}-[A-Z0-9]{6}/; const pattern = /CAS-\d{5}-[A-Z0-9]{6}/;
const match = query.ticketnumber.match(pattern); const match = query.ticketnumber.match(pattern);
if (match) { if (!match) {
console.log("Match found!", match[0]); consoleLogger({
} else { name: "MyPortalCaseTicketUnexpectedFormat",
console.log("No match."); message: "ticketnumber does not match CAS expected format",
hasTicketNumber: !!query?.ticketnumber
});
} }
const searchResultsObj = await getBasicSearch(developmentQuery); const searchResultsObj = await getBasicSearch(developmentQuery);
const searchDetailsObj = await getSearchDetails(searchResultsObj); const searchDetailsObj = await getSearchDetails(searchResultsObj);
var eventsObj = {}; let eventsObj = {};
var mediaObj = {}; let mediaObj = {};
if (searchResultsObj.value[0].pinswg_appealcasetype == 846040002) { if (searchResultsObj.value[0].pinswg_appealcasetype == 846040002) {
eventsObj = await getSIPSEvents( eventsObj = await getSIPSEvents(
@@ -220,25 +228,16 @@ export const getServerSideProps = wrapper.getServerSideProps(
store.dispatch(setMediaDetails(mediaObj)); store.dispatch(setMediaDetails(mediaObj));
} }
//console.log(
// "\n======================================\n",
// searchResultsObj,
// "\n======================================\n"
// );
//console.log(
// "\n======================================\n",
// searchDetailsObj[0],
// "\n======================================\n"
// );
store.dispatch(setSearch(developmentQuery)); store.dispatch(setSearch(developmentQuery));
// console.log(
// searchResultsObj["@odata.count"] > 1 ||
// searchResultsObj["@odata.count"] < 1
// );
if (searchResultsObj["@odata.count"] < 1) { if (searchResultsObj["@odata.count"] < 1) {
consoleLogger({
name: "MyPortalCaseTicketSearchNotFound",
message:
"myportal case ticket loader search count < 1; redirecting to 404",
ticketnumber: query?.ticketnumber
});
return { return {
redirect: { redirect: {
destination: "/404", destination: "/404",
@@ -247,6 +246,13 @@ export const getServerSideProps = wrapper.getServerSideProps(
}; };
} else { } else {
if (searchResultsObj["@odata.count"] > 1) { if (searchResultsObj["@odata.count"] > 1) {
consoleLogger({
name: "MyPortalCaseTicketSearchAmbiguous",
message:
"myportal case ticket loader search count > 1; redirecting to 404",
ticketnumber: query?.ticketnumber,
count: searchResultsObj["@odata.count"]
});
return { return {
redirect: { redirect: {
//destination: "/dns-not-found", //destination: "/dns-not-found",
@@ -255,7 +261,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
} }
}; };
} else { } else {
if (query.hasOwnProperty("key")) { if (Object.prototype.hasOwnProperty.call(query, "key")) {
let whichViewKey = query.key; let whichViewKey = query.key;
switch (whichViewKey) { switch (whichViewKey) {
@@ -268,42 +274,6 @@ export const getServerSideProps = wrapper.getServerSideProps(
); );
break; break;
case "watchedCases": case "watchedCases":
// const watchedCases = await getWatchedCases(
// loggedInUser
// );
// let showWatchedCases = (submittedArr) => {
// const required = submittedArr.value.filter(
// (el) => {
// return (
// el.pinswg_representationsubmitted ==
// null
// );
// }
// );
// let newObj = {};
// return Object.assign(newObj, {
// "@odata.count": required.length,
// "value": required,
// });
// };
// let filteredWatchedCases =
// showWatchedCases(watchedCases);
// const watchedCasesDetails = await getDetails(
// filteredWatchedCases,
// "myWatchedCases"
// );
// store.dispatch(
// setWatchedCases(filteredWatchedCases)
// );
// store.dispatch(
// setWatchedCasesDetails(watchedCasesDetails)
// );
store.dispatch( store.dispatch(
setCurrentView({ setCurrentView({
"viewName": "Watched Cases", "viewName": "Watched Cases",
@@ -362,19 +332,19 @@ export const getServerSideProps = wrapper.getServerSideProps(
} }
const watchedCases = await getWatchedCases(loggedInUser); const watchedCases = await getWatchedCases(loggedInUser);
let showWatchedCases = (submittedArr) => { const showWatchedCases = (submittedArr) => {
const required = submittedArr.value.filter((el) => { const required = submittedArr.value.filter((el) => {
return el.pinswg_representationsubmitted == null; return el.pinswg_representationsubmitted == null;
}); });
let newObj = {}; const newObj = {};
return Object.assign(newObj, { return Object.assign(newObj, {
"@odata.count": required.length, "@odata.count": required.length,
"value": required "value": required
}); });
}; };
let filteredWatchedCases = showWatchedCases(watchedCases); const filteredWatchedCases = showWatchedCases(watchedCases);
const watchedCasesDetails = await getDetails( const watchedCasesDetails = await getDetails(
filteredWatchedCases, filteredWatchedCases,
@@ -415,9 +385,10 @@ export const getServerSideProps = wrapper.getServerSideProps(
(el) => el.pinswg_representationsubmitted != null (el) => el.pinswg_representationsubmitted != null
); );
const [mySubmittedRepsDetails] = await Promise.all([ const mySubmittedRepsDetails = await getDetails(
getDetails(mySubmittedReps, "mySubmittedReps") mySubmittedReps,
]); "mySubmittedReps"
);
store.dispatch(setMySubmittedReps(mySubmittedReps)); store.dispatch(setMySubmittedReps(mySubmittedReps));
store.dispatch( store.dispatch(
@@ -425,9 +396,6 @@ export const getServerSideProps = wrapper.getServerSideProps(
); );
} }
} }
//console.log(searchResultsObj);
//console.log(loggedInUser);
return { return {
props: { props: {
searchResultsObj: { searchResultsObj: {
@@ -455,7 +423,7 @@ const getDetails = (resultsObj, detailsType) => {
detailsType == "mySubmittedReps" ? resultsObj : resultsObj.value; detailsType == "mySubmittedReps" ? resultsObj : resultsObj.value;
if (detailsType == "myRepresentations") { if (detailsType == "myRepresentations") {
const repsObj = resultsObj.map((searchDetail, index) => { resultsObj.map((searchDetail) => {
detailsArr.push( detailsArr.push(
getCase(searchDetail["incidentID"]).then((data) => { getCase(searchDetail["incidentID"]).then((data) => {
let caseID = ""; let caseID = "";
@@ -488,7 +456,7 @@ const getDetails = (resultsObj, detailsType) => {
}); });
} }
const detailsObj = resultsObj.map((searchDetail, index) => { resultsObj.map((searchDetail) => {
let caseID = ""; let caseID = "";
switch (detailsType) { switch (detailsType) {
@@ -512,25 +480,17 @@ const getDetails = (resultsObj, detailsType) => {
caseID = searchDetail.pinswg_title; caseID = searchDetail.pinswg_title;
} }
//console.log(detailsType, " case id : ", caseID);
searchDetail.pinswg_appealcasetype != null && searchDetail.pinswg_appealcasetype != null &&
detailsArr.push( detailsArr.push(
getPortalModuleDetails( getPortalModuleDetails(
getFormCollectionByID(searchDetail.pinswg_appealcasetype) getFormCollectionByID(searchDetail.pinswg_appealcasetype)
.LogicalCollectionName, .LogicalCollectionName,
caseID caseID
// detailsType != "myWatchedCases"
// ? searchDetail.ticketnumber
// : searchDetail[
// "_pinswg_watchedcase_value@OData.Community.Display.V1.FormattedValue"
// ]
) )
); );
}); });
let detArr = Promise.all(detailsArr); const detArr = Promise.all(detailsArr);
console.log(detArr);
return detArr; return detArr;
}; };
@@ -539,7 +499,6 @@ const mapStateToProps = (state) => {
accountDetails: state.accountDetails, accountDetails: state.accountDetails,
currentView: state.currentView, currentView: state.currentView,
search: state.search, search: state.search,
//searchResultsObj: state.searchResultsObj,
documentDetailsObj: state.searchResultsObj.documentDetailsObj, documentDetailsObj: state.searchResultsObj.documentDetailsObj,
formData: state.formData, formData: state.formData,
appealType: state.appealType, appealType: state.appealType,
@@ -557,12 +516,6 @@ const mapDispatchToProps = (dispatch) => {
setCurrentReference: (currentReference) => { setCurrentReference: (currentReference) => {
dispatch(setCurrentReference(refno)); dispatch(setCurrentReference(refno));
}, },
// setSearchResults: (searchResults) => {
// dispatch(setSearchResults(searchResults));
// },
// setSearchDetails: (searchDetails) => {
// dispatch(setSearchDetails(searchDetails));
// },
setLoggedInUserId: (loggedInUser) => { setLoggedInUserId: (loggedInUser) => {
dispatch(setLoggedInUserId(loggedInUser)); dispatch(setLoggedInUserId(loggedInUser));
} }
+1 -3
View File
@@ -111,9 +111,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
if (thisSession) { if (thisSession) {
console.log(" has sesssion......."); console.log(" has sesssion.......");
[loggedInUser] = await Promise.all([ loggedInUser = await getPortalLogin(thisSession.user.email);
await getPortalLogin(thisSession.user.email)
]);
loggedInUser = loggedInUser.value[0].contactid; loggedInUser = loggedInUser.value[0].contactid;
+9 -3
View File
@@ -141,7 +141,10 @@ const RenderMultiline = ({
className={className} className={className}
{...input} {...input}
maxLength={ maxLength={
custom.hasOwnProperty("maxFieldLength") Object.prototype.hasOwnProperty.call(
custom,
"maxFieldLength"
)
? custom.maxFieldLength ? custom.maxFieldLength
? custom.maxFieldLength ? custom.maxFieldLength
: 800 : 800
@@ -190,14 +193,17 @@ const RenderTextfield = ({
name={id || name} name={id || name}
id={id || name} id={id || name}
maxLength={ maxLength={
custom.hasOwnProperty("maxFieldLength") Object.prototype.hasOwnProperty.call(
custom,
"maxFieldLength"
)
? custom.maxFieldLength ? custom.maxFieldLength
? custom.maxFieldLength ? custom.maxFieldLength
: 100 : 100
: 200 : 200
} }
pattern={ pattern={
custom.hasOwnProperty("pattern") Object.prototype.hasOwnProperty.call(custom, "pattern")
? custom.pattern ? custom.pattern
: undefined : undefined
} }
+1 -3
View File
@@ -142,9 +142,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
if (thisSession) { if (thisSession) {
console.log(" has sesssion......."); console.log(" has sesssion.......");
[loggedInUser] = await Promise.all([ loggedInUser = await getPortalLogin(thisSession.user.email);
await getPortalLogin(thisSession.user.email)
]);
loggedInUser = loggedInUser.value[0].contactid; loggedInUser = loggedInUser.value[0].contactid;
+8 -10
View File
@@ -44,7 +44,6 @@ const Home = (props) => {
let { t, lang } = useTranslation(); let { t, lang } = useTranslation();
const router = useRouter(); const router = useRouter();
const { locale } = router;
const { appealtypes } = router.query; const { appealtypes } = router.query;
return ( return (
@@ -142,14 +141,12 @@ export const getServerSideProps = wrapper.getServerSideProps(
getIP(req); getIP(req);
console.log("query-", query); console.log("query-", query);
const { cookies } = req;
res.setHeader( res.setHeader(
"Cache-Control", "Cache-Control",
"public, s-maxage=10, stale-while-revalidate=59" "public, s-maxage=10, stale-while-revalidate=59"
); );
let loggedInUser = cookies.pinsUser; let loggedInUser = req.cookies.pinsUser;
let thisSession = await getSession(ctx); let thisSession = await getSession(ctx);
@@ -163,8 +160,8 @@ export const getServerSideProps = wrapper.getServerSideProps(
}; };
} else { } else {
let [accountDetails, watchedCases] = await Promise.all([ let [accountDetails, watchedCases] = await Promise.all([
await getPersonalAccount(loggedInUser), getPersonalAccount(loggedInUser),
await getWatchedCases(loggedInUser) getWatchedCases(loggedInUser)
]); ]);
// searchResultsObj = // searchResultsObj =
@@ -178,9 +175,10 @@ export const getServerSideProps = wrapper.getServerSideProps(
const showMapCheck = process.env.SHOWMAPS || false; const showMapCheck = process.env.SHOWMAPS || false;
const [watchedCasesDetails] = await Promise.all([ const watchedCasesDetails = await getDetails(
await getDetails(watchedCases, "myWatchedCases") watchedCases,
]); "myWatchedCases"
);
const dnsCoords = await getDNSCoords(); const dnsCoords = await getDNSCoords();
// store.dispatch(setSearchResults(searchResultsObj)); // store.dispatch(setSearchResults(searchResultsObj));
// store.dispatch(setSearchDetails(searchDetailsObj)); // store.dispatch(setSearchDetails(searchDetailsObj));
@@ -201,7 +199,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
const getDetails = (resultsObj, detailsType) => { const getDetails = (resultsObj, detailsType) => {
let detailsArr = []; let detailsArr = [];
resultsObj = resultsObj.value; resultsObj = resultsObj.value;
const detailsObj = resultsObj.map((searchDetail, index) => { const detailsObj = resultsObj.map((searchDetail) => {
if (searchDetail.pinswg_appealcasetype == null) { if (searchDetail.pinswg_appealcasetype == null) {
console.log( console.log(
detailsType != "myWatchedCases" detailsType != "myWatchedCases"
+51 -4
View File
@@ -6,6 +6,7 @@ import { connect } from "react-redux";
import pLimit from "p-limit"; import pLimit from "p-limit";
import { getIP } from "../../actions/core/logger"; import { getIP } from "../../actions/core/logger";
import { consoleLogger } from "../../actions/core/logger";
import { import {
getPersonalAccount, getPersonalAccount,
getPortalLogin getPortalLogin
@@ -184,15 +185,49 @@ export const getServerSideProps = wrapper.getServerSideProps(
const thisSession = await getSession(ctx); const thisSession = await getSession(ctx);
if (!thisSession) { if (!thisSession) {
consoleLogger({
name: "MyPortalIndexAuthGuard",
reasonCode: "NO_SESSION",
message:
"myportal index loader missing session; redirecting to signin"
});
return { return {
redirect: { destination: "/auth/signin", permanent: false } redirect: { destination: "/auth/signin", permanent: false }
}; };
} }
const loggedInUserResponse = await getPortalLogin( if (!thisSession?.user?.email || !thisSession?.user?.id) {
thisSession.user.email consoleLogger({
); name: "MyPortalIndexAuthGuard",
const contacts = loggedInUserResponse?.value || []; reasonCode: "NO_SESSION_USER",
message:
"myportal index loader missing session user identity; redirecting to signin",
hasSessionUserEmail: !!thisSession?.user?.email,
hasSessionUserId: !!thisSession?.user?.id
});
return {
redirect: { destination: "/auth/signin", permanent: false }
};
}
let contacts = [];
try {
const loggedInUserResponse = await getPortalLogin(
thisSession.user.email
);
contacts = loggedInUserResponse?.value || [];
} catch (error) {
consoleLogger({
name: "MyPortalIndexAuthGuard",
reasonCode: "UPSTREAM_FAILURE",
message:
"myportal index loader portal login lookup failed; redirecting to signin",
error: error?.message
});
return {
redirect: { destination: "/auth/signin", permanent: false }
};
}
if (contacts.length > 1) { if (contacts.length > 1) {
return { return {
@@ -208,6 +243,18 @@ export const getServerSideProps = wrapper.getServerSideProps(
const loggedInUser = contacts[0]?.contactid; const loggedInUser = contacts[0]?.contactid;
if (!loggedInUser) {
consoleLogger({
name: "MyPortalIndexAuthGuard",
reasonCode: "CONTACT_LOOKUP_FAILED",
message:
"myportal index loader missing CRM contact id; redirecting to signin"
});
return {
redirect: { destination: "/auth/signin", permanent: false }
};
}
await createContainerProxy(thisSession.user.id); await createContainerProxy(thisSession.user.id);
const accountDetails = await getPersonalAccount(loggedInUser); const accountDetails = await getPersonalAccount(loggedInUser);
+5 -9
View File
@@ -77,14 +77,12 @@ const Home = (props) => {
export const getServerSideProps = wrapper.getServerSideProps( export const getServerSideProps = wrapper.getServerSideProps(
(store) => async (ctx) => { (store) => async (ctx) => {
const { query, req, res } = ctx; const { query, req } = ctx;
getIP(req); getIP(req);
console.log("query-", query); console.log("query-", query);
const { cookies } = req; const { cookies } = req;
let loggedInUserCookie = cookies.pinsUser;
let thisSession = await getSession(ctx); let thisSession = await getSession(ctx);
const showReps = process.env.SHOWREPRESENTATIONS || false; const showReps = process.env.SHOWREPRESENTATIONS || false;
@@ -100,9 +98,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
} }
}; };
} else { } else {
let [loggedInUser] = await Promise.all([ let loggedInUser = await getPortalLogin(thisSession.user.email);
await getPortalLogin(thisSession.user.email)
]);
//console.log("sssss", searchResultsObj); //console.log("sssss", searchResultsObj);
@@ -113,8 +109,8 @@ export const getServerSideProps = wrapper.getServerSideProps(
//console.log("sssss", loggedInUser); //console.log("sssss", loggedInUser);
const [accountDetails, watchedCasesDetails] = await Promise.all([ const [accountDetails, watchedCasesDetails] = await Promise.all([
await getPersonalAccount(loggedInUser), getPersonalAccount(loggedInUser),
await getDetails(watchedCases, "myWatchedCases") getDetails(watchedCases, "myWatchedCases")
]); ]);
store.dispatch(setAccountDetails(accountDetails)); store.dispatch(setAccountDetails(accountDetails));
store.dispatch(setSearch(query.q)); store.dispatch(setSearch(query.q));
@@ -136,7 +132,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
const getDetails = (resultsObj, detailsType) => { const getDetails = (resultsObj, detailsType) => {
let detailsArr = []; let detailsArr = [];
resultsObj = resultsObj.value; resultsObj = resultsObj.value;
const detailsObj = resultsObj.map((searchDetail, index) => { const detailsObj = resultsObj.map((searchDetail) => {
if (searchDetail.pinswg_appealcasetype == null) { if (searchDetail.pinswg_appealcasetype == null) {
console.log( console.log(
detailsType != "myWatchedCases" detailsType != "myWatchedCases"
+4 -1
View File
@@ -126,7 +126,10 @@ export const getServerSideProps = wrapper.getServerSideProps(
let caseObj = searchResultsObj.value[0] || {}; let caseObj = searchResultsObj.value[0] || {};
let hasUnsubscribed = caseObj.hasOwnProperty("pinswg_watchlistid"); let hasUnsubscribed = Object.prototype.hasOwnProperty.call(
caseObj,
"pinswg_watchlistid"
);
console.log("is there a caseObj", hasUnsubscribed); console.log("is there a caseObj", hasUnsubscribed);
+8
View File
@@ -10,6 +10,10 @@ const runRouteStateHelperTests = require("./route-state-helper.test.cjs");
const runBreadcrumbRouteMapsHelperTests = require("./breadcrumb-route-maps-helper.test.cjs"); const runBreadcrumbRouteMapsHelperTests = require("./breadcrumb-route-maps-helper.test.cjs");
const runBreadcrumbsRouteMapStructureTests = require("./breadcrumbs-route-map-structure.test.cjs"); const runBreadcrumbsRouteMapStructureTests = require("./breadcrumbs-route-map-structure.test.cjs");
const runRepresentationBuildRepsArrRulesTests = require("./representation-build-reps-arr-rules.test.cjs"); const runRepresentationBuildRepsArrRulesTests = require("./representation-build-reps-arr-rules.test.cjs");
const runSessionClientTests = require("./session-client-behaviour.test.cjs");
const runNewAppealLoaderGuardTests = require("./newappeal-loader-guards.test.cjs");
const runMyPortalLoaderGuardTests = require("./myportal-loader-guards.test.cjs");
const runRepresentationLoaderGuardTests = require("./representation-loader-guards.test.cjs");
const run = async () => { const run = async () => {
await runCoreTokenTests(); await runCoreTokenTests();
@@ -24,6 +28,10 @@ const run = async () => {
await runBreadcrumbRouteMapsHelperTests(); await runBreadcrumbRouteMapsHelperTests();
await runBreadcrumbsRouteMapStructureTests(); await runBreadcrumbsRouteMapStructureTests();
await runRepresentationBuildRepsArrRulesTests(); await runRepresentationBuildRepsArrRulesTests();
await runSessionClientTests();
await runNewAppealLoaderGuardTests();
await runMyPortalLoaderGuardTests();
await runRepresentationLoaderGuardTests();
console.log("Phase 22 combined suite passed."); console.log("Phase 22 combined suite passed.");
}; };
@@ -0,0 +1,122 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const vm = require("vm");
const tests = [];
const test = (name, fn) => tests.push({ name, fn });
const loadMyPortalLoader = (overrides = {}) => {
const filePath = path.join(
__dirname,
"..",
"..",
"lib",
"myportal",
"loadMyPortalAppealPage.js"
);
let source = fs.readFileSync(filePath, "utf8");
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
source = source.replace(
/export\s+async\s+function\s+loadMyPortalAppealPage/,
"async function loadMyPortalAppealPage"
);
source += "\nmodule.exports = { loadMyPortalAppealPage };\n";
const context = {
module: { exports: {} },
exports: {},
getSession: async () => ({ user: { id: "u-1", email: "x@y.z" } }),
getAppealsTypesForNewAppeal: async () => ({}),
getMandatoryFields: async () => ({}),
getPickLists: async () => ({}),
getFilesFromBlob: async () => ({}),
getProgressFromBlob: async () => ({}),
getPersonalAccount: async () => ({}),
getAwaitingSubmissionFromBlob: async () => ({}),
consoleLogger: () => {},
getIP: () => {},
readFormXml: () => ({ xmlStr: "<xml/>" }),
requireQueryParams: () => ({ ok: true }),
...overrides
};
vm.runInNewContext(source, context, { filename: filePath });
return context.module.exports;
};
test("myportal loader redirects to signin when session is missing", async () => {
const mod = loadMyPortalLoader({ getSession: async () => null });
const result = await mod.loadMyPortalAppealPage({
query: { appealtypes: "s78", apt: "1", casereference: "CAS-1" },
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("myportal loader redirects to signin when pinsUser cookie is missing", async () => {
const mod = loadMyPortalLoader();
const result = await mod.loadMyPortalAppealPage({
query: { appealtypes: "s78", apt: "1", casereference: "CAS-1" },
req: { cookies: {} }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("myportal loader returns query-param redirect when required query is missing", async () => {
const mod = loadMyPortalLoader({
requireQueryParams: () => ({
ok: false,
redirect: { destination: "/myportal", permanent: false }
})
});
const result = await mod.loadMyPortalAppealPage({
query: {},
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
test("myportal loader redirects to myportal when dependency fetch fails", async () => {
const mod = loadMyPortalLoader({
getMandatoryFields: async () => {
throw new Error("mandatory fields unavailable");
}
});
const result = await mod.loadMyPortalAppealPage({
query: { appealtypes: "s78", apt: "1", casereference: "CAS-1" },
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
const run = async () => {
let passed = 0;
for (const currentTest of tests) {
await currentTest.fn();
passed += 1;
}
console.log(
`Phase 22 myportal-loader-guards tests passed (${passed}/${tests.length}).`
);
};
module.exports = run;
if (require.main === module) {
run().catch((error) => {
console.error(error);
process.exit(1);
});
}
@@ -0,0 +1,122 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const vm = require("vm");
const tests = [];
const test = (name, fn) => tests.push({ name, fn });
const loadNewAppealLoader = (overrides = {}) => {
const filePath = path.join(
__dirname,
"..",
"..",
"lib",
"newappeal",
"loadNewAppealPage.js"
);
let source = fs.readFileSync(filePath, "utf8");
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
source = source.replace(
/export\s+async\s+function\s+loadNewAppealPage/,
"async function loadNewAppealPage"
);
source += "\nmodule.exports = { loadNewAppealPage };\n";
const context = {
module: { exports: {} },
exports: {},
getSession: async () => ({ user: { id: "u-1", email: "x@y.z" } }),
getAppealsTypesForNewAppeal: async () => ({}),
getMandatoryFields: async () => ({}),
getPickLists: async () => ({}),
getProgressFromBlob: async () => ({}),
getPersonalAccount: async () => ({}),
consoleLogger: () => {},
getIP: () => {},
readFormXml: () => ({ xmlStr: "<xml/>" }),
requireQueryParams: () => ({ ok: true }),
...overrides
};
vm.runInNewContext(source, context, { filename: filePath });
return context.module.exports;
};
test("newappeal loader redirects to signin when session is missing", async () => {
const mod = loadNewAppealLoader({
getSession: async () => null
});
const result = await mod.loadNewAppealPage({
query: { appealtypes: "s78", apt: "1", id: "CASE-1" },
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("newappeal loader redirects to signin when pinsUser cookie is missing", async () => {
const mod = loadNewAppealLoader();
const result = await mod.loadNewAppealPage({
query: { appealtypes: "s78", apt: "1", id: "CASE-1" },
req: { cookies: {} }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("newappeal loader returns query-param redirect when required query is missing", async () => {
const mod = loadNewAppealLoader({
requireQueryParams: () => ({
ok: false,
redirect: { destination: "/myportal", permanent: false }
})
});
const result = await mod.loadNewAppealPage({
query: {},
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
test("newappeal loader redirects to myportal when dependency fetch fails", async () => {
const mod = loadNewAppealLoader({
getMandatoryFields: async () => {
throw new Error("mandatory fields unavailable");
}
});
const result = await mod.loadNewAppealPage({
query: { appealtypes: "s78", apt: "1", id: "CASE-1" },
req: { cookies: { pinsUser: "contact-1" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
const run = async () => {
let passed = 0;
for (const currentTest of tests) {
await currentTest.fn();
passed += 1;
}
console.log(
`Phase 22 newappeal-loader-guards tests passed (${passed}/${tests.length}).`
);
};
module.exports = run;
if (require.main === module) {
run().catch((error) => {
console.error(error);
process.exit(1);
});
}
@@ -30,7 +30,8 @@ module.exports = {
const context = { const context = {
module: { exports: {} }, module: { exports: {} },
exports: {}, exports: {},
require require,
Date
}; };
vm.runInNewContext(source, context, { filename: filePath }); vm.runInNewContext(source, context, { filename: filePath });
@@ -67,8 +68,15 @@ const baseInput = (overrides = {}) => ({
...overrides ...overrides
}); });
const normalizeForAssertion = (value) =>
JSON.parse(JSON.stringify(value ?? null));
const buildOptions = (overrides = {}) => const buildOptions = (overrides = {}) =>
buildRepsArrFromContext(buildRepresentationContext(baseInput(overrides))); normalizeForAssertion(
buildRepsArrFromContext(
buildRepresentationContext(baseInput(overrides))
)
);
test("baseline truth-table: non-DNS non-SIPS across windows/capacities/ownership", () => { test("baseline truth-table: non-DNS non-SIPS across windows/capacities/ownership", () => {
const capacities = [ const capacities = [
@@ -227,13 +235,15 @@ test("DNS rules: statement/LIR ownership behaviour and questionnaire exclusion",
}; };
const dnsOptions = (overrides = {}) => const dnsOptions = (overrides = {}) =>
buildRepsArrFromContext( normalizeForAssertion(
buildRepresentationContext( buildRepsArrFromContext(
baseInput({ buildRepresentationContext(
appealType: APPEAL_TYPES.DNS, baseInput({
detailsObj: dnsDetails, appealType: APPEAL_TYPES.DNS,
...overrides detailsObj: dnsDetails,
}) ...overrides
})
)
) )
); );
@@ -339,59 +349,69 @@ test("deduplication and ordering are stable", () => {
test("invalid or missing dates suppress date-gated options but SIPS consultation persists", () => { test("invalid or missing dates suppress date-gated options but SIPS consultation persists", () => {
assert.deepStrictEqual( assert.deepStrictEqual(
buildRepsArrFromContext( normalizeForAssertion(
buildRepresentationContext( buildRepsArrFromContext(
baseInput({ buildRepresentationContext(
detailsObj: { baseInput({
pinswg_statementduedate: "2026-04-30T00:00:00.000Z", detailsObj: {
pinswg_finalcommentsduedate: "2026-05-25T00:00:00.000Z" pinswg_statementduedate: "2026-04-30T00:00:00.000Z",
} pinswg_finalcommentsduedate:
}) "2026-05-25T00:00:00.000Z"
}
})
)
) )
), ),
[] []
); );
assert.deepStrictEqual( assert.deepStrictEqual(
buildRepsArrFromContext( normalizeForAssertion(
buildRepresentationContext( buildRepsArrFromContext(
baseInput({ buildRepresentationContext(
detailsObj: { baseInput({
pinswg_startdate: "2026-04-01T00:00:00.000Z", detailsObj: {
pinswg_finalcommentsduedate: "2026-05-25T00:00:00.000Z" pinswg_startdate: "2026-04-01T00:00:00.000Z",
} pinswg_finalcommentsduedate:
}) "2026-05-25T00:00:00.000Z"
}
})
)
) )
), ),
[] []
); );
assert.deepStrictEqual( assert.deepStrictEqual(
buildRepsArrFromContext( normalizeForAssertion(
buildRepresentationContext( buildRepsArrFromContext(
baseInput({ buildRepresentationContext(
detailsObj: { baseInput({
pinswg_startdate: "2026-04-01T00:00:00.000Z", detailsObj: {
pinswg_statementduedate: "2026-04-30T00:00:00.000Z" pinswg_startdate: "2026-04-01T00:00:00.000Z",
}, pinswg_statementduedate: "2026-04-30T00:00:00.000Z"
involvementType: INVOLVEMENT_TYPES.LPA, },
now: new Date("2026-05-10T10:00:00.000Z") involvementType: INVOLVEMENT_TYPES.LPA,
}) now: new Date("2026-05-10T10:00:00.000Z")
})
)
) )
), ),
[] []
); );
assert.deepStrictEqual( assert.deepStrictEqual(
buildRepsArrFromContext( normalizeForAssertion(
buildRepresentationContext( buildRepsArrFromContext(
baseInput({ buildRepresentationContext(
appealType: APPEAL_TYPES.SIPS, baseInput({
detailsObj: {}, appealType: APPEAL_TYPES.SIPS,
selectedCapacity: "agent", detailsObj: {},
isNRW: true, selectedCapacity: "agent",
now: new Date("2026-06-20T10:00:00.000Z") isNRW: true,
}) now: new Date("2026-06-20T10:00:00.000Z")
})
)
) )
), ),
["Consultation Response", "Local Impact Report", "Marine Impact Report"] ["Consultation Response", "Local Impact Report", "Marine Impact Report"]
@@ -0,0 +1,136 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const vm = require("vm");
const tests = [];
const test = (name, fn) => tests.push({ name, fn });
const loadRepresentationLoaders = (overrides = {}) => {
const filePath = path.join(
__dirname,
"..",
"..",
"lib",
"representation",
"pageLoaders.js"
);
let source = fs.readFileSync(filePath, "utf8");
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
source = source.replace(/export\s+const\s+/g, "const ");
source +=
"\nmodule.exports = { loadRepresentationBootstrap, loadRepresentationPage };\n";
const context = {
module: { exports: {} },
exports: {},
getSession: async () => ({
user: { id: "u-1", email: "test@example.com" }
}),
getPortalLogin: async () => ({ value: [{ contactid: "contact-1" }] }),
getPersonalAccount: async () => ({ emailaddress1: "test@example.com" }),
getRepsFromBlob: async () => ({ value: [] }),
getBasicSearch: async () => ({
value: [
{
incidentid: "i-1",
ticketnumber: "CAS-1",
title: "Case",
pinswg_appealcasetype: 1
}
]
}),
getSearchDetails: async () => [{ value: [{}] }],
getCase: async () => ({}),
getPortalModuleDetails: async () => ({}),
getFormCollectionByID: () => ({ LogicalCollectionName: "x" }),
setAccountDetails: () => ({}),
setContainerID: () => ({}),
setCurrentReference: () => ({}),
setCurrentView: () => ({}),
setFilesForRepresentations: () => ({}),
setRepresentationCapacity: () => ({}),
setMyRepresentations: () => ({}),
setMyRepresentationsDetails: () => ({}),
setSearchDetails: () => ({}),
setSearchResults: () => ({}),
setSearch: () => ({}),
getRepsFilesBlobs: async () => ({}),
consoleLogger: () => {},
...overrides
};
vm.runInNewContext(source, context, { filename: filePath });
return context.module.exports;
};
test("representation bootstrap redirects to signin when session is missing", async () => {
const mod = loadRepresentationLoaders({ getSession: async () => null });
const result = await mod.loadRepresentationBootstrap({
ctx: { query: {} }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("representation bootstrap redirects to signin when contact is missing", async () => {
const mod = loadRepresentationLoaders({
getPortalLogin: async () => ({ value: [] })
});
const result = await mod.loadRepresentationBootstrap({
ctx: { query: {} }
});
assert.strictEqual(result.redirect.destination, "/auth/signin");
});
test("representation page redirects to myportal when case query is missing", async () => {
const mod = loadRepresentationLoaders();
const store = { dispatch: () => {} };
const result = await mod.loadRepresentationPage({
store,
ctx: { query: {} }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
test("representation page redirects to myportal when state exists but created is missing", async () => {
const mod = loadRepresentationLoaders();
const store = { dispatch: () => {} };
const result = await mod.loadRepresentationPage({
store,
ctx: { query: { case: "CAS-1", state: "x" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
test("representation page redirects to myportal when existing representation search has no result", async () => {
const mod = loadRepresentationLoaders({
getBasicSearch: async () => ({ value: [] })
});
const store = { dispatch: () => {} };
const result = await mod.loadRepresentationPage({
store,
ctx: { query: { case: "CAS-1", state: "x", created: "rep-1" } }
});
assert.strictEqual(result.redirect.destination, "/myportal");
});
const run = async () => {
let passed = 0;
for (const currentTest of tests) {
await currentTest.fn();
passed += 1;
}
console.log(
`Phase 22 representation-loader-guards tests passed (${passed}/${tests.length}).`
);
};
module.exports = run;
if (require.main === module) {
run().catch((error) => {
console.error(error);
process.exit(1);
});
}
@@ -0,0 +1,134 @@
const fs = require("fs");
const path = require("path");
const vm = require("vm");
const assert = require("assert");
const rootDir = path.resolve(__dirname, "..", "..");
const loadSessionClientModule = (injected = {}) => {
const filePath = path.join(rootDir, "lib", "auth", "sessionClient.js");
let source = fs.readFileSync(filePath, "utf8");
source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, "");
source = source.replace(/export const\s+/g, "const ");
source +=
"\nmodule.exports = { buildSignedOutCallbackUrl, clearSessionArtifacts, performPortalSignOut };\n";
const context = {
module: { exports: {} },
exports: {},
require,
window: {
localStorage: {
clear: () => {}
}
},
destroyCookie: () => {},
signOut: async () => ({}),
...injected
};
vm.runInNewContext(source, context, { filename: filePath });
return context.module.exports;
};
const tests = [];
const test = (name, fn) => tests.push({ name, fn });
test("auth/sessionClient callback URL helper returns EN/CY expected routes", async () => {
const mod = loadSessionClientModule();
assert.strictEqual(mod.buildSignedOutCallbackUrl("cy"), "/cy/allgofnodi");
assert.strictEqual(mod.buildSignedOutCallbackUrl("en"), "/logout");
assert.strictEqual(mod.buildSignedOutCallbackUrl(undefined), "/logout");
});
test("auth/sessionClient clearSessionArtifacts clears storage and known auth cookies", async () => {
const destroyed = [];
let clearCalls = 0;
const mod = loadSessionClientModule({
destroyCookie: (_ctx, name, opts) => {
destroyed.push({ name, opts });
},
window: {
localStorage: {
clear: () => {
clearCalls += 1;
}
}
}
});
mod.clearSessionArtifacts();
assert.strictEqual(clearCalls, 1);
assert.deepStrictEqual(
JSON.parse(JSON.stringify(destroyed.map((d) => d.name))),
[
"next-auth.csrf-token",
"next-auth.callback-url",
"__Secure-next-auth.callback-url",
"pedw_locale",
"pinsUser"
]
);
assert.strictEqual(
destroyed.every((d) => d.opts.path === "/"),
true
);
});
test("auth/sessionClient performPortalSignOut supports locale string argument", async () => {
const signOutCalls = [];
const mod = loadSessionClientModule({
signOut: async (args) => {
signOutCalls.push(args);
return { ok: true };
}
});
await mod.performPortalSignOut("cy");
assert.strictEqual(signOutCalls.length, 1);
assert.strictEqual(signOutCalls[0].callbackUrl, "/cy/allgofnodi");
});
test("auth/sessionClient performPortalSignOut supports callback override and injected signOut", async () => {
const signOutCalls = [];
const mod = loadSessionClientModule();
await mod.performPortalSignOut({
locale: "en",
callbackUrl: "/",
signOutFn: async (args) => {
signOutCalls.push(args);
return { ok: true };
}
});
assert.strictEqual(signOutCalls.length, 1);
assert.strictEqual(signOutCalls[0].callbackUrl, "/");
});
const run = async () => {
let passed = 0;
for (const currentTest of tests) {
await currentTest.fn();
passed += 1;
}
console.log(
`Phase 22 session-client tests passed (${passed}/${tests.length}).`
);
};
module.exports = run;
if (require.main === module) {
run().catch((error) => {
console.error(error);
process.exit(1);
});
}