Merged PR 2315: Auth stabilistatiion and hardening
Related work items: #23020
This commit is contained in:
@@ -169,20 +169,28 @@ export const addStatements = (options, ctx) => {
|
||||
};
|
||||
|
||||
export const addFinalComments = (options, ctx) => {
|
||||
const canSubmitFinalComments =
|
||||
const canSubmitFinalCommentsDefault =
|
||||
ctx.isSelectedAppellant ||
|
||||
ctx.isSelectedAgent ||
|
||||
ctx.isSelectedInterestedParty ||
|
||||
ctx.isLPA;
|
||||
|
||||
const canSubmitFinalComments = ctx.isDNS
|
||||
? ctx.isLPA
|
||||
: canSubmitFinalCommentsDefault;
|
||||
|
||||
const isSpecialistNonHearing =
|
||||
ctx.specialistProcess !== SPECIALIST_PROCESS.HEARING;
|
||||
|
||||
const finalCommentsWindowStart = ctx.isDNS
|
||||
? ctx.startDate
|
||||
: ctx.statementDueDate;
|
||||
|
||||
const canAdd =
|
||||
canSubmitFinalComments &&
|
||||
isWithinWindow(
|
||||
ctx.now,
|
||||
ctx.statementDueDate,
|
||||
finalCommentsWindowStart,
|
||||
ctx.finalCommentsDueDate
|
||||
) &&
|
||||
(ctx.appealType !== APPEAL_TYPES.HOUSEHOLDER || isSpecialistNonHearing);
|
||||
|
||||
+2
-10
@@ -7,7 +7,7 @@ import { connect } from "react-redux";
|
||||
import Banner from "../components/banner";
|
||||
import { setLogout } from "../store/accountDetails/action";
|
||||
|
||||
import { signOut } from "next-auth/react";
|
||||
import { performPortalSignOut } from "../lib/auth/sessionClient";
|
||||
|
||||
const Header = (props) => {
|
||||
let { t, lang } = useTranslation();
|
||||
@@ -84,15 +84,7 @@ const Header = (props) => {
|
||||
}
|
||||
|
||||
const handleLogout = () => {
|
||||
console.info("////////////\n" + "logout" + "\n////////////");
|
||||
(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"
|
||||
}));
|
||||
performPortalSignOut(locale);
|
||||
};
|
||||
|
||||
//const switchLocale = locale === "en" ? "cy" : "en";
|
||||
|
||||
+2
-10
@@ -2,7 +2,6 @@ import { signOut } from "next-auth/react";
|
||||
import useTranslation from "next-translate/useTranslation";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { destroyCookie } from "nookies";
|
||||
import TimeOut from "../components/timeout";
|
||||
import AwaitingSubmissionFromBlob from "./myportal/awaitingsubmissionfromblob";
|
||||
|
||||
@@ -17,6 +16,7 @@ import MySubmittedReps from "./myportal/mysubmittedrepresentations";
|
||||
import ServiceBanner from "./myportal/servicebanner";
|
||||
import { JSONPath as jsonpath } from "jsonpath-plus";
|
||||
import transLookup from "../data/lookuptranslations.json";
|
||||
import { performPortalSignOut } from "../lib/auth/sessionClient";
|
||||
|
||||
const MyPortal = (props) => {
|
||||
const { showFileUpload, showLoginCheck, docsOffline } = props;
|
||||
@@ -26,15 +26,7 @@ const MyPortal = (props) => {
|
||||
const { locale } = router;
|
||||
|
||||
const handleLogout = () => {
|
||||
console.info("////////////\n" + "logout" + "\n////////////");
|
||||
(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"
|
||||
}));
|
||||
performPortalSignOut({ locale, signOutFn: signOut });
|
||||
};
|
||||
|
||||
const isLPA =
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import useTranslation from "next-translate/useTranslation";
|
||||
import router from "next/router";
|
||||
import Link from "next/link";
|
||||
import { destroyCookie } from "nookies";
|
||||
import { signOut } from "next-auth/react";
|
||||
import { performPortalSignOut } from "../../lib/auth/sessionClient";
|
||||
|
||||
const ServiceBanner = (props) => {
|
||||
props = props.props;
|
||||
@@ -19,23 +18,14 @@ const ServiceBanner = (props) => {
|
||||
};
|
||||
|
||||
const handleLogout = (locale) => {
|
||||
console.info("////////////\n" + "logout" + "\n////////////");
|
||||
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",
|
||||
});
|
||||
performPortalSignOut(locale);
|
||||
};
|
||||
|
||||
const portalLogoLink = [
|
||||
"/myportal/[appealtypes]",
|
||||
"/newappeal",
|
||||
"/newappeal/[appealtypes]",
|
||||
"/myportal/representation",
|
||||
"/myportal/representation"
|
||||
];
|
||||
return (
|
||||
<div className="servicebanner myportal govuk-!-margin-bottom-4">
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { signOut } from "next-auth/react";
|
||||
import useTranslation from "next-translate/useTranslation";
|
||||
import { useRouter } from "next/router";
|
||||
import { destroyCookie } from "nookies";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useIdleTimer } from "react-idle-timer";
|
||||
import TimeoutModal from "./timeoutmodal";
|
||||
import { performPortalSignOut } from "../../lib/auth/sessionClient";
|
||||
|
||||
const TimeOut = (props) => {
|
||||
let { t } = useTranslation();
|
||||
@@ -20,15 +19,7 @@ const TimeOut = (props) => {
|
||||
|
||||
const onIdle = () => {
|
||||
setState("Idle");
|
||||
console.info("////////////\n" + "logout" + "\n////////////");
|
||||
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",
|
||||
});
|
||||
performPortalSignOut(locale);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
@@ -48,7 +39,7 @@ const TimeOut = (props) => {
|
||||
onPrompt,
|
||||
timeout,
|
||||
promptBeforeIdle,
|
||||
throttle: 500,
|
||||
throttle: 500
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -89,14 +80,14 @@ const TimeOut = (props) => {
|
||||
<div
|
||||
className={open ? "modal fade show" : "modal fade"}
|
||||
style={{
|
||||
display: open ? "flex" : "none",
|
||||
display: open ? "flex" : "none"
|
||||
}}
|
||||
>
|
||||
<div className="modal-dialog">
|
||||
<div className="modal-content">
|
||||
<h3>
|
||||
{t("common:login-modal-message", {
|
||||
remaining: remaining,
|
||||
remaining: remaining
|
||||
})}
|
||||
</h3>
|
||||
<button
|
||||
|
||||
@@ -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.
|
||||
@@ -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 1–8) 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.
|
||||
@@ -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.
|
||||
@@ -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)
|
||||
});
|
||||
};
|
||||
@@ -2,6 +2,8 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
const xmlCache = new Map();
|
||||
|
||||
/**
|
||||
* Reads /data/formsxml/{appealtypes}.xml and normalises it.
|
||||
* Returns { xmlStr } or throws on missing file.
|
||||
@@ -12,6 +14,12 @@ export function readFormXml(appealtypes) {
|
||||
const configDirectory = path.resolve(process.cwd(), "data/formsxml");
|
||||
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");
|
||||
|
||||
// Keep existing normalisation behaviour
|
||||
@@ -20,5 +28,7 @@ export function readFormXml(appealtypes) {
|
||||
xmlStr = xmlStr.replace(/> <"/g, "><");
|
||||
xmlStr = xmlStr.toString();
|
||||
|
||||
xmlCache.set(cacheKey, xmlStr);
|
||||
|
||||
return { xmlStr, filePath };
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
getProgressFromBlob
|
||||
} from "../../actions/services/documentService";
|
||||
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 { requireQueryParams } from "../routing/requireQueryParams";
|
||||
@@ -32,11 +32,27 @@ export async function loadMyPortalAppealPage(ctx) {
|
||||
"casereference"
|
||||
]);
|
||||
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 };
|
||||
}
|
||||
|
||||
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 {
|
||||
redirect: {
|
||||
destination: "/auth/signin",
|
||||
@@ -50,21 +66,60 @@ export async function loadMyPortalAppealPage(ctx) {
|
||||
const loggedInUserIdent = session.user.id;
|
||||
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
|
||||
const [appealTypeData, mandatoryFieldsData, pickListData, blobList] =
|
||||
await Promise.all([
|
||||
let appealTypeData;
|
||||
let mandatoryFieldsData;
|
||||
let pickListData;
|
||||
let blobList;
|
||||
let blobProgress;
|
||||
let accountDetails;
|
||||
|
||||
try {
|
||||
[
|
||||
appealTypeData,
|
||||
mandatoryFieldsData,
|
||||
pickListData,
|
||||
blobList,
|
||||
blobProgress,
|
||||
accountDetails
|
||||
] = await Promise.all([
|
||||
getAppealsTypesForNewAppeal(),
|
||||
getMandatoryFields(query.appealtypes),
|
||||
getPickLists(query.appealtypes),
|
||||
getFilesFromBlob(loggedInUserIdent, query.casereference)
|
||||
getFilesFromBlob(loggedInUserIdent, query.casereference),
|
||||
getProgressFromBlob(loggedInUserIdent, query.casereference),
|
||||
getPersonalAccount(loggedInUser)
|
||||
]);
|
||||
|
||||
const blobProgress = await getProgressFromBlob(
|
||||
loggedInUserIdent,
|
||||
query.casereference
|
||||
);
|
||||
} catch (_error) {
|
||||
consoleLogger({
|
||||
name: "MyPortalAppealLoaderDependencyFailure",
|
||||
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
|
||||
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 {
|
||||
session,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export const mergeWithExistingFilesList = (buildAppealFilesArray, values) => {
|
||||
return values.hasOwnProperty("filesList")
|
||||
return Object.prototype.hasOwnProperty.call(values, "filesList")
|
||||
? (buildAppealFilesArray.concat(values.filesList),
|
||||
buildAppealFilesArray.filter(function (item, idx) {
|
||||
return item.name;
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
} from "../../actions/services/referenceDataService";
|
||||
import { getProgressFromBlob } from "../../actions/services/documentService";
|
||||
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 { requireQueryParams } from "../routing/requireQueryParams";
|
||||
|
||||
@@ -29,6 +29,28 @@ export async function loadNewAppealPage(ctx) {
|
||||
|
||||
const session = await getSession(ctx);
|
||||
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 {
|
||||
redirect: {
|
||||
destination: "/auth/signin",
|
||||
@@ -42,17 +64,76 @@ export async function loadNewAppealPage(ctx) {
|
||||
const loggedInUserIdent = session.user.id;
|
||||
const loggedInUserEmail = session.user.email;
|
||||
|
||||
const [appealTypeData, mandatoryFieldsData, pickListData] =
|
||||
await Promise.all([
|
||||
if (!loggedInUser) {
|
||||
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(),
|
||||
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);
|
||||
const accountDetails = await getPersonalAccount(loggedInUser);
|
||||
|
||||
const { xmlStr } = readFormXml(query.appealtypes);
|
||||
let xmlStr = "";
|
||||
try {
|
||||
xmlStr = readFormXml(query.appealtypes).xmlStr;
|
||||
} 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 {
|
||||
session,
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "../../actions/services/caseService";
|
||||
import { getRepsFromBlob } from "../../actions/services/documentService";
|
||||
import { getBasicSearch } from "../../actions/services/searchService";
|
||||
import { consoleLogger } from "../../actions/core/logger";
|
||||
import {
|
||||
getFormCollectionByID,
|
||||
getSearchDetails
|
||||
@@ -41,7 +42,7 @@ const getDetails = (resultsObj, detailsType) => {
|
||||
detailsType == "mySubmittedReps" ? resultsObj : resultsObj.value;
|
||||
|
||||
if (detailsType == "myRepresentations") {
|
||||
const repsObj = resultsObj.map((searchDetail, index) => {
|
||||
resultsObj.map((searchDetail) => {
|
||||
detailsArr.push(
|
||||
getCase(searchDetail["incidentID"]).then((data) => {
|
||||
let caseID = "";
|
||||
@@ -75,19 +76,21 @@ const getDetails = (resultsObj, detailsType) => {
|
||||
}
|
||||
|
||||
let detArr = Promise.all(detailsArr);
|
||||
console.log(detArr);
|
||||
return detArr;
|
||||
};
|
||||
|
||||
export const loadRepresentationBootstrap = async ({ ctx }) => {
|
||||
const { query } = ctx;
|
||||
console.log("The query", query);
|
||||
|
||||
let thisSession = await getSession(ctx);
|
||||
let loggedInUser = {};
|
||||
let loggedInUser = null;
|
||||
|
||||
if (!thisSession) {
|
||||
console.log("not has sesssion.......");
|
||||
consoleLogger({
|
||||
name: "RepresentationLoaderMissingSession",
|
||||
message:
|
||||
"loadRepresentationBootstrap missing session; redirecting to signin"
|
||||
});
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/auth/signin",
|
||||
@@ -95,22 +98,28 @@ export const loadRepresentationBootstrap = async ({ ctx }) => {
|
||||
}
|
||||
};
|
||||
} else {
|
||||
[loggedInUser] = await Promise.all([
|
||||
await getPortalLogin(thisSession.user.email)
|
||||
]);
|
||||
loggedInUser = await getPortalLogin(thisSession.user.email);
|
||||
loggedInUser = loggedInUser?.value?.[0]?.contactid || null;
|
||||
}
|
||||
|
||||
console.log(
|
||||
"=====//////////=====",
|
||||
thisSession,
|
||||
thisSession.user.email,
|
||||
loggedInUser
|
||||
);
|
||||
loggedInUser = loggedInUser.value[0].contactid;
|
||||
if (!loggedInUser) {
|
||||
consoleLogger({
|
||||
name: "RepresentationLoaderMissingContact",
|
||||
message:
|
||||
"loadRepresentationBootstrap missing CRM contact id; redirecting to signin",
|
||||
hasSessionEmail: !!thisSession?.user?.email
|
||||
});
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/auth/signin",
|
||||
permanent: false
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const [accountDetails, myRepresentations] = await Promise.all([
|
||||
await getPersonalAccount(loggedInUser),
|
||||
await getRepsFromBlob(thisSession.user.id)
|
||||
getPersonalAccount(loggedInUser),
|
||||
getRepsFromBlob(thisSession.user.id)
|
||||
]);
|
||||
|
||||
const myRepresentationsDetails = await getDetails(
|
||||
@@ -118,10 +127,8 @@ export const loadRepresentationBootstrap = async ({ ctx }) => {
|
||||
"myRepresentations"
|
||||
);
|
||||
|
||||
console.log(accountDetails);
|
||||
|
||||
const isLPA =
|
||||
accountDetails[
|
||||
accountDetails?.[
|
||||
"pinswg_typeofinvolvement@OData.Community.Display.V1.FormattedValue"
|
||||
] == "LPA"
|
||||
? true
|
||||
@@ -148,9 +155,22 @@ export const loadExistingRepresentation = async ({ store, ctx, bootstrap }) => {
|
||||
isLPA
|
||||
} = bootstrap;
|
||||
|
||||
console.log("is lpa?:", isLPA);
|
||||
|
||||
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);
|
||||
|
||||
store.dispatch(setSearchResults(searchResultsObj));
|
||||
@@ -164,11 +184,26 @@ export const loadExistingRepresentation = async ({ store, ctx, bootstrap }) => {
|
||||
}
|
||||
|
||||
const result = findObjectByKeyValue(
|
||||
myRepresentations.value,
|
||||
myRepresentations?.value || [],
|
||||
"repfile_name",
|
||||
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(
|
||||
setCurrentReference({
|
||||
"ticketnumber":
|
||||
@@ -206,6 +241,21 @@ export const loadNewRepresentation = async ({ store, ctx, bootstrap }) => {
|
||||
const { thisSession, accountDetails } = bootstrap;
|
||||
|
||||
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);
|
||||
|
||||
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(
|
||||
setCurrentReference({
|
||||
"isNRW":
|
||||
accountDetails.emailaddress1.includes(process.env.NRWDOMAIN) ||
|
||||
false,
|
||||
"ticketnumber": searchResultsObj.value[0].ticketnumber,
|
||||
"currentReference": searchResultsObj.value[0].title,
|
||||
accountDetails?.emailaddress1?.includes(
|
||||
process.env.NRWDOMAIN
|
||||
) || false,
|
||||
"ticketnumber": searchResultsObj?.value?.[0]?.ticketnumber,
|
||||
"currentReference": searchResultsObj?.value?.[0]?.title,
|
||||
"currentType": "myRepresentations",
|
||||
"incidentid": searchResultsObj.value[0].incidentid,
|
||||
"appealType": searchResultsObj.value[0].pinswg_appealcasetype,
|
||||
"incidentid": searchResultsObj?.value?.[0]?.incidentid,
|
||||
"appealType": searchResultsObj?.value?.[0]?.pinswg_appealcasetype,
|
||||
"specialistProcess":
|
||||
searchDetailsObj[0].value[0].pinswg_speacialistcaseprocess !=
|
||||
null ||
|
||||
searchDetailsObj[0].value[0].pinswg_specialistcaseprocess !=
|
||||
null
|
||||
? searchDetailsObj[0].value[0]
|
||||
searchDetailsObj?.[0]?.value?.[0]
|
||||
?.pinswg_speacialistcaseprocess != null ||
|
||||
searchDetailsObj?.[0]?.value?.[0]
|
||||
?.pinswg_specialistcaseprocess != null
|
||||
? searchDetailsObj?.[0]?.value?.[0]
|
||||
.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 }) => {
|
||||
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 });
|
||||
|
||||
if (bootstrap?.redirect) {
|
||||
return bootstrap;
|
||||
}
|
||||
|
||||
const { query } = ctx;
|
||||
|
||||
if (query.hasOwnProperty("state")) {
|
||||
if (Object.prototype.hasOwnProperty.call(query, "state")) {
|
||||
return loadExistingRepresentation({ store, ctx, bootstrap });
|
||||
}
|
||||
|
||||
|
||||
@@ -14,35 +14,41 @@ import { PrismaAdapter } from "@next-auth/prisma-adapter";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import NextAuth from "next-auth";
|
||||
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";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const WELSH_LANGUAGE_CODE = 846040000;
|
||||
|
||||
const appendParamsAndPathToNewUrl = (fromUrl, toUrl) => {
|
||||
const fromUrlObj = new URL(fromUrl);
|
||||
const params = fromUrlObj.searchParams;
|
||||
|
||||
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();
|
||||
const authDiagnostic = (event, metadata = {}) => {
|
||||
try {
|
||||
const safeMeta = JSON.parse(JSON.stringify(metadata));
|
||||
console.info(`[auth][${event}]`, redactSensitive(safeMeta));
|
||||
} catch (_error) {
|
||||
console.info(`[auth][${event}]`);
|
||||
}
|
||||
};
|
||||
|
||||
// const resolveRequestLocale = (req) => {
|
||||
// const locale =
|
||||
// req?.body?.locale || req?.query?.locale || req?.cookies?.pedw_locale;
|
||||
const appendParamsAndPathToNewUrl = (fromUrl, toUrl) => {
|
||||
try {
|
||||
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) => {
|
||||
if (!email) return null;
|
||||
@@ -69,9 +75,20 @@ const resolveCrmLocale = async (email) => {
|
||||
|
||||
const resolveEffectiveLocale = async (req, 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 }) => {
|
||||
@@ -117,19 +134,35 @@ const getLocaleFromCallbackUrl = (callbackUrl) => {
|
||||
|
||||
const resolveRequestLocale = (req) => {
|
||||
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 === "en") return "en";
|
||||
if (directLocale === "cy") {
|
||||
authDiagnostic("request-locale.direct", { locale: "cy" });
|
||||
return "cy";
|
||||
}
|
||||
if (directLocale === "en") {
|
||||
authDiagnostic("request-locale.direct", { locale: "en" });
|
||||
return "en";
|
||||
}
|
||||
|
||||
const callbackLocale =
|
||||
getLocaleFromCallbackUrl(req?.body?.callbackUrl) ||
|
||||
getLocaleFromCallbackUrl(req?.query?.callbackUrl) ||
|
||||
getLocaleFromCallbackUrl(req?.cookies?.["next-auth.callback-url"]) ||
|
||||
getLocaleFromCallbackUrl(
|
||||
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) => {
|
||||
@@ -147,24 +180,12 @@ const authOptions = (req, res) => {
|
||||
email
|
||||
);
|
||||
|
||||
console.log(
|
||||
"============================================================\n",
|
||||
"verification url API: " + url + "\n",
|
||||
"============================================================\n"
|
||||
);
|
||||
|
||||
const formURL = buildLocalizedVerificationUrl({
|
||||
url,
|
||||
email,
|
||||
effectiveLocale
|
||||
});
|
||||
|
||||
console.log(
|
||||
"============================================================\n",
|
||||
"new verification url----: " + formURL + "\n",
|
||||
"============================================================\n"
|
||||
);
|
||||
|
||||
return res
|
||||
.writeHead(200, { "Content-Type": "application/json" })
|
||||
.json({ url: formURL });
|
||||
@@ -181,24 +202,12 @@ const authOptions = (req, res) => {
|
||||
email
|
||||
);
|
||||
|
||||
console.log(
|
||||
"============================================================\n",
|
||||
"verification url----: " + url + "\n",
|
||||
"============================================================\n"
|
||||
);
|
||||
|
||||
const formURL = buildLocalizedVerificationUrl({
|
||||
url,
|
||||
email,
|
||||
effectiveLocale
|
||||
});
|
||||
|
||||
console.log(
|
||||
"============================================================\n",
|
||||
"new verification url----: " + formURL + "\n",
|
||||
"============================================================\n"
|
||||
);
|
||||
|
||||
const personalisation = {
|
||||
emailAddress: email,
|
||||
signInLink: formURL,
|
||||
@@ -261,15 +270,21 @@ const authOptions = (req, res) => {
|
||||
},
|
||||
callbacks: {
|
||||
session: async (session, user) => {
|
||||
console.log("callback in auth", session, user);
|
||||
return Promise.resolve(session);
|
||||
},
|
||||
|
||||
redirect({ url, baseUrl }) {
|
||||
console.log("baseurl:", url, baseUrl);
|
||||
|
||||
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 =
|
||||
requestLocale === "cy"
|
||||
@@ -277,7 +292,10 @@ const authOptions = (req, res) => {
|
||||
: process.env.NEXTAUTH_URL;
|
||||
|
||||
const updatedUrl = appendParamsAndPathToNewUrl(url, newUrl);
|
||||
console.log(updatedUrl);
|
||||
authDiagnostic("redirect.external-rewrite", {
|
||||
locale: requestLocale,
|
||||
targetOrigin: newUrl
|
||||
});
|
||||
return updatedUrl;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,10 +156,10 @@ export default async function ApiProxy(req, res) {
|
||||
queryUrl =
|
||||
"pinswg_sipses?$count=true&$expand=pinswg_sipscase&$filter=_pinswg_projecttype_value eq " +
|
||||
searchString.projecttype +
|
||||
(searchString.hasOwnProperty("q")
|
||||
(Object.prototype.hasOwnProperty.call(searchString, "q")
|
||||
? " and contains(pinswg_projectname, '" + searchString.q + "')"
|
||||
: "") +
|
||||
(searchString.hasOwnProperty("lpa")
|
||||
(Object.prototype.hasOwnProperty.call(searchString, "lpa")
|
||||
? " and _pinswg_associatedlpa_value eq " +
|
||||
searchString.lpa +
|
||||
" "
|
||||
|
||||
@@ -162,7 +162,7 @@ export default async function ApiProxy(req, res) {
|
||||
"@odata.count": coordsObj["@odata.count"]
|
||||
};
|
||||
|
||||
return req.query.hasOwnProperty("fordmw")
|
||||
return Object.prototype.hasOwnProperty.call(req.query, "fordmw")
|
||||
? respondSuccess(res, updatedData)
|
||||
: respondSuccess(res, coordsObj);
|
||||
} catch (error) {
|
||||
|
||||
@@ -136,7 +136,10 @@ export default async function handler(req, res) {
|
||||
return blobList;
|
||||
};
|
||||
|
||||
reqBodyobj = reqBodyobj?.hasOwnProperty("filesList")
|
||||
reqBodyobj = Object.prototype.hasOwnProperty.call(
|
||||
reqBodyobj || {},
|
||||
"filesList"
|
||||
)
|
||||
? cleanFilesList(reqBodyobj)
|
||||
: reqBodyobj;
|
||||
|
||||
|
||||
+4
-8
@@ -7,10 +7,10 @@ import CookieBanner from "../../components/cookieBanner";
|
||||
import Footer from "../../components/footer";
|
||||
import Header from "../../components/header";
|
||||
import ServiceBanner from "../../components/servicebanner";
|
||||
import { destroyCookie, setCookie } from "nookies";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { getCsrfToken } from "next-auth/react";
|
||||
import { clearSessionArtifacts } from "../../lib/auth/sessionClient";
|
||||
|
||||
const Error = (props) => {
|
||||
let { t, lang } = useTranslation();
|
||||
@@ -19,11 +19,7 @@ const Error = (props) => {
|
||||
const { error } = useRouter().query;
|
||||
|
||||
useEffect(() => {
|
||||
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: "/" });
|
||||
clearSessionArtifacts();
|
||||
}, []);
|
||||
|
||||
const errors = {
|
||||
@@ -37,7 +33,7 @@ const Error = (props) => {
|
||||
EmailSignin: t("auth:auth-error-EmailSignin-label"),
|
||||
CredentialsSignin: t("auth:auth-error-CredentialsSignin-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);
|
||||
@@ -89,7 +85,7 @@ const Error = (props) => {
|
||||
export async function getServerSideProps(context) {
|
||||
const csrfToken = await getCsrfToken(context);
|
||||
return {
|
||||
props: { csrfToken },
|
||||
props: { csrfToken }
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -141,9 +141,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
|
||||
if (thisSession) {
|
||||
console.log(" has sesssion.......");
|
||||
[loggedInUser] = await Promise.all([
|
||||
await getPortalLogin(thisSession.user.email)
|
||||
]);
|
||||
loggedInUser = await getPortalLogin(thisSession.user.email);
|
||||
|
||||
loggedInUser = loggedInUser.value[0].contactid;
|
||||
|
||||
|
||||
@@ -112,9 +112,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
|
||||
if (thisSession) {
|
||||
console.log(" has sesssion.......");
|
||||
[loggedInUser] = await Promise.all([
|
||||
await getPortalLogin(thisSession.user.email)
|
||||
]);
|
||||
loggedInUser = await getPortalLogin(thisSession.user.email);
|
||||
|
||||
loggedInUser = loggedInUser.value[0].contactid;
|
||||
|
||||
@@ -163,7 +161,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
: "pinswg_siteaddressline1";
|
||||
|
||||
store.dispatch(
|
||||
req.headers.hasOwnProperty("referer")
|
||||
Object.prototype.hasOwnProperty.call(req.headers, "referer")
|
||||
? req.headers.referer.indexOf("?") > -1
|
||||
? setSearch(req.headers.referer.split("?")[1])
|
||||
: setSearch(
|
||||
|
||||
+9
-3
@@ -141,7 +141,10 @@ const RenderMultiline = ({
|
||||
className={className}
|
||||
{...input}
|
||||
maxLength={
|
||||
custom.hasOwnProperty("maxFieldLength")
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
custom,
|
||||
"maxFieldLength"
|
||||
)
|
||||
? custom.maxFieldLength
|
||||
? custom.maxFieldLength
|
||||
: 800
|
||||
@@ -190,14 +193,17 @@ const RenderTextfield = ({
|
||||
name={id || name}
|
||||
id={id || name}
|
||||
maxLength={
|
||||
custom.hasOwnProperty("maxFieldLength")
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
custom,
|
||||
"maxFieldLength"
|
||||
)
|
||||
? custom.maxFieldLength
|
||||
? custom.maxFieldLength
|
||||
: 100
|
||||
: 200
|
||||
}
|
||||
pattern={
|
||||
custom.hasOwnProperty("pattern")
|
||||
Object.prototype.hasOwnProperty.call(custom, "pattern")
|
||||
? custom.pattern
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -144,9 +144,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
|
||||
if (thisSession) {
|
||||
console.log(" has sesssion.......");
|
||||
[loggedInUser] = await Promise.all([
|
||||
await getPortalLogin(thisSession.user.email)
|
||||
]);
|
||||
loggedInUser = await getPortalLogin(thisSession.user.email);
|
||||
|
||||
loggedInUser = loggedInUser.value[0].contactid;
|
||||
|
||||
|
||||
@@ -3,23 +3,19 @@ import { signOut } from "next-auth/react";
|
||||
import useTranslation from "next-translate/useTranslation";
|
||||
import Head from "next/head";
|
||||
import Link from "next/link";
|
||||
import { destroyCookie } from "nookies";
|
||||
import { useRouter } from "next/router";
|
||||
import CookieBanner from "../components/cookieBanner";
|
||||
import Footer from "../components/footer";
|
||||
import Header from "../components/header";
|
||||
import { performPortalSignOut } from "../lib/auth/sessionClient";
|
||||
|
||||
const FourOhFour = (props) => {
|
||||
let { t, lang } = useTranslation();
|
||||
const { footerLinks, pages } = props;
|
||||
const { locale } = useRouter();
|
||||
|
||||
const handleLogout = () => {
|
||||
console.info("////////////\n" + "logout" + "\n////////////");
|
||||
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: "/" });
|
||||
performPortalSignOut({ locale, callbackUrl: "/", signOutFn: signOut });
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -140,7 +140,7 @@ const Home = (props) => {
|
||||
|
||||
export const getServerSideProps = wrapper.getServerSideProps(
|
||||
(store) => async (ctx) => {
|
||||
const { query, req, res } = ctx;
|
||||
const { query, req } = ctx;
|
||||
getIP(req);
|
||||
const searchResultsObj = await getAddressSearch(query);
|
||||
const searchDetailsObj = searchResultsObj;
|
||||
@@ -168,14 +168,14 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
|
||||
const [accountDetails, searchResultsObj, watchedCases] =
|
||||
await Promise.all([
|
||||
await getPersonalAccount(loggedInUser),
|
||||
await getAdvancedSearch(query),
|
||||
await getWatchedCases(loggedInUser)
|
||||
getPersonalAccount(loggedInUser),
|
||||
getAdvancedSearch(query),
|
||||
getWatchedCases(loggedInUser)
|
||||
]);
|
||||
|
||||
const [searchDetailsObj, watchedCasesDetails] = await Promise.all([
|
||||
await getSearchDetails(searchResultsObj),
|
||||
await getDetails(watchedCases, "myWatchedCases")
|
||||
getSearchDetails(searchResultsObj),
|
||||
getDetails(watchedCases, "myWatchedCases")
|
||||
]);
|
||||
|
||||
store.dispatch(setAccountDetails(accountDetails));
|
||||
@@ -203,7 +203,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
const getDetails = (resultsObj, detailsType) => {
|
||||
let detailsArr = [];
|
||||
resultsObj = resultsObj.value;
|
||||
const detailsObj = resultsObj.map((searchDetail, index) => {
|
||||
const detailsObj = resultsObj.map((searchDetail) => {
|
||||
if (searchDetail.pinswg_appealcasetype == null) {
|
||||
console.log(
|
||||
detailsType != "myWatchedCases"
|
||||
|
||||
@@ -2,7 +2,7 @@ import useTranslation from "next-translate/useTranslation";
|
||||
import Head from "next/head";
|
||||
import { useRouter } from "next/router";
|
||||
import { connect } from "react-redux";
|
||||
import { getIP } from "../../actions/core/logger";
|
||||
import { consoleLogger, getIP } from "../../actions/core/logger";
|
||||
import {
|
||||
getPersonalAccount,
|
||||
getPortalLogin
|
||||
@@ -46,7 +46,6 @@ const Home = (props) => {
|
||||
let { t, lang } = useTranslation();
|
||||
|
||||
const router = useRouter();
|
||||
const { locale } = router;
|
||||
const { appealtypes } = router.query;
|
||||
|
||||
return (
|
||||
@@ -79,44 +78,98 @@ const Home = (props) => {
|
||||
|
||||
export const getServerSideProps = wrapper.getServerSideProps(
|
||||
(store) => async (ctx) => {
|
||||
const { query, req, res } = ctx;
|
||||
const { query, req } = ctx;
|
||||
getIP(req);
|
||||
console.log("query-", query);
|
||||
//console.log("search array:", Object.entries(query));
|
||||
const { cookies } = req;
|
||||
|
||||
const showLoginCheck = process.env.SHOWLOGIN || false;
|
||||
|
||||
let thisSession = await getSession(ctx);
|
||||
|
||||
let loggedInUser = await getPortalLogin(thisSession.user.email);
|
||||
|
||||
if (!thisSession) {
|
||||
console.log("not has sesssion.......");
|
||||
consoleLogger({
|
||||
name: "MyPortalAdvancedSearchResultsAuthGuard",
|
||||
reasonCode: "NO_SESSION",
|
||||
message:
|
||||
"advancedsearchresults loader missing session; redirecting to signin"
|
||||
});
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/auth/signin",
|
||||
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 &&
|
||||
store.dispatch(setContainerID(thisSession.user.id));
|
||||
|
||||
loggedInUser = await getPortalLogin(thisSession.user.email);
|
||||
|
||||
loggedInUser = loggedInUser.value[0].contactid;
|
||||
|
||||
const [accountDetails, watchedCases] = await Promise.all([
|
||||
await getPersonalAccount(loggedInUser),
|
||||
await getWatchedCases(loggedInUser)
|
||||
getPersonalAccount(loggedInUser),
|
||||
getWatchedCases(loggedInUser)
|
||||
]);
|
||||
|
||||
console.log(accountDetails);
|
||||
|
||||
const [watchedCasesDetails] = await Promise.all([
|
||||
await getDetails(watchedCases, "myWatchedCases")
|
||||
]);
|
||||
const watchedCasesDetails = await getDetails(
|
||||
watchedCases,
|
||||
"myWatchedCases"
|
||||
);
|
||||
|
||||
const showLoginCheck = process.env.SHOWLOGIN || false;
|
||||
const showReps = process.env.SHOWREPRESENTATIONS || false;
|
||||
@@ -127,7 +180,22 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
store.dispatch(setWatchedCasesDetails(watchedCasesDetails));
|
||||
store.dispatch(setSearch(Object.entries(query)));
|
||||
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 {
|
||||
props: {
|
||||
showLoginCheck: showLoginCheck
|
||||
@@ -139,7 +207,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
const getDetails = (resultsObj, detailsType) => {
|
||||
let detailsArr = [];
|
||||
resultsObj = resultsObj.value;
|
||||
const detailsObj = resultsObj.map((searchDetail, index) => {
|
||||
const detailsObj = resultsObj.map((searchDetail) => {
|
||||
if (searchDetail.pinswg_appealcasetype == null) {
|
||||
console.log(
|
||||
detailsType != "myWatchedCases"
|
||||
|
||||
@@ -2,7 +2,7 @@ import useTranslation from "next-translate/useTranslation";
|
||||
import Head from "next/head";
|
||||
import { useRouter } from "next/router";
|
||||
import { connect } from "react-redux";
|
||||
import { getIP } from "../../../actions/core/logger";
|
||||
import { consoleLogger, getIP } from "../../../actions/core/logger";
|
||||
import {
|
||||
getPersonalAccount,
|
||||
getPortalLogin
|
||||
@@ -61,17 +61,10 @@ import ServiceBanner from "../../../components/myportal/servicebanner";
|
||||
import TimeOut from "../../../components/timeout";
|
||||
|
||||
const CaseHome = (props) => {
|
||||
const {
|
||||
footerLinks,
|
||||
pages,
|
||||
setSearchResults,
|
||||
setSearchDetails,
|
||||
searchResultsObj
|
||||
} = props;
|
||||
let { t, lang } = useTranslation();
|
||||
const { footerLinks } = props;
|
||||
useTranslation();
|
||||
|
||||
const router = useRouter();
|
||||
const { locale } = router;
|
||||
const { ticketnumber } = router.query;
|
||||
|
||||
return (
|
||||
@@ -94,9 +87,6 @@ const CaseHome = (props) => {
|
||||
props={props}
|
||||
myCases={props.myCases.myCases}
|
||||
myCasesDetails={props.myCases.myCasesDetails}
|
||||
// directSearchResultsObj={
|
||||
// props.searchResultsObj.searchResultsObj
|
||||
// }
|
||||
searchResultsObj={
|
||||
props.searchResultsObj.searchResultsObj
|
||||
}
|
||||
@@ -150,28 +140,44 @@ const CaseHome = (props) => {
|
||||
|
||||
export const getServerSideProps = wrapper.getServerSideProps(
|
||||
(store) => async (ctx) => {
|
||||
const { query, req, res } = ctx;
|
||||
const { query, req } = ctx;
|
||||
getIP(req);
|
||||
const { cookies } = req;
|
||||
|
||||
console.log(cookies);
|
||||
console.log("the query :", query.ticketnumber);
|
||||
|
||||
console.log("viewkey: " + (query.hasOwnProperty("key") ? "yes" : "no"));
|
||||
consoleLogger({
|
||||
name: "MyPortalCaseTicketLoaderStart",
|
||||
message: "myportal case ticket loader invoked",
|
||||
hasTicketNumber: !!query?.ticketnumber,
|
||||
hasViewKey: Object.prototype.hasOwnProperty.call(query, "key")
|
||||
});
|
||||
|
||||
const showLoginCheck = process.env.SHOWLOGIN || false;
|
||||
let thisSession = await getSession(ctx);
|
||||
const thisSession = await getSession(ctx);
|
||||
let loggedInUser = {};
|
||||
|
||||
if (thisSession) {
|
||||
console.log(" has sesssion.......");
|
||||
[loggedInUser] = await Promise.all([
|
||||
await getPortalLogin(thisSession.user.email)
|
||||
]);
|
||||
loggedInUser = 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 {
|
||||
console.log("not has sesssion.......");
|
||||
consoleLogger({
|
||||
name: "MyPortalCaseTicketMissingSession",
|
||||
message:
|
||||
"myportal case ticket loader missing session; redirecting to signin"
|
||||
});
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/auth/signin",
|
||||
@@ -191,22 +197,24 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
store.dispatch(setAccountDetails(accountDetails));
|
||||
store.dispatch(setLoggedInUserId(loggedInUser));
|
||||
|
||||
let developmentQuery = query.ticketnumber;
|
||||
const developmentQuery = query.ticketnumber;
|
||||
|
||||
const pattern = /CAS-\d{5}-[A-Z0-9]{6}/;
|
||||
const match = query.ticketnumber.match(pattern);
|
||||
|
||||
if (match) {
|
||||
console.log("Match found!", match[0]);
|
||||
} else {
|
||||
console.log("No match.");
|
||||
if (!match) {
|
||||
consoleLogger({
|
||||
name: "MyPortalCaseTicketUnexpectedFormat",
|
||||
message: "ticketnumber does not match CAS expected format",
|
||||
hasTicketNumber: !!query?.ticketnumber
|
||||
});
|
||||
}
|
||||
|
||||
const searchResultsObj = await getBasicSearch(developmentQuery);
|
||||
const searchDetailsObj = await getSearchDetails(searchResultsObj);
|
||||
|
||||
var eventsObj = {};
|
||||
var mediaObj = {};
|
||||
let eventsObj = {};
|
||||
let mediaObj = {};
|
||||
|
||||
if (searchResultsObj.value[0].pinswg_appealcasetype == 846040002) {
|
||||
eventsObj = await getSIPSEvents(
|
||||
@@ -220,25 +228,16 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
|
||||
store.dispatch(setMediaDetails(mediaObj));
|
||||
}
|
||||
//console.log(
|
||||
// "\n======================================\n",
|
||||
// searchResultsObj,
|
||||
// "\n======================================\n"
|
||||
// );
|
||||
//console.log(
|
||||
// "\n======================================\n",
|
||||
// searchDetailsObj[0],
|
||||
// "\n======================================\n"
|
||||
// );
|
||||
|
||||
store.dispatch(setSearch(developmentQuery));
|
||||
|
||||
// console.log(
|
||||
// searchResultsObj["@odata.count"] > 1 ||
|
||||
// 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 {
|
||||
redirect: {
|
||||
destination: "/404",
|
||||
@@ -247,6 +246,13 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
};
|
||||
} else {
|
||||
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 {
|
||||
redirect: {
|
||||
//destination: "/dns-not-found",
|
||||
@@ -255,7 +261,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
}
|
||||
};
|
||||
} else {
|
||||
if (query.hasOwnProperty("key")) {
|
||||
if (Object.prototype.hasOwnProperty.call(query, "key")) {
|
||||
let whichViewKey = query.key;
|
||||
|
||||
switch (whichViewKey) {
|
||||
@@ -268,42 +274,6 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
);
|
||||
break;
|
||||
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(
|
||||
setCurrentView({
|
||||
"viewName": "Watched Cases",
|
||||
@@ -362,19 +332,19 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
}
|
||||
const watchedCases = await getWatchedCases(loggedInUser);
|
||||
|
||||
let showWatchedCases = (submittedArr) => {
|
||||
const showWatchedCases = (submittedArr) => {
|
||||
const required = submittedArr.value.filter((el) => {
|
||||
return el.pinswg_representationsubmitted == null;
|
||||
});
|
||||
|
||||
let newObj = {};
|
||||
const newObj = {};
|
||||
return Object.assign(newObj, {
|
||||
"@odata.count": required.length,
|
||||
"value": required
|
||||
});
|
||||
};
|
||||
|
||||
let filteredWatchedCases = showWatchedCases(watchedCases);
|
||||
const filteredWatchedCases = showWatchedCases(watchedCases);
|
||||
|
||||
const watchedCasesDetails = await getDetails(
|
||||
filteredWatchedCases,
|
||||
@@ -415,9 +385,10 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
(el) => el.pinswg_representationsubmitted != null
|
||||
);
|
||||
|
||||
const [mySubmittedRepsDetails] = await Promise.all([
|
||||
getDetails(mySubmittedReps, "mySubmittedReps")
|
||||
]);
|
||||
const mySubmittedRepsDetails = await getDetails(
|
||||
mySubmittedReps,
|
||||
"mySubmittedReps"
|
||||
);
|
||||
|
||||
store.dispatch(setMySubmittedReps(mySubmittedReps));
|
||||
store.dispatch(
|
||||
@@ -425,9 +396,6 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
);
|
||||
}
|
||||
}
|
||||
//console.log(searchResultsObj);
|
||||
|
||||
//console.log(loggedInUser);
|
||||
return {
|
||||
props: {
|
||||
searchResultsObj: {
|
||||
@@ -455,7 +423,7 @@ const getDetails = (resultsObj, detailsType) => {
|
||||
detailsType == "mySubmittedReps" ? resultsObj : resultsObj.value;
|
||||
|
||||
if (detailsType == "myRepresentations") {
|
||||
const repsObj = resultsObj.map((searchDetail, index) => {
|
||||
resultsObj.map((searchDetail) => {
|
||||
detailsArr.push(
|
||||
getCase(searchDetail["incidentID"]).then((data) => {
|
||||
let caseID = "";
|
||||
@@ -488,7 +456,7 @@ const getDetails = (resultsObj, detailsType) => {
|
||||
});
|
||||
}
|
||||
|
||||
const detailsObj = resultsObj.map((searchDetail, index) => {
|
||||
resultsObj.map((searchDetail) => {
|
||||
let caseID = "";
|
||||
|
||||
switch (detailsType) {
|
||||
@@ -512,25 +480,17 @@ const getDetails = (resultsObj, detailsType) => {
|
||||
caseID = searchDetail.pinswg_title;
|
||||
}
|
||||
|
||||
//console.log(detailsType, " case id : ", caseID);
|
||||
|
||||
searchDetail.pinswg_appealcasetype != null &&
|
||||
detailsArr.push(
|
||||
getPortalModuleDetails(
|
||||
getFormCollectionByID(searchDetail.pinswg_appealcasetype)
|
||||
.LogicalCollectionName,
|
||||
caseID
|
||||
// detailsType != "myWatchedCases"
|
||||
// ? searchDetail.ticketnumber
|
||||
// : searchDetail[
|
||||
// "_pinswg_watchedcase_value@OData.Community.Display.V1.FormattedValue"
|
||||
// ]
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
let detArr = Promise.all(detailsArr);
|
||||
console.log(detArr);
|
||||
const detArr = Promise.all(detailsArr);
|
||||
return detArr;
|
||||
};
|
||||
|
||||
@@ -539,7 +499,6 @@ const mapStateToProps = (state) => {
|
||||
accountDetails: state.accountDetails,
|
||||
currentView: state.currentView,
|
||||
search: state.search,
|
||||
//searchResultsObj: state.searchResultsObj,
|
||||
documentDetailsObj: state.searchResultsObj.documentDetailsObj,
|
||||
formData: state.formData,
|
||||
appealType: state.appealType,
|
||||
@@ -557,12 +516,6 @@ const mapDispatchToProps = (dispatch) => {
|
||||
setCurrentReference: (currentReference) => {
|
||||
dispatch(setCurrentReference(refno));
|
||||
},
|
||||
// setSearchResults: (searchResults) => {
|
||||
// dispatch(setSearchResults(searchResults));
|
||||
// },
|
||||
// setSearchDetails: (searchDetails) => {
|
||||
// dispatch(setSearchDetails(searchDetails));
|
||||
// },
|
||||
setLoggedInUserId: (loggedInUser) => {
|
||||
dispatch(setLoggedInUserId(loggedInUser));
|
||||
}
|
||||
|
||||
@@ -111,9 +111,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
|
||||
if (thisSession) {
|
||||
console.log(" has sesssion.......");
|
||||
[loggedInUser] = await Promise.all([
|
||||
await getPortalLogin(thisSession.user.email)
|
||||
]);
|
||||
loggedInUser = await getPortalLogin(thisSession.user.email);
|
||||
|
||||
loggedInUser = loggedInUser.value[0].contactid;
|
||||
|
||||
|
||||
@@ -141,7 +141,10 @@ const RenderMultiline = ({
|
||||
className={className}
|
||||
{...input}
|
||||
maxLength={
|
||||
custom.hasOwnProperty("maxFieldLength")
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
custom,
|
||||
"maxFieldLength"
|
||||
)
|
||||
? custom.maxFieldLength
|
||||
? custom.maxFieldLength
|
||||
: 800
|
||||
@@ -190,14 +193,17 @@ const RenderTextfield = ({
|
||||
name={id || name}
|
||||
id={id || name}
|
||||
maxLength={
|
||||
custom.hasOwnProperty("maxFieldLength")
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
custom,
|
||||
"maxFieldLength"
|
||||
)
|
||||
? custom.maxFieldLength
|
||||
? custom.maxFieldLength
|
||||
: 100
|
||||
: 200
|
||||
}
|
||||
pattern={
|
||||
custom.hasOwnProperty("pattern")
|
||||
Object.prototype.hasOwnProperty.call(custom, "pattern")
|
||||
? custom.pattern
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -142,9 +142,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
|
||||
if (thisSession) {
|
||||
console.log(" has sesssion.......");
|
||||
[loggedInUser] = await Promise.all([
|
||||
await getPortalLogin(thisSession.user.email)
|
||||
]);
|
||||
loggedInUser = await getPortalLogin(thisSession.user.email);
|
||||
|
||||
loggedInUser = loggedInUser.value[0].contactid;
|
||||
|
||||
|
||||
@@ -44,7 +44,6 @@ const Home = (props) => {
|
||||
let { t, lang } = useTranslation();
|
||||
|
||||
const router = useRouter();
|
||||
const { locale } = router;
|
||||
const { appealtypes } = router.query;
|
||||
|
||||
return (
|
||||
@@ -142,14 +141,12 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
getIP(req);
|
||||
console.log("query-", query);
|
||||
|
||||
const { cookies } = req;
|
||||
|
||||
res.setHeader(
|
||||
"Cache-Control",
|
||||
"public, s-maxage=10, stale-while-revalidate=59"
|
||||
);
|
||||
|
||||
let loggedInUser = cookies.pinsUser;
|
||||
let loggedInUser = req.cookies.pinsUser;
|
||||
|
||||
let thisSession = await getSession(ctx);
|
||||
|
||||
@@ -163,8 +160,8 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
};
|
||||
} else {
|
||||
let [accountDetails, watchedCases] = await Promise.all([
|
||||
await getPersonalAccount(loggedInUser),
|
||||
await getWatchedCases(loggedInUser)
|
||||
getPersonalAccount(loggedInUser),
|
||||
getWatchedCases(loggedInUser)
|
||||
]);
|
||||
|
||||
// searchResultsObj =
|
||||
@@ -178,9 +175,10 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
|
||||
const showMapCheck = process.env.SHOWMAPS || false;
|
||||
|
||||
const [watchedCasesDetails] = await Promise.all([
|
||||
await getDetails(watchedCases, "myWatchedCases")
|
||||
]);
|
||||
const watchedCasesDetails = await getDetails(
|
||||
watchedCases,
|
||||
"myWatchedCases"
|
||||
);
|
||||
const dnsCoords = await getDNSCoords();
|
||||
// store.dispatch(setSearchResults(searchResultsObj));
|
||||
// store.dispatch(setSearchDetails(searchDetailsObj));
|
||||
@@ -201,7 +199,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
const getDetails = (resultsObj, detailsType) => {
|
||||
let detailsArr = [];
|
||||
resultsObj = resultsObj.value;
|
||||
const detailsObj = resultsObj.map((searchDetail, index) => {
|
||||
const detailsObj = resultsObj.map((searchDetail) => {
|
||||
if (searchDetail.pinswg_appealcasetype == null) {
|
||||
console.log(
|
||||
detailsType != "myWatchedCases"
|
||||
|
||||
+51
-4
@@ -6,6 +6,7 @@ import { connect } from "react-redux";
|
||||
import pLimit from "p-limit";
|
||||
|
||||
import { getIP } from "../../actions/core/logger";
|
||||
import { consoleLogger } from "../../actions/core/logger";
|
||||
import {
|
||||
getPersonalAccount,
|
||||
getPortalLogin
|
||||
@@ -184,15 +185,49 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
const thisSession = await getSession(ctx);
|
||||
|
||||
if (!thisSession) {
|
||||
consoleLogger({
|
||||
name: "MyPortalIndexAuthGuard",
|
||||
reasonCode: "NO_SESSION",
|
||||
message:
|
||||
"myportal index loader missing session; redirecting to signin"
|
||||
});
|
||||
return {
|
||||
redirect: { destination: "/auth/signin", permanent: false }
|
||||
};
|
||||
}
|
||||
|
||||
const loggedInUserResponse = await getPortalLogin(
|
||||
thisSession.user.email
|
||||
);
|
||||
const contacts = loggedInUserResponse?.value || [];
|
||||
if (!thisSession?.user?.email || !thisSession?.user?.id) {
|
||||
consoleLogger({
|
||||
name: "MyPortalIndexAuthGuard",
|
||||
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) {
|
||||
return {
|
||||
@@ -208,6 +243,18 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
|
||||
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);
|
||||
const accountDetails = await getPersonalAccount(loggedInUser);
|
||||
|
||||
|
||||
@@ -77,14 +77,12 @@ const Home = (props) => {
|
||||
|
||||
export const getServerSideProps = wrapper.getServerSideProps(
|
||||
(store) => async (ctx) => {
|
||||
const { query, req, res } = ctx;
|
||||
const { query, req } = ctx;
|
||||
getIP(req);
|
||||
console.log("query-", query);
|
||||
|
||||
const { cookies } = req;
|
||||
|
||||
let loggedInUserCookie = cookies.pinsUser;
|
||||
|
||||
let thisSession = await getSession(ctx);
|
||||
|
||||
const showReps = process.env.SHOWREPRESENTATIONS || false;
|
||||
@@ -100,9 +98,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
}
|
||||
};
|
||||
} else {
|
||||
let [loggedInUser] = await Promise.all([
|
||||
await getPortalLogin(thisSession.user.email)
|
||||
]);
|
||||
let loggedInUser = await getPortalLogin(thisSession.user.email);
|
||||
|
||||
//console.log("sssss", searchResultsObj);
|
||||
|
||||
@@ -113,8 +109,8 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
//console.log("sssss", loggedInUser);
|
||||
|
||||
const [accountDetails, watchedCasesDetails] = await Promise.all([
|
||||
await getPersonalAccount(loggedInUser),
|
||||
await getDetails(watchedCases, "myWatchedCases")
|
||||
getPersonalAccount(loggedInUser),
|
||||
getDetails(watchedCases, "myWatchedCases")
|
||||
]);
|
||||
store.dispatch(setAccountDetails(accountDetails));
|
||||
store.dispatch(setSearch(query.q));
|
||||
@@ -136,7 +132,7 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
const getDetails = (resultsObj, detailsType) => {
|
||||
let detailsArr = [];
|
||||
resultsObj = resultsObj.value;
|
||||
const detailsObj = resultsObj.map((searchDetail, index) => {
|
||||
const detailsObj = resultsObj.map((searchDetail) => {
|
||||
if (searchDetail.pinswg_appealcasetype == null) {
|
||||
console.log(
|
||||
detailsType != "myWatchedCases"
|
||||
|
||||
@@ -126,7 +126,10 @@ export const getServerSideProps = wrapper.getServerSideProps(
|
||||
|
||||
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);
|
||||
|
||||
|
||||
@@ -10,6 +10,10 @@ const runRouteStateHelperTests = require("./route-state-helper.test.cjs");
|
||||
const runBreadcrumbRouteMapsHelperTests = require("./breadcrumb-route-maps-helper.test.cjs");
|
||||
const runBreadcrumbsRouteMapStructureTests = require("./breadcrumbs-route-map-structure.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 () => {
|
||||
await runCoreTokenTests();
|
||||
@@ -24,6 +28,10 @@ const run = async () => {
|
||||
await runBreadcrumbRouteMapsHelperTests();
|
||||
await runBreadcrumbsRouteMapStructureTests();
|
||||
await runRepresentationBuildRepsArrRulesTests();
|
||||
await runSessionClientTests();
|
||||
await runNewAppealLoaderGuardTests();
|
||||
await runMyPortalLoaderGuardTests();
|
||||
await runRepresentationLoaderGuardTests();
|
||||
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 = {
|
||||
module: { exports: {} },
|
||||
exports: {},
|
||||
require
|
||||
require,
|
||||
Date
|
||||
};
|
||||
|
||||
vm.runInNewContext(source, context, { filename: filePath });
|
||||
@@ -67,8 +68,15 @@ const baseInput = (overrides = {}) => ({
|
||||
...overrides
|
||||
});
|
||||
|
||||
const normalizeForAssertion = (value) =>
|
||||
JSON.parse(JSON.stringify(value ?? null));
|
||||
|
||||
const buildOptions = (overrides = {}) =>
|
||||
buildRepsArrFromContext(buildRepresentationContext(baseInput(overrides)));
|
||||
normalizeForAssertion(
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(baseInput(overrides))
|
||||
)
|
||||
);
|
||||
|
||||
test("baseline truth-table: non-DNS non-SIPS across windows/capacities/ownership", () => {
|
||||
const capacities = [
|
||||
@@ -227,13 +235,15 @@ test("DNS rules: statement/LIR ownership behaviour and questionnaire exclusion",
|
||||
};
|
||||
|
||||
const dnsOptions = (overrides = {}) =>
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(
|
||||
baseInput({
|
||||
appealType: APPEAL_TYPES.DNS,
|
||||
detailsObj: dnsDetails,
|
||||
...overrides
|
||||
})
|
||||
normalizeForAssertion(
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(
|
||||
baseInput({
|
||||
appealType: APPEAL_TYPES.DNS,
|
||||
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", () => {
|
||||
assert.deepStrictEqual(
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(
|
||||
baseInput({
|
||||
detailsObj: {
|
||||
pinswg_statementduedate: "2026-04-30T00:00:00.000Z",
|
||||
pinswg_finalcommentsduedate: "2026-05-25T00:00:00.000Z"
|
||||
}
|
||||
})
|
||||
normalizeForAssertion(
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(
|
||||
baseInput({
|
||||
detailsObj: {
|
||||
pinswg_statementduedate: "2026-04-30T00:00:00.000Z",
|
||||
pinswg_finalcommentsduedate:
|
||||
"2026-05-25T00:00:00.000Z"
|
||||
}
|
||||
})
|
||||
)
|
||||
)
|
||||
),
|
||||
[]
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(
|
||||
baseInput({
|
||||
detailsObj: {
|
||||
pinswg_startdate: "2026-04-01T00:00:00.000Z",
|
||||
pinswg_finalcommentsduedate: "2026-05-25T00:00:00.000Z"
|
||||
}
|
||||
})
|
||||
normalizeForAssertion(
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(
|
||||
baseInput({
|
||||
detailsObj: {
|
||||
pinswg_startdate: "2026-04-01T00:00:00.000Z",
|
||||
pinswg_finalcommentsduedate:
|
||||
"2026-05-25T00:00:00.000Z"
|
||||
}
|
||||
})
|
||||
)
|
||||
)
|
||||
),
|
||||
[]
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(
|
||||
baseInput({
|
||||
detailsObj: {
|
||||
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")
|
||||
})
|
||||
normalizeForAssertion(
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(
|
||||
baseInput({
|
||||
detailsObj: {
|
||||
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")
|
||||
})
|
||||
)
|
||||
)
|
||||
),
|
||||
[]
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(
|
||||
baseInput({
|
||||
appealType: APPEAL_TYPES.SIPS,
|
||||
detailsObj: {},
|
||||
selectedCapacity: "agent",
|
||||
isNRW: true,
|
||||
now: new Date("2026-06-20T10:00:00.000Z")
|
||||
})
|
||||
normalizeForAssertion(
|
||||
buildRepsArrFromContext(
|
||||
buildRepresentationContext(
|
||||
baseInput({
|
||||
appealType: APPEAL_TYPES.SIPS,
|
||||
detailsObj: {},
|
||||
selectedCapacity: "agent",
|
||||
isNRW: true,
|
||||
now: new Date("2026-06-20T10:00:00.000Z")
|
||||
})
|
||||
)
|
||||
)
|
||||
),
|
||||
["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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user