Merged PR 2675: Feature/ithc mitigation

ITHC fixes

Related work items: #25508, #25509, #25510, #25513, #25514, #25515
This commit is contained in:
Robert Bond
2026-11-10 10:39:40 +00:00
152 changed files with 13238 additions and 49631 deletions
-34
View File
@@ -1,34 +0,0 @@
{
"extends": "next/core-web-vitals",
"rules": {
"@next/next/no-img-element": "off",
"react/no-unknown-property": "error"
}//,
//...your configuration
// "overrides": [
// //...your overrides
// {
// // Force the setting of a swagger description on each api endpoint
// "files": ["pages/api/**/*.js"],
// "plugins": ["jsdoc"],
// "rules": {
// "jsdoc/no-missing-syntax": [
// "error",
// {
// "contexts": [
// {
// "comment": "JsdocBlock:has(JsdocTag[tag=swagger])",
// "context": "any",
// "message": "@swagger documentation is required on each API. Check this out for syntax info: https://github.com/jellydn/next-swagger-doc"
// }
// ]
// }
// ]
// }
// }
// ]
}
+2 -2
View File
@@ -1,8 +1,8 @@
import { getJson, requestJson } from "./endpointClient"; import { getJson, requestJson } from "./endpointClient";
import { getSignedJson, postSignedJson } from "./signedRequestClient"; import { getSignedJson, postSignedJson } from "./signedRequestClient";
export const getFileJson = (url) => { export const getFileJson = (url, config) => {
return getJson(url); return getJson(url, config);
}; };
export const getSignedFileJson = async (queryUrl) => { export const getSignedFileJson = async (queryUrl) => {
-25
View File
@@ -11,31 +11,6 @@ export const getPersonalAccount = (contactid) => {
}); });
}; };
export const getLogin = (emailAddress, pwd) => {
return getJson(
"/api/endpoint/getlogin_api?emailAddress=" +
emailAddress +
"&pwd=" +
pwd
).catch((error) => {
consoleLogger(error);
});
};
export const updatePassword = (contactId, newpassword) => {
var queryUrl = "/api/endpoint/updateaccount_api?contactId=" + contactId;
var data = { "pinswg_custom_password": newpassword };
var config = {
method: "post",
url: queryUrl,
data: data
};
return requestJson(config).catch((error) => {
consoleLogger(error);
});
};
export const updateAccount = async (contactId, updateBody, ssr) => { export const updateAccount = async (contactId, updateBody, ssr) => {
var queryUrl = var queryUrl =
(ssr ? BASE_URL : "") + (ssr ? BASE_URL : "") +
-4
View File
@@ -1,7 +1,5 @@
import { import {
getPersonalAccount, getPersonalAccount,
getLogin,
updatePassword,
updateAccount, updateAccount,
createAccount, createAccount,
getEmailAccountCheck, getEmailAccountCheck,
@@ -12,8 +10,6 @@ import {
export { export {
getPersonalAccount, getPersonalAccount,
getLogin,
updatePassword,
updateAccount, updateAccount,
createAccount, createAccount,
getEmailAccountCheck, getEmailAccountCheck,
-29
View File
@@ -76,35 +76,6 @@ export const getAppealID = (
}); });
}; };
export const createNewCase = (
appealTypeId,
lpaID,
contactid,
createBody,
containerName
) => {
appealTypeId = parseInt(appealTypeId);
var data = createBody;
var queryUrl = buildFileQuery("/api/endpoint/createcase_api", {
appealTypeId,
lpaID,
contactid,
containername: containerName
});
var config = {
method: "post",
url: withBaseUrl(BASE_URL, queryUrl),
data: data
};
return requestJson(config).catch((error) => {
consoleLogger(error);
});
};
export const createNewCaseBlob = ( export const createNewCaseBlob = (
appealTypeId, appealTypeId,
lpaID, lpaID,
-2
View File
@@ -4,7 +4,6 @@ import {
getSIPSEvents, getSIPSEvents,
getSIPSMedia, getSIPSMedia,
getAppealID, getAppealID,
createNewCase,
createNewCaseBlob, createNewCaseBlob,
updateCase, updateCase,
updateCaseBlob, updateCaseBlob,
@@ -26,7 +25,6 @@ export {
getSIPSEvents, getSIPSEvents,
getSIPSMedia, getSIPSMedia,
getAppealID, getAppealID,
createNewCase,
createNewCaseBlob, createNewCaseBlob,
updateCase, updateCase,
updateCaseBlob, updateCaseBlob,
+37 -2
View File
@@ -28,13 +28,48 @@ export const getAwaitingSubmissionFromBlob = (containerName) => {
}); });
}; };
export const getRepsFromBlob = (containerName) => { export const getRepsFromBlob = (containerName, config) => {
const route = buildFileQuery("/api/file/getrepsblob", { const route = buildFileQuery("/api/file/getrepsblob", {
container: containerName container: containerName
}); });
const url = withBaseUrl(BASE_URL, appendHashSuffix(route, hashAPIPath));
const hasForwardedCookie =
typeof config?.headers?.Cookie === "string" &&
config.headers.Cookie.length > 0;
if (hasForwardedCookie) {
let trustedDestination = false;
try {
const destination = new URL(url);
const expectedOrigin = new URL(process.env.NEXTAUTH_URL);
trustedDestination =
destination.origin === expectedOrigin.origin &&
["http:", "https:"].includes(destination.protocol) &&
!destination.username &&
!destination.password;
} catch {
trustedDestination = false;
}
if (!trustedDestination) {
return Promise.reject(
new Error("Untrusted representation request destination")
);
}
}
return getFileJson( return getFileJson(
withBaseUrl(BASE_URL, appendHashSuffix(route, hashAPIPath)) url,
hasForwardedCookie
? {
...config,
maxRedirects: 0
}
: config
).catch((error) => { ).catch((error) => {
consoleLogger(error); consoleLogger(error);
}); });
-18
View File
@@ -144,24 +144,6 @@ export const createWatchedCases = async (formValues) => {
} }
}; };
export const deleteMyRepresentations = (myRepresentationsID) => {
var queryUrl = buildFileQuery("/api/endpoint/deletemyrepresentations_api", {
myRepresentationsID
});
return deleteSignedJson(queryUrl, {
headers: {
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
"Accept": "application/json;odata.metadata=none",
"Prefer": 'odata.include-annotations="*",return=representation',
"Content-Type": "application/json"
}
}).catch((error) => {
consoleLogger(error);
});
};
export const deleteAwaitingSubmissions = (incidentID) => { export const deleteAwaitingSubmissions = (incidentID) => {
var queryUrl = buildFileQuery( var queryUrl = buildFileQuery(
"/api/endpoint/deleteawaitingsubmissions_api", "/api/endpoint/deleteawaitingsubmissions_api",
-2
View File
@@ -12,7 +12,6 @@ import {
getAwaitingSubmissionProxy, getAwaitingSubmissionProxy,
createWatchedCases, createWatchedCases,
deleteWatchedCases, deleteWatchedCases,
deleteMyRepresentations,
deleteAwaitingSubmissions, deleteAwaitingSubmissions,
sendCaseCompleteMessage, sendCaseCompleteMessage,
sendCaseCompleteMessageProxy, sendCaseCompleteMessageProxy,
@@ -35,7 +34,6 @@ export {
getAwaitingSubmissionProxy, getAwaitingSubmissionProxy,
createWatchedCases, createWatchedCases,
deleteWatchedCases, deleteWatchedCases,
deleteMyRepresentations,
deleteAwaitingSubmissions, deleteAwaitingSubmissions,
sendCaseCompleteMessage, sendCaseCompleteMessage,
sendCaseCompleteMessageProxy, sendCaseCompleteMessageProxy,
+1 -1
View File
@@ -1,5 +1,5 @@
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import { parseCookies, setCookie } from "nookies"; import { parseCookies, setCookie } from "../lib/cookies";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
const COOKIE_NAME = "pedwAiPolicyNoticeHidden"; const COOKIE_NAME = "pedwAiPolicyNoticeHidden";
-184
View File
@@ -1,184 +0,0 @@
import useTranslation from "next-translate/useTranslation";
import Link from "next/link";
import { useRouter } from "next/router";
import React, { useState } from "react";
import { connect } from "react-redux";
import { Field, formValueSelector, reduxForm } from "redux-form";
import { updatePassword } from "../../actions/services/accountService";
const RenderTextfield = ({
id,
className,
rows,
datafieldname,
name,
label,
input,
type,
errorMsg,
meta: { touched, error },
...custom
}) => {
return (
<>
<div
className={
touched && error
? "govuk-form-group govuk-form-group--error"
: "govuk-form-group "
}
>
<label className="govuk-label " htmlFor={id} id={id + "_label"}>
{label}
</label>
{touched && error && (
<span id={id + "-error"} className="govuk-error-message">
<span className="govuk-visually-hidden">Error:</span>{" "}
{touched &&
((error && (
<span>{errorMsg ? errorMsg : error}</span>
)) ||
(warning && <span>{warning}</span>))}
</span>
)}
<input
{...input}
className={className}
name={name}
id={id}
type={type}
/>
</div>
</>
);
};
const ChangePassword = (props) => {
const {
footerLinks,
pages,
handleSubmit,
value,
setPasswordUpdated,
passwordUpdated
} = props;
let { t, lang } = useTranslation();
const router = useRouter();
const { locale } = router;
let errorsobj = {};
const onHandleSubmit = (values) => {
let contactid = props.props.accountDetails.loggedinUserId;
let updateBody = props.props.form.changepasswordForm.values.newpassword;
console.log(contactid, updateBody);
updatePassword(contactid, updateBody);
setPasswordUpdated(true);
};
const required = (value) => (value ? undefined : "Is required");
const passwordsMustMatch = (value, allValues) =>
value !== allValues.newpassword ? "Passwords do not match" : undefined;
const minLength = (min) => (value) =>
value && value.length < min
? `Must be at least ${min} characters`
: undefined;
const [hasErrors, setHasErrors] = useState("");
return (
<>
{passwordUpdated != true ? (
<form onSubmit={handleSubmit(onHandleSubmit)}>
<fieldset className="govuk-fieldset">
<Field
name="newpassword"
id="newpassword"
component={RenderTextfield}
type="password"
className="govuk-input govuk-input--width-20"
validate={[required, minLength(6)]}
label="New password"
/>
<Field
name="confirmpassword"
id="confirmpassword"
component={RenderTextfield}
type="password"
className="govuk-input govuk-input--width-20"
validate={[required, passwordsMustMatch]}
label="Confirm new password"
/>
</fieldset>
<div className="govuk-button-group">
<button
type="submit"
className="govuk-button"
data-module="govuk-button"
>
Continue
</button>
<Link
href={
"/myportal?q=" +
props.accountDetails.loggedinUserId
}
className="govuk-link"
>
Cancel
</Link>
</div>
</form>
) : (
<>
<p className="govuk-body">
<Link
href={
"/myportal?q=" +
props.accountDetails.loggedinUserId
}
className="govuk-link"
>
Go to My Portal
</Link>
</p>
</>
)}
</>
);
};
const mapStateToProps = (state) => {
return {
search: state.search,
searchResultsObj: state.searchResultsObj,
formData: state.formData,
appealType: state.appealType,
accountDetails: state.accountDetails
//form: state.form,
};
};
const mapDispatchToProps = (dispatch) => {
return {
setCurrentSection: (currentSection) => {
dispatch(setCurrentSection(currentSection));
}
};
};
const selector = formValueSelector("changepasswordForm"); // <-- same as form name
export default connect(
mapStateToProps,
mapDispatchToProps
)(
reduxForm({
form: "changepasswordForm",
destroyOnUnmount: false
})(ChangePassword)
);
@@ -4,7 +4,7 @@ import { useRouter } from "next/router";
import React, { useEffect } from "react"; import React, { useEffect } from "react";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { updateAccount } from "../../actions/services/accountService"; import { updateAccount } from "../../actions/services/accountService";
import { setCookie } from "nookies"; import { setCookie } from "../../lib/cookies";
const PersonalDetailsComplete = (props) => { const PersonalDetailsComplete = (props) => {
const { const {
-5
View File
@@ -92,11 +92,6 @@ const RegisterForm = (props) => {
? "Invalid phone number" ? "Invalid phone number"
: undefined; : undefined;
const passwordsMatch = (value, allValues) =>
value !== allValues.pinswg_custom_password
? "Passwords don't match"
: undefined;
const minLength = (min) => (value) => const minLength = (min) => (value) =>
value && value.length < min value && value.length < min
? `Must be ${min} characters or more` ? `Must be ${min} characters or more`
+113 -28
View File
@@ -2,13 +2,6 @@
import { useState } from "react"; import { useState } from "react";
import Link from "next/link"; import Link from "next/link";
import { bytesToSize } from "../../../components/utils"; import { bytesToSize } from "../../../components/utils";
import {
deleteMyRepresentationsFromBlob,
deleteAwaitingSubmissionsFromBlob,
getRepsFromBlobProxy
} from "../../../actions/services/documentService";
import { sendRepCompleteMessage } from "../../../actions/services/portalService";
import { parseCookies } from "nookies";
import { consoleLogger } from "../../../actions/core/logger"; import { consoleLogger } from "../../../actions/core/logger";
import { formatBlobDates } from "../utils/adminHelper"; import { formatBlobDates } from "../utils/adminHelper";
@@ -25,15 +18,38 @@ export default function StorageTab({ data, repCompleteCount }) {
}; };
const deleteRepItem = (containerID, caseID, repfile) => { const deleteRepItem = (containerID, caseID, repfile) => {
let cookies = parseCookies(); fetch("/api/admin/deleteblobrep", {
//console.log("sssss", containerID, caseID, repfile); method: "POST",
headers: { "Content-Type": "application/json" },
deleteMyRepresentationsFromBlob(containerID, caseID, repfile) body: JSON.stringify({
container: containerID,
casefolderID: caseID,
repfile
})
})
.then((response) => {
if (!response.ok) {
throw new Error("Unable to delete representation");
}
return response.json();
})
.then((data) => { .then((data) => {
return data; return data;
}) })
.then(() => { .then(() => {
getRepsFromBlobProxy(containerID) fetch("/api/admin/getrepsblobproxy", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ container: containerID })
})
.then((response) => {
if (!response.ok) {
throw new Error(
"Unable to refresh representations"
);
}
return response.json();
})
.then((data) => { .then((data) => {
setMyRepresentations(data); setMyRepresentations(data);
setMyRepresentationsDetails(data); setMyRepresentationsDetails(data);
@@ -48,6 +64,9 @@ export default function StorageTab({ data, repCompleteCount }) {
"viewKey": "myRepresentations" "viewKey": "myRepresentations"
}); });
}); });
})
.catch((error) => {
consoleLogger(error);
}); });
}; };
@@ -116,20 +135,52 @@ export default function StorageTab({ data, repCompleteCount }) {
{folder.hasTmpFile && ( {folder.hasTmpFile && (
<> <>
<button <button
onClick={() => { onClick={async () => {
confirm( if (
!confirm(
"Do you want to remove this unsubmitted appeal " + "Do you want to remove this unsubmitted appeal " +
folder.folderPath + folder.folderPath +
"?\n" "?\n"
) && )
(deleteCaseItem( ) {
return;
}
try {
const response =
await fetch(
"/api/admin/deleteblobcase",
{
method: "POST",
headers:
{
"Content-Type":
"application/json"
},
body: JSON.stringify(
{
container:
c.container, c.container,
folder.folderPath, casefolderID:
setData folder.folderPath
), }
)
}
);
if (!response.ok) {
throw new Error(
"Unable to delete case"
);
}
alert( alert(
"Temp case Deleted!" "Temp case Deleted!"
)); );
window.location.reload();
} catch (error) {
consoleLogger(error);
}
}} }}
> >
Delete this TMP appeal Delete this TMP appeal
@@ -174,7 +225,7 @@ export default function StorageTab({ data, repCompleteCount }) {
onClick={async () => { onClick={async () => {
const response = const response =
await fetch( await fetch(
"/api/file/editRepJson", "/api/admin/editRepJson",
{ {
method: "POST", method: "POST",
headers: headers:
@@ -216,7 +267,8 @@ export default function StorageTab({ data, repCompleteCount }) {
{folder.repComplete && ( {folder.repComplete && (
<button <button
onClick={async () => { onClick={async () => {
confirm( if (
!confirm(
"Do you want resend the rep queue message " + "Do you want resend the rep queue message " +
folder.repJsonBlob.name.split( folder.repJsonBlob.name.split(
"/" "/"
@@ -225,20 +277,53 @@ export default function StorageTab({ data, repCompleteCount }) {
folder.repJsonBlob.name.split( folder.repJsonBlob.name.split(
"/" "/"
)[1] )[1]
) && )
(sendRepCompleteMessage( ) {
return;
}
try {
const response =
await fetch(
"/api/admin/createrepcompletemessage",
{
method: "POST",
headers:
{
"Content-Type":
"application/json"
},
body: JSON.stringify(
{
container:
c.container, c.container,
tempcaseref:
folder.repJsonBlob.name.split( folder.repJsonBlob.name.split(
"/" "/"
)[0], )[0],
folder.repJsonBlob.name.split( repid: folder.repJsonBlob.name.split(
"/" "/"
)[1] )[1]
), }
)
}
);
if (!response.ok) {
throw new Error(
"Unable to recreate representation queue message"
);
}
alert( alert(
"rep queue message sent!" "rep queue message sent!"
), );
window.location.reload()); window.location.reload();
} catch (error) {
consoleLogger(
error
);
}
}} }}
> >
Recreate Queue Message Recreate Queue Message
+1 -1
View File
@@ -32,7 +32,7 @@ import {
} from "../../store/watchedCases/action"; } from "../../store/watchedCases/action";
import { signIn, useSession } from "next-auth/react"; import { signIn, useSession } from "next-auth/react";
import { destroyCookie, parseCookies, setCookie } from "nookies"; import { destroyCookie, parseCookies, setCookie } from "../../lib/cookies";
import { getFormCollectionByID, getDetailsProxy, hasOwn } from "../utils"; import { getFormCollectionByID, getDetailsProxy, hasOwn } from "../utils";
import { import {
getLivePublishedEvent, getLivePublishedEvent,
+1 -1
View File
@@ -2,7 +2,7 @@ import { signOut } from "next-auth/react";
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { destroyCookie, parseCookies, setCookie } from "nookies"; import { destroyCookie, parseCookies, setCookie } from "../../lib/cookies";
import { signIn, useSession } from "next-auth/react"; import { signIn, useSession } from "next-auth/react";
const WatchModal = (props) => { const WatchModal = (props) => {
+1 -1
View File
@@ -1,7 +1,7 @@
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { parseCookies } from "nookies"; import { parseCookies } from "../../lib/cookies";
import { useState } from "react"; import { useState } from "react";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { reduxForm } from "redux-form"; import { reduxForm } from "redux-form";
+1 -1
View File
@@ -2,7 +2,7 @@ import _ from "lodash";
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { destroyCookie, setCookie } from "nookies"; import { destroyCookie, setCookie } from "../lib/cookies";
import { connect } from "react-redux"; import { connect } from "react-redux";
import Banner from "../components/banner"; import Banner from "../components/banner";
import { setLogout } from "../store/accountDetails/action"; import { setLogout } from "../store/accountDetails/action";
+1 -1
View File
@@ -2,7 +2,7 @@ import useTranslation from "next-translate/useTranslation";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { parseCookies } from "nookies"; import { parseCookies } from "../../lib/cookies";
import { setLoggedInUserId } from "../../store/accountDetails/action"; import { setLoggedInUserId } from "../../store/accountDetails/action";
import { signOut, useSession } from "next-auth/react"; import { signOut, useSession } from "next-auth/react";
import CaseComment from "./casecomment"; import CaseComment from "./casecomment";
@@ -1,7 +1,7 @@
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { parseCookies } from "nookies"; import { parseCookies } from "../../lib/cookies";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { import {
deleteAwaitingSubmissionsFromBlob, deleteAwaitingSubmissionsFromBlob,
+1 -1
View File
@@ -2,7 +2,7 @@ import _ from "lodash";
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { parseCookies } from "nookies"; import { parseCookies } from "../../lib/cookies";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { import {
deleteAwaitingSubmissions, deleteAwaitingSubmissions,
+1 -1
View File
@@ -1,7 +1,7 @@
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { parseCookies } from "nookies"; import { parseCookies } from "../../lib/cookies";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { import {
deleteAwaitingSubmissions, deleteAwaitingSubmissions,
+1 -1
View File
@@ -3,7 +3,7 @@ import _ from "lodash";
import useTranslation from "next-translate/useTranslation"; import useTranslation from "next-translate/useTranslation";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { parseCookies } from "nookies"; import { parseCookies } from "../../lib/cookies";
import { useState } from "react"; import { useState } from "react";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { import {
-18
View File
@@ -27,24 +27,6 @@ export default function YourAccount() {
</Link> </Link>
</div> </div>
</div> </div>
{/* <div className="card-body">
<h3 className="heading-small card-heading">
{t("myportal:changepassword-card-title")}
</h3>
<p className="govuk-body-s">
{" "}
{t("myportal:changepassword-card-paragraph-one")}
</p>
<div>
<Link href="/account/changepassword">
<a className="govuk-button-secondary">
{t("myportal:changepassword-card-link")}
</a>
</Link>
</div>
</div> */}
</div> </div>
</> </>
); );
-7
View File
@@ -393,13 +393,6 @@ let CreateCase = (props) => {
delete values.confirmHASCAS; delete values.confirmHASCAS;
// createNewCase(
// appTypeCollection.appealTypeID,
// values.lpaTypes,
// props.loggedInUser,
// values,
// props.containerID
// )
const selectedLpaName = props.LPAData.LPAData.value.filter((obj) => { const selectedLpaName = props.LPAData.LPAData.value.filter((obj) => {
return obj.accountid === values.lpaTypes; return obj.accountid === values.lpaTypes;
})[0].name; })[0].name;
+1 -1
View File
@@ -8,7 +8,7 @@ import { connect } from "react-redux";
import transLookup from "../../data/lookuptranslations.json"; import transLookup from "../../data/lookuptranslations.json";
import { setCurrentReference } from "../../store/currentView/action"; import { setCurrentReference } from "../../store/currentView/action";
import { parseCookies, setCookie } from "nookies"; import { parseCookies, setCookie } from "../../lib/cookies";
import { useEffect } from "react"; import { useEffect } from "react";
import { setLoggedInUserId } from "../../store/accountDetails/action"; import { setLoggedInUserId } from "../../store/accountDetails/action";
import { import {
+1 -1
View File
@@ -15,7 +15,7 @@ import {
} from "../../actions/services/searchService"; } from "../../actions/services/searchService";
import GoogleMapReact from "google-map-react"; import GoogleMapReact from "google-map-react";
import { parseCookies } from "nookies"; import { parseCookies } from "../../lib/cookies";
import OSPoint from "ospoint"; import OSPoint from "ospoint";
import { import {
createWatchedCases, createWatchedCases,
+1 -2
View File
@@ -14,7 +14,7 @@ import {
setCurrentReference setCurrentReference
} from "../../store/currentView/action"; } from "../../store/currentView/action";
import { parseCookies, setCookie } from "nookies"; import { parseCookies, setCookie } from "../../lib/cookies";
import { useEffect } from "react"; import { useEffect } from "react";
import { setLoggedInUserId } from "../../store/accountDetails/action"; import { setLoggedInUserId } from "../../store/accountDetails/action";
import { import {
@@ -40,7 +40,6 @@ import resolveCrmDisplayValue from "../../lib/i18n/crmDisplay/resolveCrmDisplayV
import { sendGAEvent } from "@next/third-parties/google"; import { sendGAEvent } from "@next/third-parties/google";
import RepsOnResults from "./repsonresults"; import RepsOnResults from "./repsonresults";
import LiveLink from "./liveLink"; import LiveLink from "./liveLink";
import { query } from "jsonpath";
import { splitWatchedCasesBySubmissionState } from "../../lib/domain/dashboard-policy/splitWatchedCasesBySubmissionState"; import { splitWatchedCasesBySubmissionState } from "../../lib/domain/dashboard-policy/splitWatchedCasesBySubmissionState";
const escapeRegExp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const escapeRegExp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+5 -1
View File
@@ -687,6 +687,8 @@ export const updateLinks = (input) => {
const EMPTY_QUILL_PARAGRAPHS_REGEX = const EMPTY_QUILL_PARAGRAPHS_REGEX =
/<p[^>]*>\s*(?:<br\s*\/?>|&nbsp;|\s)*\s*<\/p>/gi; /<p[^>]*>\s*(?:<br\s*\/?>|&nbsp;|\s)*\s*<\/p>/gi;
const VIDEO_EMBED_REGEX = /<(iframe|video)\b[^>]*>[\s\S]*?<\/\1\s*>/gi;
const URL_REGEX = /\b(https?:\/\/[^\s<]+)/gi; const URL_REGEX = /\b(https?:\/\/[^\s<]+)/gi;
const stripTrailingUrlPunctuation = (url) => { const stripTrailingUrlPunctuation = (url) => {
@@ -732,7 +734,9 @@ export const updateLinks = (input) => {
const processHtmlString = (htmlString) => { const processHtmlString = (htmlString) => {
if (typeof htmlString !== "string" || !htmlString) return htmlString; if (typeof htmlString !== "string" || !htmlString) return htmlString;
let html = htmlString.replace(EMPTY_QUILL_PARAGRAPHS_REGEX, ""); let html = htmlString
.replace(VIDEO_EMBED_REGEX, "")
.replace(EMPTY_QUILL_PARAGRAPHS_REGEX, "");
const anchorPlaceholders = []; const anchorPlaceholders = [];
html = html.replace(/<a\b[^>]*>[\s\S]*?<\/a>/gi, (match) => { html = html.replace(/<a\b[^>]*>[\s\S]*?<\/a>/gi, (match) => {
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-7
View File
@@ -1,7 +0,0 @@
const DNSForm = (props) => {
const { caseReference } = props;
return <></>;
};
export default DNSForm;
-353
View File
@@ -1,353 +0,0 @@
const ElectricityActForm = (props) => {
const { caseReference } = props;
return (
<>
<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds">
<h1 class="govuk-heading-m govuk-!-margin-top-5">
Enter your appeal information
</h1>
<form>
<div class="govuk-grid-column-full">
<div class="govuk-grid-row">
<div class="govuk-form-group">
<label
class="govuk-label "
for="pinswg_name"
>
Name
</label>
<input
type="text"
name="pinswg_name"
id="pinswg_name"
component="[object Object]"
class="govuk-input govuk-input--width-20"
disabled
value="CAS-00497-K4H2Z5"
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_anticipatedgridreferencenorthingtext"
id="pinswg_anticipatedgridreferencenorthingtext_label"
>
Anticipated grid reference northing
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_anticipatedgridreferencenorthingtext"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_anticipatedgridreferenceeastingtext"
id="pinswg_anticipatedgridreferenceeastingtext_label"
>
Anticipated grid reference easting
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_anticipatedgridreferenceeastingtext"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_projectname"
id="pinswg_projectname_label"
>
Project name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_projectname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_projectdiscription"
id="pinswg_projectdiscription_label"
>
Project description
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_projectdiscription"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_projectlocation"
id="pinswg_projectlocation_label"
>
Project location
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_projectlocation"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addresscounty"
id="pinswg_addresscounty_label"
>
Address county
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addresscounty"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addressline1"
id="pinswg_addressline1_label"
>
Address line 1
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addressline1"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addressline2"
id="pinswg_addressline2_label"
>
Address line 2
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addressline2"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addresstown"
id="pinswg_addresstown_label"
>
Address Town
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addresstown"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_postcode"
id="pinswg_postcode_label"
>
Post Code
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_postcode"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_agentcontactname"
id="pinswg_agentcontactname_label"
>
Agent contact name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_agentcontactname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_emailaddress"
id="pinswg_emailaddress_label"
>
Email Address
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_emailaddress"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_salutation"
id="pinswg_salutation_label"
>
Salutation
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_salutation"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_firstname"
id="pinswg_firstname_label"
>
First Name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_firstname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_lastname"
id="pinswg_lastname_label"
>
Last Name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_lastname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_organisation"
id="pinswg_organisation_label"
>
Organisation
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_organisation"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_role"
id="pinswg_role_label"
>
Role
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_role"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_telephonenumber"
id="pinswg_telephonenumber_label"
>
Telephone Number
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_telephonenumber"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_webaddress"
id="pinswg_webaddress_label"
>
Web Address
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_webaddress"
value=""
/>
</div>
</div>
</div>
<div class="govuk-button-group">
<button
type="submit"
class="govuk-button"
data-module="govuk-button"
>
Submit
</button>
</div>
</form>
</div>
</div>
</>
);
};
export default ElectricityActForm;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-353
View File
@@ -1,353 +0,0 @@
const HarbourRevisionOrderForm = (props) => {
const { caseReference } = props;
return (
<>
<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds">
<h1 class="govuk-heading-m govuk-!-margin-top-5">
Enter your appeal information
</h1>
<form>
<div class="govuk-grid-column-full">
<div class="govuk-grid-row">
<div class="govuk-form-group">
<label
class="govuk-label "
for="pinswg_name"
>
Name
</label>
<input
type="text"
name="pinswg_name"
id="pinswg_name"
component="[object Object]"
class="govuk-input govuk-input--width-20"
disabled
value="CAS-00499-C4D7R4"
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_anticipatedgridreferenceeastingtext"
id="pinswg_anticipatedgridreferenceeastingtext_label"
>
Anticipated grid reference easting
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_anticipatedgridreferenceeastingtext"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_anticipatedgridreferencenorthingtext"
id="pinswg_anticipatedgridreferencenorthingtext_label"
>
Anticipated grid reference northing
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_anticipatedgridreferencenorthingtext"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_projectname"
id="pinswg_projectname_label"
>
Project name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_projectname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_projectdiscription"
id="pinswg_projectdiscription_label"
>
Project description
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_projectdiscription"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_projectlocation"
id="pinswg_projectlocation_label"
>
Project location
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_projectlocation"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addresscounty"
id="pinswg_addresscounty_label"
>
Address county
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addresscounty"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addressline1"
id="pinswg_addressline1_label"
>
Address line 1
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addressline1"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addressline2"
id="pinswg_addressline2_label"
>
Address line 2
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addressline2"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addresstown"
id="pinswg_addresstown_label"
>
Address Town
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addresstown"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_agentcontactname"
id="pinswg_agentcontactname_label"
>
Agent contact name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_agentcontactname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_emailaddress"
id="pinswg_emailaddress_label"
>
Email Address
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_emailaddress"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_salutation"
id="pinswg_salutation_label"
>
Salutation
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_salutation"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_firstname"
id="pinswg_firstname_label"
>
First Name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_firstname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_lastname"
id="pinswg_lastname_label"
>
Last Name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_lastname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_organisation"
id="pinswg_organisation_label"
>
Organisation
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_organisation"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_postcode"
id="pinswg_postcode_label"
>
Post Code
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_postcode"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_role"
id="pinswg_role_label"
>
Role
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_role"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_telephonenumber"
id="pinswg_telephonenumber_label"
>
Telephone Number
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_telephonenumber"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_webaddress"
id="pinswg_webaddress_label"
>
Web Address
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_webaddress"
value=""
/>
</div>
</div>
</div>
<div class="govuk-button-group">
<button
type="submit"
class="govuk-button"
data-module="govuk-button"
>
Submit
</button>
</div>
</form>
</div>
</div>
</>
);
};
export default HarbourRevisionOrderForm;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-49
View File
@@ -1,49 +0,0 @@
const LdpForm = (props) => {
const { caseReference } = props;
return (
<>
<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds">
<h1 class="govuk-heading-m govuk-!-margin-top-5">
Enter your appeal information
</h1>
<form>
<div class="govuk-grid-column-full">
<div class="govuk-grid-row">
<div class="govuk-form-group">
<label
class="govuk-label "
for="pinswg_name"
>
Name
</label>
<input
type="text"
name="pinswg_name"
id="pinswg_name"
component="[object Object]"
class="govuk-input govuk-input--width-20"
disabled
value="CAS-00508-J6L1F0"
/>
</div>
</div>
</div>
<div class="govuk-button-group">
<button
type="submit"
class="govuk-button"
data-module="govuk-button"
>
Submit
</button>
</div>
</form>
</div>
</div>
</>
);
};
export default LdpForm;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-1918
View File
File diff suppressed because it is too large Load Diff
-353
View File
@@ -1,353 +0,0 @@
const TransportAndWorkActForm = (props) => {
const { caseReference } = props;
return (
<>
<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds">
<h1 class="govuk-heading-m govuk-!-margin-top-5">
Enter your appeal information
</h1>
<form>
<div class="govuk-grid-column-full">
<div class="govuk-grid-row">
<div class="govuk-form-group">
<label
class="govuk-label "
for="pinswg_name"
>
Name
</label>
<input
type="text"
name="pinswg_name"
id="pinswg_name"
component="[object Object]"
class="govuk-input govuk-input--width-20"
disabled
value="CAS-00498-H2F6B6"
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_anticipatedgridreferenceeastingtext"
id="pinswg_anticipatedgridreferenceeastingtext_label"
>
Anticipated grid reference easting
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_anticipatedgridreferenceeastingtext"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_anticipatedgridreferencenorthingtext"
id="pinswg_anticipatedgridreferencenorthingtext_label"
>
Anticipated grid reference northing
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_anticipatedgridreferencenorthingtext"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_projectname"
id="pinswg_projectname_label"
>
Project name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_projectname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_projectlocation"
id="pinswg_projectlocation_label"
>
Project location
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_projectlocation"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_projectdescription"
id="pinswg_projectdescription_label"
>
Project Description
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_projectdescription"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addresscounty"
id="pinswg_addresscounty_label"
>
Address county
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addresscounty"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addressline1"
id="pinswg_addressline1_label"
>
Address line 1
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addressline1"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addressline2"
id="pinswg_addressline2_label"
>
Address line 2
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addressline2"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_addresstown"
id="pinswg_addresstown_label"
>
Address Town
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_addresstown"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_agentcontactname"
id="pinswg_agentcontactname_label"
>
Agent contact name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_agentcontactname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_emailaddress"
id="pinswg_emailaddress_label"
>
Email Address
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_emailaddress"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_salutation"
id="pinswg_salutation_label"
>
Salutation
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_salutation"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_firstname"
id="pinswg_firstname_label"
>
First Name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_firstname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_lastname"
id="pinswg_lastname_label"
>
Last Name
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_lastname"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_organisation"
id="pinswg_organisation_label"
>
Organisation
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_organisation"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_postcode"
id="pinswg_postcode_label"
>
Post Code
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_postcode"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_role"
id="pinswg_role_label"
>
Role
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_role"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_telephonenumber"
id="pinswg_telephonenumber_label"
>
Telephone Number
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_telephonenumber"
value=""
/>
</div>
</div>
<div class="govuk-grid-row">
<div class="govuk-form-group ">
<label
class="govuk-label "
for="pinswg_webaddress"
id="pinswg_webaddress_label"
>
Web Address
</label>
<input
class="govuk-input govuk-input--width-20"
id="pinswg_webaddress"
value=""
/>
</div>
</div>
</div>
<div class="govuk-button-group">
<button
type="submit"
class="govuk-button"
data-module="govuk-button"
>
Submit
</button>
</div>
</form>
</div>
</div>
</>
);
};
export default TransportAndWorkActForm;
File diff suppressed because it is too large Load Diff
+143
View File
@@ -0,0 +1,143 @@
# Administrative authentication foundation
## Integrated administrative sign-in
Administrators sign in at `/admin/login` using the shared credential configured
as `ADMIN_AUTH_SECRET`. The page submits the credential directly to
`POST /api/admin/auth/login`; it does not place the credential in a URL or store
it in browser storage.
Successful authentication creates the administrative session cookie and sends
the browser to `/admin`. The `/admin` server-side loader validates that cookie
before loading administrative data. A valid session is not sufficient by
itself: the existing `/admin` IP allowlist remains an additional restriction,
and a valid administrator outside the allowed network is sent to `/403`.
The administrative interface provides a **Sign out** control which calls
`POST /api/admin/auth/logout`, clears the cookie, and returns the browser to
`/admin/login`. Sessions expire after 20 minutes and expired, invalid, or
missing sessions are redirected to the login page.
## Required server-side configuration
The deployment must provide all of the following server-side values:
- `ADMIN_AUTH_SECRET`: a unique high-entropy administrative passphrase of at
least 32 characters.
- `ADMIN_SESSION_SECRET`: a different unique high-entropy signing key of at
least 32 characters.
- `NEXTAUTH_URL`: the existing canonical application URL. Administrative login
and logout compare the request `Origin` with this server-configured origin.
The administrative values must never use a `NEXT_PUBLIC_` prefix or be exposed
to browser JavaScript. Do not commit real values. Missing, short, or identical
administrative secrets fail closed.
## Security properties and limitations
- Credentials are derived with Node `scrypt` and compared with
`timingSafeEqual`.
- Sessions are stateless, versioned HMAC-SHA256 tokens with a 20-minute fixed
lifetime and a random nonce.
- The cookie is `HttpOnly`, `SameSite=Strict`, scoped to `/`, explicitly
expires, and is `Secure` in production.
- Login and logout require an exact same-origin `Origin` match against
`NEXTAUTH_URL`; missing or malformed origins fail closed.
- Authentication responses use `Cache-Control: no-store`.
- Logout clears the browser cookie. Because sessions are stateless, a stolen
token can remain valid until its short expiry; later protected routes must
continue verifying signature and expiry on every request.
- This is shared-credential authentication. A valid token proves knowledge of
the shared credential, not the identity of a named administrator.
- Protecting `/admin` prevents its server-side Prisma, storage, and CRM data
loading from running without a valid administrative session. It does not by
itself protect browser-addressable API routes.
## Administrative API protection limitations
The current administrative UI directly uses API routes that do not yet enforce
the administrative session, including:
- `/api/admin/getnewappeals_api`
- `/api/admin/getlatestdocuments_api`
- `/api/admin/getStatusCountsByAppeal_api`
- `/api/admin/getStatusCountsByAppealAndLPA_api`
The appeals and documents routes expose paging operations used after the page
has loaded. The status routes expose administrative dashboard reads. These
routes retain their existing relay token and HMAC behaviour but have no
independent administrative-session authorization. A later authorised stage
must enforce the administrative session on privileged API routes and account
for both browser calls and the existing server-side bootstrap callers.
Storage download and queue actions retain their existing authorization
behaviour. The other administrative API and storage limitations described in
this section remain open.
Directly observed storage routes include:
- `/api/file/getrepsblobproxy`, which forwards a caller-supplied container using
server relay credentials and path signing.
- `/api/file/downloadblob` and `/api/file/createrepcompletemessage_api`, which
enforce existing path-HMAC checks but not administrative authorization.
## Stage 3 deletion controls
Ordinary case and representation deletion through `/api/file/deleteblobcase`
and `/api/file/deleteblobrep` now requires a valid NextAuth session whose user
ID matches the requested Azure container. The existing signed-query/HMAC check
also remains required. Requests that fail ownership or HMAC validation are
rejected before the Azure storage deletion operation is called.
Ordinary JSON and multipart uploads through `/api/file/upload` and
`/api/file/uploadsinglefile` independently require a valid NextAuth session whose
user ID exactly matches the submitted `containerID`. The existing upload HMAC
remains mandatory. Missing or unusable sessions, cross-container requests, and
invalid HMACs are rejected before file processing or Azure storage writes.
Administrative cross-container representation deletion uses the dedicated
`POST /api/admin/deleteblobrep` route. That endpoint independently validates
the administrative session and requires a trusted same-origin request. It also
validates the requested container, case-folder segment, and representation-file
segment before performing deletion.
Administrative cross-container case deletion uses the dedicated
`POST /api/admin/deleteblobcase` route. That endpoint independently validates
the administrative session, requires a trusted same-origin request, and
validates the requested container and case-folder segment before performing
deletion. It invokes the same existing `deleteBlobCase(container,
casefolderID)` operation as the ordinary endpoint. That operation lists and
deletes blobs in the selected container whose names begin with the supplied
case-folder prefix; it does not delete the Azure container or broaden deletion
to unrelated containers.
Administrative representation JSON unlocking uses the dedicated
`POST /api/admin/editRepJson` route. That endpoint independently validates the
administrative session, requires a trusted same-origin request, and validates
the requested container and blob path before removing `repComplete`. The former
`/api/file/editRepJson` route is retired and no longer performs storage access.
Automated contract verification for the implemented deletion controls has
passed, including ordinary ownership/HMAC rejection, administrative method,
session, origin and input rejection, zero deletion calls on rejected requests,
and exact cross-container helper arguments on success. Live Azure behaviour,
browser-level behaviour, and deployment configuration have not been verified
by that automated coverage. The other administrative API and storage
limitations documented above remain open, and these changes do not establish
closure of the overall ITHC finding.
## Deployment requirements before production use
The repository does not provide a demonstrated distributed rate-limit service.
Administrative login must therefore be protected by an ingress, gateway, WAF,
or shared backing service that enforces rate limits consistently across all
deployed instances. A process-local limiter is intentionally not used because
it would reset on restart and could be bypassed across instances.
The deployment must also ensure `NEXTAUTH_URL` is the correct canonical HTTPS
origin. Login and logout intentionally do not derive trust from `Host` or
forwarding headers.
Any future administrative state-changing API must require more than possession
of the cookie: it must independently validate the administrative session and
enforce same-origin/CSRF protection before performing side effects.
+25
View File
@@ -0,0 +1,25 @@
import { defineConfig } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import reactPlugin from "eslint-plugin-react";
export default defineConfig([
...nextVitals,
{
plugins: {
react: reactPlugin
},
rules: {
"@next/next/no-img-element": "off",
"react/no-unknown-property": "error"
}
},
{
files: ["pages/api/file/**/*.js"],
rules: {
"react-hooks/rules-of-hooks": "off"
}
},
{
ignores: [".next/**", "out/**", "build/**", "next-env.d.ts"]
}
]);
+228
View File
@@ -0,0 +1,228 @@
import {
createHash,
createHmac,
randomBytes,
scryptSync,
timingSafeEqual
} from "crypto";
export const ADMIN_SESSION_COOKIE = "pedw_admin_session";
export const ADMIN_SESSION_TTL_SECONDS = 20 * 60;
export const ADMIN_PASSPHRASE_MAX_LENGTH = 512;
const TOKEN_VERSION = "v1";
const AUTH_DERIVATION_SALT = "pedw-admin-auth-v1";
const MINIMUM_SECRET_LENGTH = 32;
const CLOCK_SKEW_SECONDS = 60;
const isValidSecret = (value) =>
typeof value === "string" && value.length >= MINIMUM_SECRET_LENGTH;
const getAdminConfiguration = (env = process.env) => {
const authSecret = env.ADMIN_AUTH_SECRET;
const sessionSecret = env.ADMIN_SESSION_SECRET;
if (!isValidSecret(authSecret) || !isValidSecret(sessionSecret)) {
return null;
}
const authDigest = createHash("sha256").update(authSecret).digest();
const sessionDigest = createHash("sha256").update(sessionSecret).digest();
if (timingSafeEqual(authDigest, sessionDigest)) {
return null;
}
return { authSecret, sessionSecret };
};
const deriveCredential = (value) =>
scryptSync(value, AUTH_DERIVATION_SALT, 32, {
N: 16384,
r: 8,
p: 1,
maxmem: 32 * 1024 * 1024
});
const encode = (value) => Buffer.from(value).toString("base64url");
const decode = (value) => Buffer.from(value, "base64url");
export const validateAdminPassphrase = (
passphrase,
{ env = process.env } = {}
) => {
const configuration = getAdminConfiguration(env);
if (
!configuration ||
typeof passphrase !== "string" ||
passphrase.length === 0 ||
passphrase.length > ADMIN_PASSPHRASE_MAX_LENGTH
) {
return false;
}
const expected = deriveCredential(configuration.authSecret);
const supplied = deriveCredential(passphrase);
return timingSafeEqual(expected, supplied);
};
export const issueAdminSession = (
{ env = process.env, now = Date.now, nonce = () => randomBytes(16) } = {}
) => {
const configuration = getAdminConfiguration(env);
if (!configuration) return null;
const issuedAt = Math.floor(now() / 1000);
const payload = {
v: 1,
iat: issuedAt,
exp: issuedAt + ADMIN_SESSION_TTL_SECONDS,
nonce: nonce().toString("base64url")
};
const encodedPayload = encode(JSON.stringify(payload));
const signature = createHmac("sha256", configuration.sessionSecret)
.update(`${TOKEN_VERSION}.${encodedPayload}`)
.digest("base64url");
return `${TOKEN_VERSION}.${encodedPayload}.${signature}`;
};
export const validateAdminSession = (
token,
{ env = process.env, now = Date.now } = {}
) => {
const configuration = getAdminConfiguration(env);
if (!configuration || typeof token !== "string" || token.length > 2048) {
return false;
}
const parts = token.split(".");
if (parts.length !== 3 || parts[0] !== TOKEN_VERSION) return false;
const [version, encodedPayload, suppliedSignature] = parts;
const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
if (
!base64UrlPattern.test(encodedPayload) ||
!base64UrlPattern.test(suppliedSignature)
) {
return false;
}
const expectedSignature = createHmac("sha256", configuration.sessionSecret)
.update(`${version}.${encodedPayload}`)
.digest();
let suppliedSignatureBuffer;
try {
suppliedSignatureBuffer = decode(suppliedSignature);
} catch (_error) {
return false;
}
if (
suppliedSignatureBuffer.length !== expectedSignature.length ||
!timingSafeEqual(expectedSignature, suppliedSignatureBuffer)
) {
return false;
}
let payload;
try {
payload = JSON.parse(decode(encodedPayload).toString("utf8"));
} catch (_error) {
return false;
}
const currentTime = Math.floor(now() / 1000);
return (
payload?.v === 1 &&
Number.isInteger(payload.iat) &&
Number.isInteger(payload.exp) &&
typeof payload.nonce === "string" &&
payload.nonce.length > 0 &&
payload.exp - payload.iat === ADMIN_SESSION_TTL_SECONDS &&
payload.iat <= currentTime + CLOCK_SKEW_SECONDS &&
payload.exp > currentTime
);
};
const cookieSecurityAttributes = (production) => [
"Path=/",
"HttpOnly",
"SameSite=Strict",
...(production ? ["Secure"] : [])
];
export const createAdminSessionCookie = (
token,
{ now = Date.now, production = process.env.NODE_ENV === "production" } = {}
) => {
const expires = new Date(now() + ADMIN_SESSION_TTL_SECONDS * 1000);
return [
`${ADMIN_SESSION_COOKIE}=${encodeURIComponent(token)}`,
`Max-Age=${ADMIN_SESSION_TTL_SECONDS}`,
`Expires=${expires.toUTCString()}`,
...cookieSecurityAttributes(production)
].join("; ");
};
export const createClearedAdminSessionCookie = (
{ production = process.env.NODE_ENV === "production" } = {}
) =>
[
`${ADMIN_SESSION_COOKIE}=`,
"Max-Age=0",
"Expires=Thu, 01 Jan 1970 00:00:00 GMT",
...cookieSecurityAttributes(production)
].join("; ");
export const readAdminSessionCookie = (req) => {
const rawCookie = req?.headers?.cookie;
if (typeof rawCookie !== "string") return null;
for (const entry of rawCookie.split(";")) {
const separator = entry.indexOf("=");
if (separator === -1) continue;
const name = entry.slice(0, separator).trim();
if (name !== ADMIN_SESSION_COOKIE) continue;
try {
return decodeURIComponent(entry.slice(separator + 1).trim());
} catch (_error) {
return null;
}
}
return null;
};
export const hasTrustedSameOrigin = (req, { env = process.env } = {}) => {
const requestOrigin = req?.headers?.origin;
const configuredUrl = env.NEXTAUTH_URL;
if (
typeof requestOrigin !== "string" ||
typeof configuredUrl !== "string" ||
configuredUrl.length === 0
) {
return false;
}
try {
return new URL(requestOrigin).origin === new URL(configuredUrl).origin;
} catch (_error) {
return false;
}
};
export const setAdminAuthNoStore = (res) => {
res.setHeader("Cache-Control", "no-store, max-age=0");
res.setHeader("Pragma", "no-cache");
};
+31
View File
@@ -0,0 +1,31 @@
/**
* NextAuth email provider configuration for PEDW.
*
* PEDW supplies its own sendVerificationRequest implementation using
* GOV.UK Notify, so the default Nodemailer SMTP sender is unnecessary.
*
* Preserve the NextAuth v4 email provider configuration contract.
*/
const EmailProvider = (options = {}) => ({
id: "email",
type: "email",
name: "Email",
server: {
host: "localhost",
port: 25,
auth: {
user: "",
pass: ""
}
},
from: "NextAuth <no-reply@example.com>",
maxAge: 24 * 60 * 60,
async sendVerificationRequest() {
throw new Error(
"PEDW requires a custom GOV.UK Notify verification sender"
);
},
options
});
export default EmailProvider;
+1 -1
View File
@@ -1,4 +1,4 @@
import { destroyCookie } from "nookies"; import { destroyCookie } from "../cookies";
import { signOut } from "next-auth/react"; import { signOut } from "next-auth/react";
const AUTH_COOKIE_CANDIDATES = [ const AUTH_COOKIE_CANDIDATES = [
+120
View File
@@ -0,0 +1,120 @@
import * as cookie from "cookie";
import setCookieParser from "set-cookie-parser";
const isBrowser = () => typeof window !== "undefined";
const createCookie = (name, value, options) => {
let sameSite = options.sameSite;
if (sameSite === true) {
sameSite = "strict";
}
if (sameSite === undefined || sameSite === false) {
sameSite = "lax";
}
const cookieToSet = { ...options, sameSite };
delete cookieToSet.encode;
return { name, value, ...cookieToSet };
};
const hasSameProperties = (firstCookie, secondCookie) => {
const firstProperties = Object.getOwnPropertyNames(firstCookie);
const secondProperties = Object.getOwnPropertyNames(secondCookie);
if (firstProperties.length !== secondProperties.length) {
return false;
}
return firstProperties.every(
(propertyName) =>
firstCookie[propertyName] === secondCookie[propertyName]
);
};
const areCookiesEqual = (firstCookie, secondCookie) => {
let sameSiteMatches = firstCookie.sameSite === secondCookie.sameSite;
if (
typeof firstCookie.sameSite === "string" &&
typeof secondCookie.sameSite === "string"
) {
sameSiteMatches =
firstCookie.sameSite.toLowerCase() ===
secondCookie.sameSite.toLowerCase();
}
return (
hasSameProperties(
{ ...firstCookie, sameSite: undefined },
{ ...secondCookie, sameSite: undefined }
) && sameSiteMatches
);
};
export const parseCookies = (ctx, options) => {
if (ctx?.req?.headers?.cookie) {
return cookie.parse(ctx.req.headers.cookie, options);
}
if (isBrowser()) {
return cookie.parse(document.cookie, options);
}
return {};
};
export const setCookie = (ctx, name, value, options = {}) => {
if (ctx?.res?.getHeader && ctx.res.setHeader) {
if (ctx?.res?.finished) {
console.warn(`Not setting "${name}" cookie. Response has finished.`);
console.warn("You should set cookie before res.send()");
return {};
}
let cookies = ctx.res.getHeader("Set-Cookie") || [];
if (typeof cookies === "string") {
cookies = [cookies];
}
if (typeof cookies === "number") {
cookies = [];
}
const parsedCookies = setCookieParser.parse(cookies, {
decodeValues: false
});
const newCookie = createCookie(name, value, options);
const cookiesToSet = [];
parsedCookies.forEach((parsedCookie) => {
if (!areCookiesEqual(parsedCookie, newCookie)) {
cookiesToSet.push(
cookie.serialize(parsedCookie.name, parsedCookie.value, {
encode: (cookieValue) => cookieValue,
...parsedCookie
})
);
}
});
cookiesToSet.push(cookie.serialize(name, value, options));
ctx.res.setHeader("Set-Cookie", cookiesToSet);
}
if (isBrowser()) {
if (options?.httpOnly) {
throw new Error("Can not set a httpOnly cookie in the browser.");
}
document.cookie = cookie.serialize(name, value, options);
}
return {};
};
export const destroyCookie = (ctx, name, options) =>
setCookie(ctx, name, "", { ...(options || {}), maxAge: -1 });
+3 -1
View File
@@ -120,7 +120,9 @@ export const loadRepresentationBootstrap = async ({ ctx }) => {
const [accountDetails, myRepresentations] = await Promise.all([ const [accountDetails, myRepresentations] = await Promise.all([
getPersonalAccount(loggedInUser), getPersonalAccount(loggedInUser),
getRepsFromBlob(thisSession.user.id) getRepsFromBlob(thisSession.user.id, {
headers: { Cookie: ctx.req?.headers?.cookie || "" }
})
]); ]);
const myRepresentationsDetails = await getDetails( const myRepresentationsDetails = await getDetails(
@@ -472,15 +472,6 @@ export const createDetailAndAccountRouteRenderers = ({
{t("account:account-title")} {t("account:account-title")}
</li> </li>
</> </>
),
"/account/changepassword": () => (
<>
{renderLinkCrumb(cyMyPortalHref, t("common:breadcrumb-my-portal"))}
<li className="govuk-breadcrumbs__list-item">
Update your password
</li>
</>
) )
}); });
+16
View File
@@ -0,0 +1,16 @@
import { relayGetData } from "../../pages/api/middleware/relayForwarding";
import { RELAY_POLICY_LOOKUP } from "../../pages/api/middleware/relayPolicyPresets";
export const getCrmPersonalAccount = async (contactId) => {
const queryUrl =
"contacts(" +
contactId +
")?$select=firstname, lastname, emailaddress1, telephone1, pinswg_companyname, address1_line1,address1_line2,address1_city, address1_county,address1_postalcode,pinswg_typeofinvolvement,pinswg_contact_associatedlpa,pinswg_preferredlanguage&$count=true";
const { data } = await relayGetData({
queryUrl,
relayPolicy: RELAY_POLICY_LOOKUP
});
return data;
};
+29
View File
@@ -0,0 +1,29 @@
import axios from "axios";
import { getToken } from "../../actions/core/token";
import { hashAPIPath } from "../../actions/core/hash";
const WEBAPI_URL =
process.env.RELAY_ROOT ||
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
export const updateCrmContact = async (contactId, updatePayload) => {
const token = await getToken();
const queryUrl = "contacts(" + contactId + ")";
const config = {
method: "patch",
url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
headers: {
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
Accept: "application/json",
Prefer: 'odata.include-annotations="*",return=representation',
Authorization: "Bearer " + token.access_token,
"Content-Type": "application/json"
},
data: JSON.stringify(updatePayload)
};
const response = await axios(config);
return response.data;
};
+3 -1
View File
@@ -1,5 +1,7 @@
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts";
import "./.next/types/root-params.d.ts";
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information. // see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
+1 -6
View File
@@ -58,17 +58,12 @@ const buildId = Date.now().toString();
module.exports = { module.exports = {
//output: "standalone", //output: "standalone",
eslint: {
// Warning: This allows production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true
},
reactStrictMode: false, reactStrictMode: false,
env: { env: {
BUILD_ID_ENV: buildId BUILD_ID_ENV: buildId
}, },
swcMinify: false,
sassOptions: { sassOptions: {
quietDeps: true,
includePaths: [ includePaths: [
"/styles/sass", "/styles/sass",
"node_modules/govuk-frontend/govuk/all", "node_modules/govuk-frontend/govuk/all",
+2739 -4094
View File
File diff suppressed because it is too large Load Diff
+25 -27
View File
@@ -2,15 +2,23 @@
"name": "acp", "name": "acp",
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"overrides": {
"webpack": {
"terser-webpack-plugin": {
".": "5.3.17",
"schema-utils": "4.3.0"
}
}
},
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev --webpack",
"debugdev": "NODE_OPTIONS='--inspect' next dev", "debugdev": "NODE_OPTIONS='--inspect' next dev",
"dev:app": "node ./server/server.js", "dev:app": "node ./server/server.js",
"build": "NODE_ENV=production node_modules/next/dist/bin/next build", "build": "NODE_ENV=production node_modules/next/dist/bin/next build --webpack",
"start2": "NODE_ENV=production node ./server.js", "start2": "NODE_ENV=production node ./server.js",
"start3": "NODE_ENV=production next start", "start3": "NODE_ENV=production next start",
"start": "NODE_ENV=production node_modules/next/dist/bin/next start", "start": "NODE_ENV=production node_modules/next/dist/bin/next start",
"lint": "next lint", "lint": "eslint .",
"prisma:generate": "prisma generate", "prisma:generate": "prisma generate",
"test": "playwright test", "test": "playwright test",
"test:reps": "playwright test pwe2e/tests/loggedin/raiserep.spec.js --headed", "test:reps": "playwright test pwe2e/tests/loggedin/raiserep.spec.js --headed",
@@ -22,49 +30,42 @@
"child_process": false "child_process": false
}, },
"dependencies": { "dependencies": {
"@auth/prisma-adapter": "^1.0.10", "@azure/identity": "4.14.1",
"@azure/identity": "^4.0.0",
"@azure/storage-blob": "^12.17.0", "@azure/storage-blob": "^12.17.0",
"@azure/storage-queue": "^12.16.0", "@azure/storage-queue": "^12.16.0",
"@microsoft/applicationinsights-react-js": "^17.3.2", "@microsoft/applicationinsights-react-js": "^17.3.2",
"@microsoft/applicationinsights-web": "^3.3.2", "@microsoft/applicationinsights-web": "^3.3.2",
"@next-auth/prisma-adapter": "^1.0.7", "@next-auth/prisma-adapter": "^1.0.7",
"@next/third-parties": "latest", "@next/third-parties": "16.4.4",
"@prisma/client": "^5.7.0", "@prisma/client": "^5.7.0",
"@react-pdf/renderer": "^3.1.14", "@react-pdf/renderer": "^3.1.14",
"@redux-devtools/extension": "^3.3.0", "@redux-devtools/extension": "^3.3.0",
"@xmldom/xmldom": "^0.8.10", "@xmldom/xmldom": "^0.8.10",
"applicationinsights": "^2.9.1", "axios": "^1.21.0",
"axios": "^1.7.7", "cookie": "0.7.2",
"compression": "^1.7.4",
"cookie-cutter": "^0.2.0", "cookie-cutter": "^0.2.0",
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"date-fns": "^2.30.0", "date-fns": "^2.30.0",
"dom": "^0.0.3", "dom": "^0.0.3",
"express": "^4.18.2", "express": "^4.22.3",
"file-type": "^20.4.1", "file-type": "22.3.0",
"fs": "0.0.2", "fs": "0.0.2",
"google-map-react": "^2.2.1", "google-map-react": "^2.2.1",
"govuk-frontend": "^5.0.0", "govuk-frontend": "^5.0.0",
"history": "^5.3.0", "history": "^5.3.0",
"jsonpath": "^1.1.1",
"jsonpath-plus": "^10.3.0", "jsonpath-plus": "^10.3.0",
"leaflet": "^1.9.4", "leaflet": "^1.9.4",
"leaflet-defaulticon-compatibility": "^0.1.2", "leaflet-defaulticon-compatibility": "^0.1.2",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"moment": "^2.29.4",
"multiparty": "^4.2.3", "multiparty": "^4.2.3",
"mysql": "^2.18.1", "mysql": "^2.18.1",
"next": "^14.2.28", "next": "16.4.4",
"next-auth": "^4.24.4", "next-auth": "4.24.15",
"next-build-id": "^3.0.0", "next-build-id": "^3.0.0",
"next-connect": "^0.12.2", "next-connect": "^0.12.2",
"next-redux-wrapper": "^7.0.5", "next-redux-wrapper": "^7.0.5",
"next-swagger-doc": "^0.4.0",
"next-translate": "^2.6.2", "next-translate": "^2.6.2",
"next-translate-plugin": "^2.6.2", "next-translate-plugin": "^2.6.2",
"nodemailer": "^6.9.7",
"nookies": "^2.5.2",
"notifications-node-client": "^7.0.6", "notifications-node-client": "^7.0.6",
"openapi-types": "^12.1.3", "openapi-types": "^12.1.3",
"ospoint": "^0.2.1", "ospoint": "^0.2.1",
@@ -75,15 +76,13 @@
"react": "^18.2.0", "react": "^18.2.0",
"react-accessible-accordion": "^5.0.0", "react-accessible-accordion": "^5.0.0",
"react-autosuggest": "^10.1.0", "react-autosuggest": "^10.1.0",
"react-cookie-consent": "^9.0.0", "react-cookie-consent": "^10.0.2",
"react-datepicker": "4.24.0", "react-datepicker": "4.24.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-dropzone": "^14.2.3", "react-dropzone": "^14.2.3",
"react-idle-timer": "^5.7.2", "react-idle-timer": "^5.7.2",
"react-leaflet": "^4.2.1", "react-leaflet": "^4.2.1",
"react-pdf": "^7.6.0",
"react-pdf-html": "^1.1.18", "react-pdf-html": "^1.1.18",
"react-quill": "^2.0.0",
"react-quill-new": "^3.3.3", "react-quill-new": "^3.3.3",
"react-redux": "^7.2.6", "react-redux": "^7.2.6",
"redux": "^4.2.1", "redux": "^4.2.1",
@@ -92,12 +91,11 @@
"redux-thunk": "^2.4.2", "redux-thunk": "^2.4.2",
"sass": "1.69", "sass": "1.69",
"sass-loader": "13.3.2", "sass-loader": "13.3.2",
"swagger-ui": "^5.18.2", "set-cookie-parser": "2.7.0",
"swagger-ui-react": "^5.18.2",
"tslib": "^2.7.0", "tslib": "^2.7.0",
"typescript": "^5.3.2", "typescript": "^5.3.2",
"uuid": "9.0.0", "uuid": "11.1.1",
"webpack": "^5.66.0", "webpack": "5.112.2",
"xpath": "^0.0.32" "xpath": "^0.0.32"
}, },
"resolutions": { "resolutions": {
@@ -106,8 +104,8 @@
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.62.1", "@playwright/test": "^1.62.1",
"eslint": "^8.57.0", "eslint": "9.39.5",
"eslint-config-next": "^14.2.28", "eslint-config-next": "16.4.4",
"eslint-plugin-jsdoc": "^48.2.3", "eslint-plugin-jsdoc": "^48.2.3",
"prisma": "^5.0.0" "prisma": "^5.0.0"
} }
+1 -1
View File
@@ -2,7 +2,7 @@ import Document, { Html, Head, Main, NextScript } from "next/document";
import SkipLink from "../components/skiplink"; import SkipLink from "../components/skiplink";
import { Tracking, TrackingNoScript } from "../components/tracking"; import { Tracking, TrackingNoScript } from "../components/tracking";
//import { nanoid } from "nanoid"; //import { nanoid } from "nanoid";
import { setCookie } from "nookies"; import { setCookie } from "../lib/cookies";
import Script from "next/script"; import Script from "next/script";
class MyDocument extends Document { class MyDocument extends Document {
+1 -1
View File
@@ -4,7 +4,7 @@ import Link from "next/link";
import CookieBanner from "../components/cookieBanner"; import CookieBanner from "../components/cookieBanner";
import Footer from "../components/footer"; import Footer from "../components/footer";
import Header from "../components/header"; import Header from "../components/header";
import { parseCookies, setCookie, destroyCookie } from "nookies"; import { parseCookies, setCookie, destroyCookie } from "../lib/cookies";
import { useSession, signIn, signOut } from "next-auth/react"; import { useSession, signIn, signOut } from "next-auth/react";
function Error({ statusCode }, props) { function Error({ statusCode }, props) {
-120
View File
@@ -1,120 +0,0 @@
import Link from "next/link";
import _ from "lodash";
import Head from "next/head";
import Header from "../../components/header";
import Banner from "../../components/banner";
import CookieBanner from "../../components/cookieBanner";
import Breadcrumbs from "../../components/breadcrumbs";
import Footer from "../../components/footer";
import { useSelector, shallowEqual, connect } from "react-redux";
import { wrapper } from "../../store/store";
import { useRouter } from "next/router";
import { useState } from "react";
import useTranslation from "next-translate/useTranslation";
import { JSONPath as jsonpath } from "jsonpath-plus";
import { reduxForm, formValueSelector } from "redux-form";
import ChangePassword from "../../components/account/changepassword";
import xpath from "xpath";
import {
setAppealType,
setAppealTypeTitle,
setAppealTypeID,
setAppealLPA,
getAppealTypeObj
} from "../../store/appealType/action";
import {
getAppealsTypes,
getLPA
} from "../../actions/services/referenceDataService";
import { setLPA } from "../../store/lpa/action";
import { getSession, useSession } from "next-auth/react";
import NoSessionWarning from "../../components/nosession";
const Home = (props) => {
const { footerLinks, pages, formData } = props;
let { t, lang } = useTranslation();
const router = useRouter();
const { locale } = router;
const { appealtypes } = router.query;
const { appealType, LPAData } = props;
const [passwordUpdated, setPasswordUpdated] = useState(false);
const { data: session, status } = useSession();
if (status === "loading") {
return <NoSessionWarning loading={true} />;
}
if (status === "unauthenticated") {
router.push("/auth/signin");
return <NoSessionWarning />;
}
return (
<div>
<Head>
<title>
{t("search:page-title")} - {t("common:service-name")}
</title>
</Head>
<div id="page_wrapper">
<CookieBanner />
<Header />
<div className="govuk-grid-row">
<div className="govuk-grid-column-full">
<div className="govuk-width-container">
<Breadcrumbs slug={appealtypes} props={props} />
<main
className="govuk-main-wrapper--auto-spacing"
id="main-content"
role="main"
>
<div className="govuk-grid-row">
<div className="govuk-grid-column-two-thirds">
{passwordUpdated == true ? (
<h1>
Your password has been changed
</h1>
) : (
<h1>Change password</h1>
)}
<ChangePassword
props={props}
setPasswordUpdated={
setPasswordUpdated
}
passwordUpdated={passwordUpdated}
/>
</div>
</div>
</main>
</div>
</div>
</div>
<Footer footerLinks={footerLinks} ticketnumber={props} />
</div>
</div>
);
};
const mapStateToProps = (state) => {
return {
search: state.search,
searchResultsObj: state.searchResultsObj,
formData: state.formData,
appealType: state.appealType,
LPAData: state.LPAData,
form: state.form,
accountDetails: state.accountDetails
};
};
export default connect(mapStateToProps)(Home);
+1 -1
View File
@@ -20,7 +20,7 @@ import { reduxForm, formValueSelector } from "redux-form";
import PersonalDetails from "../../components/account/personaldetails"; import PersonalDetails from "../../components/account/personaldetails";
import { setAccountDetails } from "../../store/accountDetails/action"; import { setAccountDetails } from "../../store/accountDetails/action";
import { getPersonalAccount } from "../../actions/services/accountService"; import { getPersonalAccount } from "../../actions/services/accountService";
import { setCookie } from "nookies"; import { setCookie } from "../../lib/cookies";
import { getSession, useSession } from "next-auth/react"; import { getSession, useSession } from "next-auth/react";
import NoSessionWarning from "../../components/nosession"; import NoSessionWarning from "../../components/nosession";
+44
View File
@@ -1,6 +1,7 @@
// pages/admin/storage.js // pages/admin/storage.js
import { useState } from "react"; import { useState } from "react";
import Head from "next/head"; import Head from "next/head";
import { useRouter } from "next/router";
import CookieBanner from "../../components/cookieBanner"; import CookieBanner from "../../components/cookieBanner";
import Header from "../../components/header"; import Header from "../../components/header";
import Footer from "../../components/footer"; import Footer from "../../components/footer";
@@ -29,6 +30,10 @@ import {
setSearchResults setSearchResults
} from "../../store/searchOutput/action"; } from "../../store/searchOutput/action";
import { setCurrentPage } from "../../store/currentView/action"; import { setCurrentPage } from "../../store/currentView/action";
import {
readAdminSessionCookie,
validateAdminSession
} from "../../lib/admin/adminAuth";
const StoragePage = (props) => { const StoragePage = (props) => {
const { const {
@@ -42,6 +47,27 @@ const StoragePage = (props) => {
statusLPAObj statusLPAObj
} = props; } = props;
const [whichTab, setWhichTab] = useState("appealDashboard"); const [whichTab, setWhichTab] = useState("appealDashboard");
const [signingOut, setSigningOut] = useState(false);
const router = useRouter();
const handleSignOut = async () => {
setSigningOut(true);
try {
const response = await fetch("/api/admin/auth/logout", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "same-origin"
});
if (response.ok) {
await router.replace("/admin/login");
return;
}
} finally {
setSigningOut(false);
}
};
return ( return (
<div> <div>
@@ -57,6 +83,16 @@ const StoragePage = (props) => {
style={{ width: "90%", margin: "auto" }} style={{ width: "90%", margin: "auto" }}
> >
<div className="js-enabled govuk-template__body govuk-frontend-supported"> <div className="js-enabled govuk-template__body govuk-frontend-supported">
<div className="govuk-!-margin-top-4 govuk-!-text-align-right">
<button
type="button"
className="govuk-button govuk-button--secondary"
onClick={handleSignOut}
disabled={signingOut}
>
{signingOut ? "Signing out..." : "Sign out"}
</button>
</div>
<div className="govuk-tabs" data-module="govuk-tabs"> <div className="govuk-tabs" data-module="govuk-tabs">
<h2 className="govuk-tabs__title">Contents</h2> <h2 className="govuk-tabs__title">Contents</h2>
@@ -199,6 +235,14 @@ const StoragePage = (props) => {
export const getServerSideProps = wrapper.getServerSideProps( export const getServerSideProps = wrapper.getServerSideProps(
(store) => async (ctx) => { (store) => async (ctx) => {
const { query, req, res } = ctx; const { query, req, res } = ctx;
const adminSession = readAdminSessionCookie(req);
if (!validateAdminSession(adminSession)) {
return {
redirect: { destination: "/admin/login", permanent: false }
};
}
// IP restriction check // IP restriction check
const ALLOWED_IPS = process.env.ALLOWED_IPS const ALLOWED_IPS = process.env.ALLOWED_IPS
? process.env.ALLOWED_IPS.split(",").map((ip) => ip.trim()) ? process.env.ALLOWED_IPS.split(",").map((ip) => ip.trim())
+155
View File
@@ -0,0 +1,155 @@
import Head from "next/head";
import { useRouter } from "next/router";
import { useState } from "react";
import CookieBanner from "../../components/cookieBanner";
import Footer from "../../components/footer";
import Header from "../../components/header";
import {
readAdminSessionCookie,
validateAdminSession
} from "../../lib/admin/adminAuth";
const AdminLoginPage = () => {
const router = useRouter();
const [passphrase, setPassphrase] = useState("");
const [error, setError] = useState("");
const [submitting, setSubmitting] = useState(false);
const handleSubmit = async (event) => {
event.preventDefault();
setError("");
setSubmitting(true);
try {
const response = await fetch("/api/admin/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "same-origin",
body: JSON.stringify({ passphrase })
});
if (!response.ok) {
setError("Sign in failed. Check the details and try again.");
return;
}
await router.replace("/admin");
} catch (_error) {
setError("Sign in failed. Check the details and try again.");
} finally {
setSubmitting(false);
}
};
return (
<div>
<Head>
<title>Administrative sign in</title>
</Head>
<div id="page_wrapper">
<CookieBanner />
<Header />
<main
className="govuk-width-container govuk-main-wrapper govuk-!-padding-bottom-9"
id="main-content"
>
<div className="govuk-grid-row">
<div className="govuk-grid-column-two-thirds">
<h1 className="govuk-heading-l">
Administrative sign in
</h1>
{error && (
<div
className="govuk-error-summary"
role="alert"
aria-labelledby="admin-login-error-title"
tabIndex={-1}
>
<h2
className="govuk-error-summary__title"
id="admin-login-error-title"
>
There is a problem
</h2>
<div className="govuk-error-summary__body">
<p>{error}</p>
</div>
</div>
)}
<form onSubmit={handleSubmit} noValidate>
<div
className={`govuk-form-group${
error ? " govuk-form-group--error" : ""
}`}
>
<label
className="govuk-label govuk-label--m"
htmlFor="admin-passphrase"
>
Password
</label>
{error && (
<p
id="admin-passphrase-error"
className="govuk-error-message"
>
<span className="govuk-visually-hidden">
Error:
</span>{" "}
{error}
</p>
)}
<input
className={`govuk-input${
error ? " govuk-input--error" : ""
}`}
id="admin-passphrase"
name="passphrase"
type="password"
autoComplete="current-password"
value={passphrase}
onChange={(event) =>
setPassphrase(event.target.value)
}
aria-describedby={
error
? "admin-passphrase-error"
: undefined
}
aria-invalid={error ? "true" : undefined}
disabled={submitting}
required
/>
</div>
<button
className="govuk-button"
type="submit"
disabled={submitting}
>
{submitting ? "Signing in..." : "Sign in"}
</button>
</form>
</div>
</div>
</main>
<Footer />
</div>
</div>
);
};
export const getServerSideProps = async ({ req }) => {
const adminSession = readAdminSessionCookie(req);
if (validateAdminSession(adminSession)) {
return {
redirect: { destination: "/admin", permanent: false }
};
}
return { props: {} };
};
export default AdminLoginPage;
+39
View File
@@ -0,0 +1,39 @@
import {
createAdminSessionCookie,
hasTrustedSameOrigin,
issueAdminSession,
setAdminAuthNoStore,
validateAdminPassphrase
} from "../../../../lib/admin/adminAuth";
import { respondError, respondSuccess } from "../../middleware/apiResponse";
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
export default async function handler(req, res) {
setAdminAuthNoStore(res);
res.setHeader("Allow", "POST");
if (req.method !== "POST") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Method not allowed"
});
}
if (!hasTrustedSameOrigin(req)) return forbidden(res);
const passphrase = req.body?.passphrase;
if (!validateAdminPassphrase(passphrase)) return forbidden(res);
const token = issueAdminSession();
if (!token) return forbidden(res);
res.setHeader("Set-Cookie", createAdminSessionCookie(token));
return respondSuccess(res, { authenticated: true });
}
+30
View File
@@ -0,0 +1,30 @@
import {
createClearedAdminSessionCookie,
hasTrustedSameOrigin,
setAdminAuthNoStore
} from "../../../../lib/admin/adminAuth";
import { respondError, respondSuccess } from "../../middleware/apiResponse";
export default async function handler(req, res) {
setAdminAuthNoStore(res);
res.setHeader("Allow", "POST");
if (req.method !== "POST") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Method not allowed"
});
}
if (!hasTrustedSameOrigin(req)) {
return respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
}
res.setHeader("Set-Cookie", createClearedAdminSessionCookie());
return respondSuccess(res, { authenticated: false });
}
+24
View File
@@ -0,0 +1,24 @@
import {
readAdminSessionCookie,
setAdminAuthNoStore,
validateAdminSession
} from "../../../../lib/admin/adminAuth";
import { respondError, respondSuccess } from "../../middleware/apiResponse";
export default async function handler(req, res) {
setAdminAuthNoStore(res);
res.setHeader("Allow", "GET");
if (req.method !== "GET") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Method not allowed"
});
}
const token = readAdminSessionCookie(req);
return respondSuccess(res, {
authenticated: validateAdminSession(token)
});
}
@@ -0,0 +1,82 @@
import { createRepCompleteMessage } from "../../../actions/azurestorage";
import { consoleLogger } from "../../../actions/core/logger";
import {
hasTrustedSameOrigin,
readAdminSessionCookie,
setAdminAuthNoStore,
validateAdminSession
} from "../../../lib/admin/adminAuth";
import { respondError, respondSuccess } from "../middleware/apiResponse";
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
const isValidPathSegment = (value) =>
typeof value === "string" &&
value.length > 0 &&
value.length <= 255 &&
value === value.trim() &&
value !== "." &&
value !== ".." &&
!/[\\/\u0000-\u001f\u007f]/.test(value);
export default async function handler(req, res) {
setAdminAuthNoStore(res);
res.setHeader("Allow", "POST");
if (req.method !== "POST") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Method not allowed"
});
}
const adminSession = readAdminSessionCookie(req);
if (!validateAdminSession(adminSession)) {
return forbidden(res);
}
if (!hasTrustedSameOrigin(req)) {
return forbidden(res);
}
const { container, tempcaseref, repid } = req.body ?? {};
if (
!isValidContainer(container) ||
!isValidPathSegment(tempcaseref) ||
!isValidPathSegment(repid)
) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
try {
const data = await createRepCompleteMessage(
container,
tempcaseref,
repid
);
return respondSuccess(res, data);
} catch (error) {
consoleLogger(error);
return respondError(res, {
status: 400,
code: "CREATE_REP_COMPLETE_MESSAGE_FAILED",
message: "Failed to create representation complete message"
});
}
}
+71
View File
@@ -0,0 +1,71 @@
import { deleteBlobCase } from "../../../actions/azurestorage";
import {
hasTrustedSameOrigin,
readAdminSessionCookie,
setAdminAuthNoStore,
validateAdminSession
} from "../../../lib/admin/adminAuth";
import { respondError, respondSuccess } from "../middleware/apiResponse";
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
const isValidPathSegment = (value) =>
typeof value === "string" &&
value.length > 0 &&
value.length <= 255 &&
value === value.trim() &&
value !== "." &&
value !== ".." &&
!/[\\/\u0000-\u001f\u007f]/.test(value);
export default async function handler(req, res) {
setAdminAuthNoStore(res);
res.setHeader("Allow", "POST");
if (req.method !== "POST") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Method not allowed"
});
}
const adminSession = readAdminSessionCookie(req);
if (
!validateAdminSession(adminSession) ||
!hasTrustedSameOrigin(req)
) {
return forbidden(res);
}
const { container, casefolderID } = req.body ?? {};
if (!isValidContainer(container) || !isValidPathSegment(casefolderID)) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
try {
const data = await deleteBlobCase(container, casefolderID);
return respondSuccess(res, { data });
} catch (_error) {
return respondError(res, {
status: 400,
code: "DELETE_BLOB_CASE_FAILED",
message: "Unable to delete blob case"
});
}
}
+78
View File
@@ -0,0 +1,78 @@
import { deleteBlobRep } from "../../../actions/azurestorage";
import {
hasTrustedSameOrigin,
readAdminSessionCookie,
setAdminAuthNoStore,
validateAdminSession
} from "../../../lib/admin/adminAuth";
import { respondError, respondSuccess } from "../middleware/apiResponse";
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
const isValidPathSegment = (value) =>
typeof value === "string" &&
value.length > 0 &&
value.length <= 255 &&
value === value.trim() &&
value !== "." &&
value !== ".." &&
!/[\\/\u0000-\u001f\u007f]/.test(value);
export default async function handler(req, res) {
setAdminAuthNoStore(res);
res.setHeader("Allow", "POST");
if (req.method !== "POST") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Method not allowed"
});
}
const adminSession = readAdminSessionCookie(req);
if (
!validateAdminSession(adminSession) ||
!hasTrustedSameOrigin(req)
) {
return forbidden(res);
}
const { container, casefolderID, repfile } = req.body ?? {};
if (
!isValidContainer(container) ||
!isValidPathSegment(casefolderID) ||
!isValidPathSegment(repfile)
) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
try {
const data = await deleteBlobRep(
container,
`${casefolderID}/${repfile}`
);
return respondSuccess(res, { data });
} catch (_error) {
return respondError(res, {
status: 400,
code: "DELETE_BLOB_REP_FAILED",
message: "Unable to delete blob representation"
});
}
}
+126
View File
@@ -0,0 +1,126 @@
import { DefaultAzureCredential } from "@azure/identity";
import { BlobServiceClient } from "@azure/storage-blob";
import { consoleLogger } from "../../../actions/core/logger";
import {
hasTrustedSameOrigin,
readAdminSessionCookie,
setAdminAuthNoStore,
validateAdminSession
} from "../../../lib/admin/adminAuth";
import { respondError, respondSuccess } from "../middleware/apiResponse";
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
const isValidBlobName = (value) =>
typeof value === "string" &&
value.length > 0 &&
value.length <= 1024 &&
value === value.trim() &&
!/[\\\u0000-\u001f\u007f]/.test(value) &&
value.split("/").every((segment) => segment && segment !== "." && segment !== "..");
export default async function handler(req, res) {
setAdminAuthNoStore(res);
res.setHeader("Allow", "POST");
if (req.method !== "POST") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Method not allowed"
});
}
const adminSession = readAdminSessionCookie(req);
if (
!validateAdminSession(adminSession) ||
!hasTrustedSameOrigin(req)
) {
return forbidden(res);
}
const { container, blobName } = req.body ?? {};
if (!isValidContainer(container) || !isValidBlobName(blobName)) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
try {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
const creds = new DefaultAzureCredential();
const blobServiceClient = new BlobServiceClient(
`https://${accountName}.blob.core.windows.net`,
creds
);
const containerClient = blobServiceClient.getContainerClient(container);
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const downloadResponse = await blockBlobClient.download(0);
const downloaded = await streamToString(
downloadResponse.readableStreamBody
);
const json = JSON.parse(downloaded);
if ("repComplete" in json) {
delete json.repComplete;
}
const tags = {
containerid: json.containerID,
caseID: json.ticketnumber,
blobType: "Representation"
};
const updatedContent = JSON.stringify(json, null, 2);
await blockBlobClient.upload(
updatedContent,
Buffer.byteLength(updatedContent),
{
blobHTTPHeaders: { blobContentType: "application/json" }
}
);
await blockBlobClient.setTags(tags);
await blockBlobClient.setMetadata(tags);
return respondSuccess(res, {
message: "repComplete removed successfully"
});
} catch (error) {
consoleLogger(error);
return respondError(res, {
status: 500,
code: "EDIT_REP_JSON_FAILED",
message: "Failed to edit rep.json"
});
}
}
async function streamToString(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on("data", (data) => {
chunks.push(data.toString());
});
readableStream.on("end", () => {
resolve(chunks.join(""));
});
readableStream.on("error", reject);
});
}
+97
View File
@@ -0,0 +1,97 @@
import { BASE_URL } from "../../../actions/core/env";
import { getToken } from "../../../actions/core/token";
import { azureHeaders } from "../../../actions/core/headers";
import { consoleLogger } from "../../../actions/core/logger";
import { hashAPIPath } from "../../../actions/core/hash";
import axios from "axios";
import {
ADMIN_SESSION_COOKIE,
hasTrustedSameOrigin,
readAdminSessionCookie,
setAdminAuthNoStore,
validateAdminSession
} from "../../../lib/admin/adminAuth";
import { respondError, respondSuccess } from "../middleware/apiResponse";
const isTrustedInternalDestination = () => {
try {
return (
new URL(BASE_URL).origin ===
new URL(process.env.NEXTAUTH_URL).origin
);
} catch {
return false;
}
};
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
export default async function handler(req, res) {
setAdminAuthNoStore(res);
res.setHeader("Allow", "POST");
if (req.method !== "POST") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Method not allowed"
});
}
const adminSession = readAdminSessionCookie(req);
if (!validateAdminSession(adminSession) || !hasTrustedSameOrigin(req)) {
return forbidden(res);
}
const { container } = req.body ?? {};
if (!isValidContainer(container)) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
if (!isTrustedInternalDestination()) {
return forbidden(res);
}
const token = await getToken();
const queryUrl =
"/api/file/getrepsblob?container=" + encodeURIComponent(container);
try {
const config = azureHeaders(token.access_token);
const { data } = await axios.get(
BASE_URL + queryUrl + hashAPIPath(queryUrl),
{
...config,
headers: {
...config.headers,
Cookie: `${ADMIN_SESSION_COOKIE}=${encodeURIComponent(adminSession)}`
},
maxRedirects: 0
}
);
return respondSuccess(res, data);
} catch (error) {
consoleLogger(error);
return respondError(res, {
status: 400,
code: "GET_REPS_BLOB_PROXY_FAILED",
message: "Failed to fetch representation blobs"
});
}
}
+2 -2
View File
@@ -13,7 +13,7 @@
import { PrismaAdapter } from "@next-auth/prisma-adapter"; import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client"; import { PrismaClient } from "@prisma/client";
import NextAuth from "next-auth"; import NextAuth from "next-auth";
import EmailProvider from "next-auth/providers/email"; import EmailProvider from "../../../lib/auth/email-provider";
import { consoleLogger, redactSensitive } from "../../../actions/core/logger"; import { consoleLogger, redactSensitive } from "../../../actions/core/logger";
import { getPortalLogin } from "../../../actions/services/accountService"; import { getPortalLogin } from "../../../actions/services/accountService";
@@ -199,7 +199,7 @@ const resolveRequestLocale = (req) => {
return resolved; return resolved;
}; };
const authOptions = (req, res) => { export const authOptions = (req, res) => {
const requestLocale = resolveRequestLocale(req); const requestLocale = resolveRequestLocale(req);
const verificationTokenCompletion = createVerificationTokenCompletion(); const verificationTokenCompletion = createVerificationTokenCompletion();
-13
View File
@@ -1,13 +0,0 @@
import { withSwagger } from 'next-swagger-doc';
const swaggerHandler = withSwagger({
definition: {
openapi: '3.0.0',
info: {
title: 'PEDW Example',
version: '0.1.0',
},
},
schemaFolders: ['models'],
});
export default swaggerHandler();
-150
View File
@@ -1,150 +0,0 @@
/**
* @swagger
* /api/endpoint/createcase_api:
* post:
* tags: [Case]
* description: Create case
* summary: Phase 2
* parameters:
* - name: body
* in: requestbody
* required: true
* example: {}
* schema:
* type: object
* - name: contactid
* in: query
* required: true
* example: pinswg_planningappeals78s
* schema:
* type: string
* - name: appealTypeId
* in: query
* required: true
* example: pinswg_planningappeals78id
* schema:
* type: string
* - name: containername
* in: query
* required: true
* example: pinswg_planningappeals78id
* schema:
* type: string
* - name: lpaID
* in: query
* required: true
* example: pinswg_planningappeals78id
* schema:
* type: string
* responses:
* 200:
* description: Success
*/
import axios from "axios";
import { consoleLogger } from "../../../actions/core/logger";
import { getToken } from "../../../actions/core/token";
import { getCaseBlob } from "../../../actions/azurestorage";
import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse";
const WEBAPI_URL =
process.env.RELAY_ROOT ||
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
export default async function ApiProxy(req, res) {
const createCaseBody = req.body;
const contactid = req.query.contactid;
const appealTypeId = req.query.appealTypeId;
const containerName = req.query.containername;
const lpaID = req.query.lpaID;
const queryUrl = "incidents";
if (!createCaseBody || typeof createCaseBody !== "object") {
return respondError(res, {
status: 400,
code: "CASE_PAYLOAD_REQUIRED",
message: "Case payload is required"
});
}
if (typeof contactid !== "string" || contactid.trim().length === 0) {
return respondError(res, {
status: 400,
code: "CONTACT_ID_REQUIRED",
message: "contactid is required"
});
}
if (typeof appealTypeId !== "string" || appealTypeId.trim().length === 0) {
return respondError(res, {
status: 400,
code: "APPEAL_TYPE_ID_REQUIRED",
message: "appealTypeId is required"
});
}
if (
typeof containerName !== "string" ||
containerName.trim().length === 0
) {
return respondError(res, {
status: 400,
code: "CONTAINER_NAME_REQUIRED",
message: "containername is required"
});
}
if (typeof lpaID !== "string" || lpaID.trim().length === 0) {
return respondError(res, {
status: 400,
code: "LPA_ID_REQUIRED",
message: "lpaID is required"
});
}
try {
const token = await getToken();
const data = {
"title": "insertion test case",
"caseorigincode": 3,
"servicestage": 1,
"customerid_contact@odata.bind": "/contacts(" + contactid + ")",
"pinswg_appealcasetype": appealTypeId,
"pinswg_AssociatedLPA@odata.bind": "/accounts(" + lpaID + ")"
};
const newData = Object.assign(data, createCaseBody);
delete newData.lpaTypes;
delete newData.appealTypes;
console.log("/////Create Case:\n", newData, "\n//////////////");
const config = {
method: "post",
url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
headers: {
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
"Accept": "application/json",
"Prefer": 'odata.include-annotations="*",return=representation',
"Authorization": "Bearer " + token.access_token,
"Content-Type": "application/json"
},
data: JSON.stringify(newData)
};
const { data: responseData } = await axios(config);
await getCaseBlob(
containerName,
responseData.ticketnumber,
createCaseBody
);
return respondSuccess(res, responseData);
} catch (error) {
consoleLogger(error);
return respondError(res, {
status: 400,
code: "CASE_CREATE_FAILED",
message: "Failed to create case"
});
}
}
-43
View File
@@ -1,46 +1,3 @@
/**
* @swagger
* /api/endpoint/createcase_api:
* post:
* tags: [Case]
* description: Create case
* summary: Phase 2
* parameters:
* - name: body
* in: requestbody
* required: true
* example: {}
* schema:
* type: object
* - name: contactid
* in: query
* required: true
* example: pinswg_planningappeals78s
* schema:
* type: string
* - name: appealTypeId
* in: query
* required: true
* example: pinswg_planningappeals78id
* schema:
* type: string
* - name: containername
* in: query
* required: true
* example: pinswg_planningappeals78id
* schema:
* type: string
* - name: lpaID
* in: query
* required: true
* example: pinswg_planningappeals78id
* schema:
* type: string
* responses:
* 200:
* description: Success
*/
import axios from "axios"; import axios from "axios";
import { isNonEmptyString, sanitizeString } from "../../../actions/core/guards"; import { isNonEmptyString, sanitizeString } from "../../../actions/core/guards";
import { consoleLogger } from "../../../actions/core/logger"; import { consoleLogger } from "../../../actions/core/logger";
+156 -21
View File
@@ -16,16 +16,24 @@ import { getToken } from "../../../actions/core/token";
import { hashAPIPath } from "../../../actions/core/hash"; import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
import { relayGetData } from "../middleware/relayForwarding"; import { relayGetData } from "../middleware/relayForwarding";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import { azureHeaders } from "../../../actions/core/headers";
import { escapeODataString } from "../../../actions/core/guards";
const WEBAPI_URL = const WEBAPI_URL =
process.env.RELAY_ROOT || process.env.RELAY_ROOT ||
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/"; "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
const GUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const recordExists = async (incidentId, contactId, accessToken) => { const recordExists = async (incidentId, contactId, accessToken) => {
const filter = `$filter=pinswg_WatchedCase/incidentid eq ${incidentId} and pinswg_Contact/contactid eq ${contactId}`; const filter = `$filter=pinswg_WatchedCase/incidentid eq ${incidentId} and pinswg_Contact/contactid eq ${contactId}`;
const queryUrl = `pinswg_watchlists?${filter}`; const queryUrl =
`pinswg_watchlists?${filter}` +
"&$select=pinswg_watchlistid,_pinswg_contact_value,_pinswg_watchedcase_value,pinswg_representationsubmitted";
try {
const response = await relayGetData({ const response = await relayGetData({
queryUrl, queryUrl,
accessToken, accessToken,
@@ -37,17 +45,44 @@ const recordExists = async (incidentId, contactId, accessToken) => {
}) })
}); });
if (response.data.value && response.data.value.length > 0) { const records = response?.data?.value;
return response.data.value[0]; // return the existing record
if (!Array.isArray(records)) {
return {
status: "invalid",
records: []
};
} }
return null; return {
} catch (err) { status: "found",
throw err; records
} };
}; };
export default async function ApiProxy(req, res) { export default async function ApiProxy(req, res) {
if (req.method !== "POST") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Only POST is supported"
});
}
const session = await getServerSession(req, res, authOptions(req, res));
const authenticatedEmail = session?.user?.email;
if (
typeof authenticatedEmail !== "string" ||
authenticatedEmail.trim().length === 0
) {
return respondError(res, {
status: 401,
code: "UNAUTHENTICATED",
message: "Authentication required"
});
}
const data = req.body; const data = req.body;
const watchedCaseBind = data?.["pinswg_WatchedCase@odata.bind"]; const watchedCaseBind = data?.["pinswg_WatchedCase@odata.bind"];
const contactBind = data?.["pinswg_Contact@odata.bind"]; const contactBind = data?.["pinswg_Contact@odata.bind"];
@@ -66,8 +101,13 @@ export default async function ApiProxy(req, res) {
}); });
} }
const watchedCaseMatch = watchedCaseBind.match(/\(([^)]+)\)/); const watchedCaseMatch = watchedCaseBind.match(
const contactMatch = contactBind.match(/\(([^)]+)\)/); /^\/incidents\(([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)$/i
);
const contactMatch = contactBind.match(
/^\/contacts\(([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)$/i
);
if (!watchedCaseMatch || !contactMatch) { if (!watchedCaseMatch || !contactMatch) {
return respondError(res, { return respondError(res, {
@@ -79,26 +119,118 @@ export default async function ApiProxy(req, res) {
try { try {
const token = await getToken(); const token = await getToken();
const incidentId = watchedCaseMatch[1]; const incidentId = watchedCaseMatch[1];
const contactId = contactMatch[1]; const contactId = contactMatch[1];
const existingRecord = await recordExists( const escapedEmail = escapeODataString(authenticatedEmail);
const contactQueryUrl =
"contacts?$filter=emailaddress1 eq '" +
escapedEmail +
"' and statuscode eq 1&$select=contactid";
const contactResponse = await relayGetData({
queryUrl: contactQueryUrl,
accessToken: token.access_token,
requestOptionsBuilder: (accessToken) => azureHeaders(accessToken)
});
const contacts = contactResponse?.data?.value;
if (
!Array.isArray(contacts) ||
contacts.length !== 1 ||
typeof contacts[0]?.contactid !== "string" ||
!GUID_PATTERN.test(contacts[0].contactid.trim())
) {
return respondError(res, {
status: 403,
code: "CONTACT_IDENTITY_NOT_RESOLVED",
message: "Request not permitted"
});
}
if (
contactId.trim().toLowerCase() !==
contacts[0].contactid.trim().toLowerCase()
) {
return respondError(res, {
status: 403,
code: "CONTACT_OWNERSHIP_MISMATCH",
message: "Request not permitted"
});
}
const lookup = await recordExists(
incidentId, incidentId,
contactId, contactId,
token.access_token token.access_token
); );
let method, queryUrl; if (lookup.status === "invalid") {
return respondError(res, {
if (existingRecord) { status: 500,
method = "patch"; code: "WATCHLIST_LOOKUP_FAILED",
queryUrl = `pinswg_watchlists(${existingRecord.pinswg_watchlistid})`; message: "Unable to verify existing watched-case records"
} else { });
method = "post";
queryUrl = "pinswg_watchlists";
} }
const records = lookup.records;
const isRepresentationSubmission =
data?.pinswg_representationsubmitted != null;
// Validate every returned record before considering it for an update.
const validRecords = records.every((record) => {
const recordID = record?.pinswg_watchlistid;
const recordContactID = record?._pinswg_contact_value;
const recordCaseID = record?._pinswg_watchedcase_value;
return (
typeof recordID === "string" &&
GUID_PATTERN.test(recordID) &&
typeof recordContactID === "string" &&
GUID_PATTERN.test(recordContactID) &&
typeof recordCaseID === "string" &&
GUID_PATTERN.test(recordCaseID) &&
recordContactID.toLowerCase() === contactId.toLowerCase() &&
recordCaseID.toLowerCase() === incidentId.toLowerCase()
);
});
if (!validRecords) {
return respondError(res, {
status: 403,
code: "WATCHLIST_OWNERSHIP_MISMATCH",
message: "Request not permitted"
});
}
const watchingOnlyRecords = records.filter(
(record) => record.pinswg_representationsubmitted == null
);
let existingRecord;
if (isRepresentationSubmission) {
// Reuse a watching-only record for the first representation.
// Never overwrite an earlier representation submission.
existingRecord =
watchingOnlyRecords.length === 1
? watchingOnlyRecords[0]
: null;
} else {
// Watching or subscribing: prefer a watching-only record.
// Otherwise reuse an existing representation-associated record.
existingRecord = watchingOnlyRecords[0] ?? records[0] ?? null;
}
const method = existingRecord ? "patch" : "post";
const queryUrl = existingRecord
? `pinswg_watchlists(${existingRecord.pinswg_watchlistid})`
: "pinswg_watchlists";
const config = { const config = {
method: method, method: method,
url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
@@ -110,7 +242,10 @@ export default async function ApiProxy(req, res) {
Authorization: "Bearer " + token.access_token, Authorization: "Bearer " + token.access_token,
"Content-Type": "application/json" "Content-Type": "application/json"
}, },
data: JSON.stringify(data) data: JSON.stringify({
...data,
"pinswg_Contact@odata.bind": `/contacts(${contacts[0].contactid.trim()})`
})
}; };
const result = await axios(config); const result = await axios(config);
@@ -1,66 +0,0 @@
/**
* @swagger
* /api/endpoint/deleteamyrepresentations_api:
* delete:
* tags: [Portal,Representations]
* summary: Phase 2
* description: Delete my representations
* responses:
* 200:
* description: Success
*/
import axios from "axios";
import { consoleLogger } from "../../../actions/core/logger";
import { getToken } from "../../../actions/core/token";
import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse";
const WEBAPI_URL =
process.env.RELAY_ROOT ||
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
export default async function ApiProxy(req, res) {
const myRepresentationsID = req.query.myRepresentationsID;
if (
typeof myRepresentationsID !== "string" ||
myRepresentationsID.trim().length === 0
) {
return respondError(res, {
status: 400,
code: "MY_REPRESENTATION_ID_REQUIRED",
message: "myRepresentationsID is required"
});
}
try {
const token = await getToken();
const queryUrl =
"pinswg_representationses(" + myRepresentationsID + ")";
const config = {
method: "delete",
url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
headers: {
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
Accept: "application/json",
Prefer: 'odata.include-annotations="*",return=representation',
Authorization: "Bearer " + token.access_token,
"Content-Type": "application/json"
}
};
const { data } = await axios(config);
return respondSuccess(res, data);
} catch (error) {
consoleLogger(error);
return respondError(res, {
status: 400,
code: "MY_REPRESENTATION_DELETE_FAILED",
message: "Failed to delete representation"
});
}
}
+116 -5
View File
@@ -11,32 +11,143 @@
*/ */
import axios from "axios"; import axios from "axios";
import { getServerSession } from "next-auth/next";
import { azureHeaders } from "../../../actions/core/headers";
import { escapeODataString } from "../../../actions/core/guards";
import { consoleLogger } from "../../../actions/core/logger"; import { consoleLogger } from "../../../actions/core/logger";
import { getToken } from "../../../actions/core/token"; import { getToken } from "../../../actions/core/token";
import { hashAPIPath } from "../../../actions/core/hash"; import { hashAPIPath } from "../../../actions/core/hash";
import { authOptions } from "../auth/[...nextauth]";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
import { relayGetData } from "../middleware/relayForwarding";
const WEBAPI_URL = const WEBAPI_URL =
process.env.RELAY_ROOT || process.env.RELAY_ROOT ||
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/"; "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
const GUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const normaliseGuid = (value) => value.trim().toLowerCase();
export default async function ApiProxy(req, res) { export default async function ApiProxy(req, res) {
const watchedCaseID = req.query.watchedCaseID; const watchedCaseID = req.query.watchedCaseID;
if ( if (
typeof watchedCaseID !== "string" || typeof watchedCaseID !== "string" ||
watchedCaseID.trim().length === 0 !GUID_PATTERN.test(watchedCaseID)
) { ) {
return respondError(res, { return respondError(res, {
status: 400, status: 400,
code: "WATCHED_CASE_ID_REQUIRED", code: "INVALID_WATCHED_CASE_ID",
message: "watchedCaseID is required" message: "watchedCaseID must be a valid GUID"
});
}
if (req.method !== "DELETE") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Only DELETE is supported"
});
}
const session = await getServerSession(req, res, authOptions(req, res));
const authenticatedEmail = session?.user?.email;
if (
typeof authenticatedEmail !== "string" ||
authenticatedEmail.trim().length === 0
) {
return respondError(res, {
status: 401,
code: "UNAUTHENTICATED",
message: "Authentication required"
}); });
} }
try { try {
const token = await getToken(); const token = await getToken();
const queryUrl = "pinswg_watchlists(" + watchedCaseID + ")"; const requestOptionsBuilder = (accessToken) => azureHeaders(accessToken);
const escapedEmail = escapeODataString(authenticatedEmail);
const contactQueryUrl =
"contacts?$filter=emailaddress1 eq '" +
escapedEmail +
"' and statuscode eq 1&$select=contactid";
const contactResponse = await relayGetData({
queryUrl: contactQueryUrl,
accessToken: token.access_token,
requestOptionsBuilder
});
const contacts = contactResponse?.data?.value;
if (!Array.isArray(contacts)) {
return respondError(res, {
status: 500,
code: "CONTACT_LOOKUP_FAILED",
message: "Unable to verify portal contact"
});
}
if (
contacts.length !== 1 ||
typeof contacts[0]?.contactid !== "string" ||
!GUID_PATTERN.test(contacts[0].contactid.trim())
) {
return respondError(res, {
status: 403,
code: "CONTACT_IDENTITY_NOT_RESOLVED",
message: "Request not permitted"
});
}
const normalisedWatchedCaseID = normaliseGuid(watchedCaseID);
const watchlistQueryUrl =
"pinswg_watchlists(" +
normalisedWatchedCaseID +
")?$select=pinswg_watchlistid,_pinswg_contact_value";
let watchlistResponse;
try {
watchlistResponse = await relayGetData({
queryUrl: watchlistQueryUrl,
accessToken: token.access_token,
requestOptionsBuilder
});
} catch (error) {
if (error?.response?.status === 404) {
return respondError(res, {
status: 404,
code: "WATCHED_CASE_NOT_FOUND",
message: "Watched case not found"
});
}
throw error;
}
const watchlist = watchlistResponse?.data;
const watchlistContactID = watchlist?._pinswg_contact_value;
const watchlistRecordID = watchlist?.pinswg_watchlistid;
if (
typeof watchlistRecordID !== "string" ||
!GUID_PATTERN.test(watchlistRecordID.trim()) ||
normaliseGuid(watchlistRecordID) !== normalisedWatchedCaseID ||
typeof watchlistContactID !== "string" ||
!GUID_PATTERN.test(watchlistContactID.trim()) ||
normaliseGuid(watchlistContactID) !==
normaliseGuid(contacts[0].contactid)
) {
return respondError(res, {
status: 404,
code: "WATCHED_CASE_NOT_FOUND",
message: "Watched case not found"
});
}
const queryUrl =
"pinswg_watchlists(" + normalisedWatchedCaseID + ")";
const config = { const config = {
method: "delete", method: "delete",
@@ -56,7 +167,7 @@ export default async function ApiProxy(req, res) {
} catch (error) { } catch (error) {
consoleLogger(error); consoleLogger(error);
return respondError(res, { return respondError(res, {
status: 400, status: 500,
code: "WATCHED_CASE_DELETE_FAILED", code: "WATCHED_CASE_DELETE_FAILED",
message: "Failed to delete watched case" message: "Failed to delete watched case"
}); });
+70 -4
View File
@@ -1,12 +1,25 @@
import { hashAPIPath } from "../../../actions/core/hash"; import { hashAPIPath } from "../../../actions/core/hash";
import nextConnect from "next-connect"; import nextConnect from "next-connect";
import { getSession } from "next-auth/react"; import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
const ApiProxy = nextConnect(); const ApiProxy = nextConnect();
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
const isValidTempCaseRef = (value) =>
typeof value === "string" &&
value.length <= 100 &&
!value.includes("..") &&
/^[A-Za-z0-9](?:[A-Za-z0-9/-]*[A-Za-z0-9])?$/.test(value);
ApiProxy.get(async (req, res) => { ApiProxy.get(async (req, res) => {
const session = await getSession({ req }); const session = await getServerSession(req, res, authOptions(req, res));
if (!session) { if (!session) {
return respondError(res, { return respondError(res, {
@@ -25,8 +38,8 @@ ApiProxy.get(async (req, res) => {
const allowedPrefix = [ const allowedPrefix = [
"/api/endpoint/getportallogin_api", "/api/endpoint/getportallogin_api",
"/api/endpoint/deletemyrepresentations_api",
"/api/endpoint/deletewatchedcases_api", "/api/endpoint/deletewatchedcases_api",
"/api/subscriptions/delete-watched-case",
"/api/file/upload", "/api/file/upload",
"/api/file/uploadsinglefile", "/api/file/uploadsinglefile",
"/api/file/deleteblobcase", "/api/file/deleteblobcase",
@@ -41,7 +54,7 @@ ApiProxy.get(async (req, res) => {
typeof queryPath !== "string" || typeof queryPath !== "string" ||
queryPath.length === 0 || queryPath.length === 0 ||
!queryPath.startsWith("/api/") || !queryPath.startsWith("/api/") ||
!allowedPrefix.some((prefix) => queryPath.startsWith(prefix)) || !allowedPrefix.includes(queryPath) ||
queryPath.includes("/api/endpoint/gethash_api") queryPath.includes("/api/endpoint/gethash_api")
) { ) {
return respondError(res, { return respondError(res, {
@@ -51,6 +64,59 @@ ApiProxy.get(async (req, res) => {
}); });
} }
if (
queryPath.startsWith("/api/file/createappealcompletemessage_api") &&
queryPath !== "/api/file/createappealcompletemessage_api"
) {
return respondError(res, {
status: 400,
code: "INVALID_HASH_PATH",
message: "Invalid path for hash generation"
});
}
if (queryPath === "/api/file/createappealcompletemessage_api") {
let completionPath;
try {
completionPath = new URL(rawQueryPath, "http://localhost");
} catch (_error) {
return respondError(res, {
status: 400,
code: "INVALID_HASH_PATH",
message: "Invalid path for hash generation"
});
}
const containerName = completionPath.searchParams.get("container");
const tempCaseRef = completionPath.searchParams.get("tempcaseref");
if (
!isValidContainer(containerName) ||
!isValidTempCaseRef(tempCaseRef) ||
completionPath.searchParams.getAll("container").length !== 1 ||
completionPath.searchParams.getAll("tempcaseref").length !== 1
) {
return respondError(res, {
status: 400,
code: "INVALID_HASH_PATH",
message: "Invalid path for hash generation"
});
}
if (
typeof session?.user?.id !== "string" ||
session.user.id.length === 0 ||
session.user.id !== containerName
) {
return respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
}
}
return respondSuccess(res, { hash: hashAPIPath(rawQueryPath) }); return respondSuccess(res, { hash: hashAPIPath(rawQueryPath) });
}); });
-69
View File
@@ -1,69 +0,0 @@
/**
* @swagger
* /api/endpoint/getlogin_api:
* get:
* tags: [Login]
* description: Returns the hello world
* summary: Phase 2
* parameters:
* - name: emailaddress
* in: query
* required: true
* schema:
* type: string
* - name: pwd
* in: query
* required: true
* schema:
* type: string
* responses:
* 200:
* description: hello world
*/
import { azureHeadersPaged } from "../../../actions/core/headers";
import { respondError } from "../middleware/apiResponse";
import { relayGet } from "../middleware/relayForwarding";
import { RELAY_POLICY_STRICT_LOGIN } from "../middleware/relayPolicyPresets";
export default async function ApiProxy(req, res) {
const emailAddress = req.query.emailAddress;
const pwd = req.query.pwd;
if (typeof emailAddress !== "string" || emailAddress.trim().length === 0) {
return respondError(res, {
status: 400,
code: "EMAIL_ADDRESS_REQUIRED",
message: "emailAddress is required"
});
}
if (typeof pwd !== "string" || pwd.trim().length === 0) {
return respondError(res, {
status: 400,
code: "PASSWORD_REQUIRED",
message: "pwd is required"
});
}
const queryUrl =
"contacts?$filter=emailaddress1 eq '" +
emailAddress +
"' and pinswg_custom_password eq '" +
pwd +
"'&$count=true&$select=emailaddress1,contactid,pinswg_custom_password,yomifullname,firstname,lastname";
const relayPolicy = RELAY_POLICY_STRICT_LOGIN;
return relayGet({
queryUrl,
res,
requestOptionsBuilder: (accessToken) => azureHeadersPaged(accessToken),
relayPolicy,
errorResponse: {
status: 400,
code: "LOGIN_FETCH_FAILED",
message: "Failed to fetch login details"
}
});
}
+110 -42
View File
@@ -1,37 +1,68 @@
/**
* @swagger
* /api/endpoint/updateaccount_api:
* patch:
* tags: [Account]
* description: Update account
* summary: Phase 2
* responses:
* 200:
* description: Success
*/
import axios from "axios";
import { consoleLogger } from "../../../actions/core/logger"; import { consoleLogger } from "../../../actions/core/logger";
import { getToken } from "../../../actions/core/token";
import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
import { updateCrmContact } from "../../../lib/server/updateCrmContact";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import { getToken } from "../../../actions/core/token";
import { relayGetData } from "../middleware/relayForwarding";
import { azureHeaders } from "../../../actions/core/headers";
import { escapeODataString } from "../../../actions/core/guards";
const WEBAPI_URL = const GUID_PATTERN =
process.env.RELAY_ROOT || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
const ALLOWED_ACCOUNT_FIELDS = new Set([
"pinswg_preferredlanguage",
"firstname",
"lastname",
"telephone1",
"pinswg_companyname",
"address1_line1",
"address1_line2",
"address1_city",
"address1_county",
"address1_postalcode"
]);
export default async function ApiProxy(req, res) { export default async function ApiProxy(req, res) {
const contactId = req.query.contactId; if (req.method !== "POST") {
res.setHeader("Allow", "POST");
if (typeof contactId !== "string" || contactId.trim().length === 0) {
return respondError(res, { return respondError(res, {
status: 400, status: 405,
code: "CONTACT_ID_REQUIRED", code: "METHOD_NOT_ALLOWED",
message: "contactId is required" message: "Method not allowed"
}); });
} }
if (!req.body || Object.keys(req.body).length === 0) { const session = await getServerSession(req, res, authOptions(req, res));
if (
typeof session?.user?.email !== "string" ||
session.user.email.trim().length === 0
) {
return respondError(res, {
status: 401,
code: "UNAUTHENTICATED",
message: "Authentication required"
});
}
const contactId = req.query.contactId;
if (typeof contactId !== "string" || !GUID_PATTERN.test(contactId.trim())) {
return respondError(res, {
status: 400,
code: "INVALID_CONTACT_ID",
message: "A valid contactId is required"
});
}
if (
!req.body ||
typeof req.body !== "object" ||
Array.isArray(req.body) ||
Object.keys(req.body).length === 0
) {
return respondError(res, { return respondError(res, {
status: 400, status: 400,
code: "ACCOUNT_UPDATE_PAYLOAD_REQUIRED", code: "ACCOUNT_UPDATE_PAYLOAD_REQUIRED",
@@ -41,25 +72,62 @@ export default async function ApiProxy(req, res) {
try { try {
const token = await getToken(); const token = await getToken();
const data = JSON.stringify(req.body);
const queryUrl = "contacts(" + contactId + ")";
const config = { const escapedEmail = escapeODataString(session.user.email);
method: "patch",
url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
headers: {
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
Accept: "application/json",
Prefer: 'odata.include-annotations="*",return=representation',
Authorization: "Bearer " + token.access_token,
"Content-Type": "application/json"
},
data
};
const response = await axios(config); const contactQueryUrl =
return respondSuccess(res, response.data); "contacts?$filter=emailaddress1 eq '" +
escapedEmail +
"' and statuscode eq 1&$select=contactid";
const contactResponse = await relayGetData({
queryUrl: contactQueryUrl,
accessToken: token.access_token,
requestOptionsBuilder: (accessToken) => azureHeaders(accessToken)
});
const contacts = contactResponse?.data?.value;
if (
!Array.isArray(contacts) ||
contacts.length !== 1 ||
typeof contacts[0]?.contactid !== "string" ||
!GUID_PATTERN.test(contacts[0].contactid.trim())
) {
return respondError(res, {
status: 403,
code: "CONTACT_IDENTITY_NOT_RESOLVED",
message: "Request not permitted"
});
}
if (
contactId.trim().toLowerCase() !==
contacts[0].contactid.trim().toLowerCase()
) {
return respondError(res, {
status: 403,
code: "CONTACT_OWNERSHIP_MISMATCH",
message: "Request not permitted"
});
}
const updatePayload = Object.fromEntries(
Object.entries(req.body).filter(([field]) =>
ALLOWED_ACCOUNT_FIELDS.has(field)
)
);
if (Object.keys(updatePayload).length === 0) {
return respondError(res, {
status: 400,
code: "NO_ALLOWED_ACCOUNT_FIELDS",
message: "No permitted account fields supplied"
});
}
const data = await updateCrmContact(contactId.trim(), updatePayload);
return respondSuccess(res, data);
} catch (error) { } catch (error) {
consoleLogger(error); consoleLogger(error);
return respondError(res, { return respondError(res, {
-71
View File
@@ -1,71 +0,0 @@
/**
* @swagger
* /api/endpoint/updatepassword_api:
* patch:
* tags: [Account]
* description: Update password
* summary: Phase 2
* responses:
* 200:
* description: Success
*/
import axios from "axios";
import { consoleLogger } from "../../../actions/core/logger";
import { getToken } from "../../../actions/core/token";
import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse";
const WEBAPI_URL =
process.env.RELAY_ROOT ||
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
export default async function ApiProxy(req, res) {
const contactId = req.query.contactId;
if (typeof contactId !== "string" || contactId.trim().length === 0) {
return respondError(res, {
status: 400,
code: "CONTACT_ID_REQUIRED",
message: "contactId is required"
});
}
if (!req.body || Object.keys(req.body).length === 0) {
return respondError(res, {
status: 400,
code: "PASSWORD_UPDATE_PAYLOAD_REQUIRED",
message: "Password update payload is required"
});
}
try {
const token = await getToken();
const data = JSON.stringify(req.body);
const queryUrl = "contacts(" + contactId + ")";
const config = {
method: "patch",
url: WEBAPI_URL + queryUrl + hashAPIPath(queryUrl),
headers: {
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
Accept: "application/json",
Prefer: 'odata.include-annotations="*",return=representation',
Authorization: "Bearer " + token.access_token,
"Content-Type": "application/json"
},
data
};
const response = await axios(config);
return respondSuccess(res, response.data);
} catch (error) {
consoleLogger(error);
return respondError(res, {
status: 400,
code: "PASSWORD_UPDATE_FAILED",
message: "Failed to update password"
});
}
}
@@ -1,4 +1,4 @@
import { updateAccount } from "../../../actions/services/accountService"; import { updateCrmContact } from "../../../lib/server/updateCrmContact";
import { hashAPIPath } from "../../../actions/core/hash"; import { hashAPIPath } from "../../../actions/core/hash";
import { consoleLogger } from "../../../actions/core/logger"; import { consoleLogger } from "../../../actions/core/logger";
import { import {
@@ -13,10 +13,34 @@ import _ from "lodash";
import nextConnect from "next-connect"; import nextConnect from "next-connect";
import middleware from "../middleware/middleware"; import middleware from "../middleware/middleware";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
const ApiProxy = nextConnect(); const ApiProxy = nextConnect();
ApiProxy.use(middleware); ApiProxy.use(middleware);
const hasValue = (value) =>
typeof value === "string" && value.trim().length > 0;
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
const isValidTempCaseRef = (value) =>
typeof value === "string" &&
value.length <= 100 &&
!value.includes("..") &&
/^[A-Za-z0-9](?:[A-Za-z0-9/-]*[A-Za-z0-9])?$/.test(value);
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
ApiProxy.get(async (req, res) => { ApiProxy.get(async (req, res) => {
const containerName = req.query.container; const containerName = req.query.container;
const tempCaseRef = req.query.tempcaseref; const tempCaseRef = req.query.tempcaseref;
@@ -24,12 +48,9 @@ ApiProxy.get(async (req, res) => {
const checkHash = req.query.hash; const checkHash = req.query.hash;
if ( if (
typeof containerName === "undefined" || !hasValue(containerName) ||
containerName.length === 0 || !hasValue(tempCaseRef) ||
typeof tempCaseRef === "undefined" || !hasValue(checkHash)
tempCaseRef.length === 0 ||
typeof checkHash === "undefined" ||
checkHash.length === 0
) { ) {
return respondError(res, { return respondError(res, {
status: 400, status: 400,
@@ -38,6 +59,23 @@ ApiProxy.get(async (req, res) => {
}); });
} }
if (!isValidContainer(containerName) || !isValidTempCaseRef(tempCaseRef)) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
const session = await getServerSession(req, res, authOptions(req, res));
if (
typeof session?.user?.id !== "string" ||
session.user.id.length === 0 ||
session.user.id !== containerName
) {
return forbidden(res);
}
const hashCandidatePaths = [ const hashCandidatePaths = [
"/api/file/createappealcompletemessage_api?container=" + "/api/file/createappealcompletemessage_api?container=" +
containerName + containerName +
@@ -117,13 +155,9 @@ ApiProxy.get(async (req, res) => {
if (typeofinvolvement != 846040000) { if (typeofinvolvement != 846040000) {
void (async () => { void (async () => {
try { try {
await updateAccount( await updateCrmContact(contactId[1], {
contactId[1],
{
pinswg_typeofinvolvement: 846040001 pinswg_typeofinvolvement: 846040001
}, });
true
);
} catch (error) { } catch (error) {
consoleLogger(error); consoleLogger(error);
} }
@@ -4,6 +4,8 @@ import { azureHeaders } from "../../../actions/core/headers";
import { consoleLogger } from "../../../actions/core/logger"; import { consoleLogger } from "../../../actions/core/logger";
import axios from "axios"; import axios from "axios";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import nextConnect from "next-connect"; import nextConnect from "next-connect";
import middleware from "../middleware/middleware"; import middleware from "../middleware/middleware";
@@ -16,6 +18,25 @@ const BASE_URL = process.env.API_ROOT || `http://localhost:${port}`;
const hasValue = (value) => const hasValue = (value) =>
typeof value === "string" && value.trim().length > 0; typeof value === "string" && value.trim().length > 0;
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
const isValidTempCaseRef = (value) =>
typeof value === "string" &&
value.length <= 100 &&
!value.includes("..") &&
/^[A-Za-z0-9](?:[A-Za-z0-9/-]*[A-Za-z0-9])?$/.test(value);
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
ApiProxy.get(async (req, res) => { ApiProxy.get(async (req, res) => {
const containerName = req.query.container; const containerName = req.query.container;
const tempCaseRef = req.query.tempcaseref; const tempCaseRef = req.query.tempcaseref;
@@ -28,6 +49,26 @@ ApiProxy.get(async (req, res) => {
}); });
} }
if (
!isValidContainer(containerName) ||
!isValidTempCaseRef(tempCaseRef)
) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
const session = await getServerSession(req, res, authOptions(req, res));
if (
typeof session?.user?.id !== "string" ||
session.user.id.length === 0 ||
session.user.id !== containerName
) {
return forbidden(res);
}
const token = await getToken(); const token = await getToken();
const queryUrl = const queryUrl =
@@ -37,9 +78,17 @@ ApiProxy.get(async (req, res) => {
encodeURIComponent(tempCaseRef); encodeURIComponent(tempCaseRef);
try { try {
const requestOptions = azureHeaders(token.access_token);
if (typeof req.headers?.cookie === "string") {
requestOptions.headers = {
...requestOptions.headers,
cookie: req.headers.cookie
};
}
const { data } = await axios.get( const { data } = await axios.get(
BASE_URL + queryUrl + hashAPIPath(queryUrl), BASE_URL + queryUrl + hashAPIPath(queryUrl),
azureHeaders(token.access_token) requestOptions
); );
return respondSuccess(res, data); return respondSuccess(res, data);
} catch (error) { } catch (error) {
+80 -11
View File
@@ -9,30 +9,59 @@ import { getTempCaseRef } from "../../../components/utils";
import { v4 as uuidv4 } from "uuid"; import { v4 as uuidv4 } from "uuid";
import { hashAPIPath } from "../../../actions/core/hash"; import { hashAPIPath } from "../../../actions/core/hash";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
const WEBAPI_URL = const WEBAPI_URL =
process.env.RELAY_ROOT || process.env.RELAY_ROOT ||
"https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/"; "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/";
const hasValue = (value) =>
typeof value === "string" && value.trim().length > 0;
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
const isValidDraftFolder = (value) =>
typeof value === "string" &&
value.length <= 100 &&
!value.includes("..") &&
/^[A-Za-z0-9](?:[A-Za-z0-9/-]*[A-Za-z0-9])?$/.test(value);
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
export default async function ApiProxy(req, res) { export default async function ApiProxy(req, res) {
var createCaseBody = req.body; let createCaseBody;
try {
createCaseBody =
typeof req.body === "string" ? JSON.parse(req.body) : req.body;
} catch (_error) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
var contactid = req.query.contactid; var contactid = req.query.contactid;
var appealTypeId = req.query.appealTypeId; var appealTypeId = req.query.appealTypeId;
var containerName = req.query.containername; var containerName = req.query.containername;
var lpaID = req.query.lpaID; var lpaID = req.query.lpaID;
var queryUrl = "incidents"; var queryUrl = "incidents";
var token = await getToken();
var tempCaseRef = getTempCaseRef();
if ( if (
typeof contactid === "undefined" || !hasValue(contactid) ||
contactid.length === 0 || !hasValue(appealTypeId) ||
typeof appealTypeId === "undefined" || !hasValue(containerName) ||
appealTypeId.length === 0 || !hasValue(lpaID)
typeof containerName === "undefined" ||
containerName.length === 0 ||
typeof lpaID === "undefined" ||
lpaID.length === 0
) { ) {
return respondError(res, { return respondError(res, {
status: 400, status: 400,
@@ -42,6 +71,46 @@ export default async function ApiProxy(req, res) {
}); });
} }
if (
!createCaseBody ||
typeof createCaseBody !== "object" ||
Array.isArray(createCaseBody) ||
!isValidContainer(containerName) ||
["container", "containerID", "containername"].some(
(key) => Object.prototype.hasOwnProperty.call(createCaseBody, key)
) ||
["container", "containerID"].some((key) =>
Object.prototype.hasOwnProperty.call(req.query, key)
)
) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
const session = await getServerSession(req, res, authOptions(req, res));
if (
typeof session?.user?.id !== "string" ||
session.user.id.length === 0 ||
session.user.id !== containerName
) {
return forbidden(res);
}
var tempCaseRef = getTempCaseRef();
if (!isValidDraftFolder(tempCaseRef)) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
var token = await getToken();
var data = { var data = {
"title": tempCaseRef, "title": tempCaseRef,
"ticketnumber": tempCaseRef, "ticketnumber": tempCaseRef,
+60 -16
View File
@@ -1,18 +1,42 @@
import { import { createRepCompleteMessage } from "../../../actions/azurestorage";
getBlobs,
createRepCompleteMessage
} from "../../../actions/azurestorage";
import { hashAPIPath } from "../../../actions/core/hash"; import { hashAPIPath } from "../../../actions/core/hash";
import { consoleLogger } from "../../../actions/core/logger"; import { consoleLogger } from "../../../actions/core/logger";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
import { getSession } from "next-auth/react";
import nextConnect from "next-connect"; const forbidden = (res) =>
import middleware from "../middleware/middleware"; respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
const ApiProxy = nextConnect(); const isValidContainer = (value) =>
ApiProxy.use(middleware); typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
const isValidPathSegment = (value) =>
typeof value === "string" &&
value.length > 0 &&
value.length <= 255 &&
value === value.trim() &&
value !== "." &&
value !== ".." &&
!/[\\/\u0000-\u001f\u007f]/.test(value);
export default async function handler(req, res) {
res.setHeader("Allow", "GET");
if (req.method !== "GET") {
return respondError(res, {
status: 405,
code: "METHOD_NOT_ALLOWED",
message: "Method not allowed"
});
}
ApiProxy.get(async (req, res) => {
const containerName = req.query.container; const containerName = req.query.container;
const tempCaseRef = req.query.tempcaseref; const tempCaseRef = req.query.tempcaseref;
const filename = req.query.repid; const filename = req.query.repid;
@@ -20,13 +44,13 @@ ApiProxy.get(async (req, res) => {
if ( if (
typeof containerName === "undefined" || typeof containerName === "undefined" ||
containerName.length === 0 || containerName === "" ||
typeof tempCaseRef === "undefined" || typeof tempCaseRef === "undefined" ||
tempCaseRef.length === 0 || tempCaseRef === "" ||
typeof filename === "undefined" || typeof filename === "undefined" ||
filename.length === 0 || filename === "" ||
typeof checkHash === "undefined" || typeof checkHash === "undefined" ||
checkHash.length === 0 checkHash === ""
) { ) {
return respondError(res, { return respondError(res, {
status: 400, status: 400,
@@ -35,6 +59,28 @@ ApiProxy.get(async (req, res) => {
}); });
} }
if (
!isValidContainer(containerName) ||
!isValidPathSegment(tempCaseRef) ||
!isValidPathSegment(filename) ||
typeof checkHash !== "string"
) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
const session = await getSession({ req });
if (
typeof session?.user?.id !== "string" ||
session.user.id.length === 0 ||
session.user.id !== containerName
) {
return forbidden(res);
}
const hashCandidatePaths = [ const hashCandidatePaths = [
"/api/file/createrepcompletemessage_api?container=" + "/api/file/createrepcompletemessage_api?container=" +
containerName + containerName +
@@ -77,12 +123,10 @@ ApiProxy.get(async (req, res) => {
message: "Failed to create representation complete message" message: "Failed to create representation complete message"
}); });
} }
}); }
export const config = { export const config = {
api: { api: {
bodyParser: false bodyParser: false
} }
}; };
export default ApiProxy;
@@ -1,6 +1,8 @@
import { hashAPIPath } from "../../../actions/core/hash"; import { hashAPIPath } from "../../../actions/core/hash";
import { deleteBlob } from "../../../actions/azurestorage"; import { deleteBlob } from "../../../actions/azurestorage";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import nextConnect from "next-connect"; import nextConnect from "next-connect";
import middleware from "../middleware/middleware"; import middleware from "../middleware/middleware";
@@ -8,6 +10,22 @@ import middleware from "../middleware/middleware";
const ApiProxy = nextConnect(); const ApiProxy = nextConnect();
ApiProxy.use(middleware); ApiProxy.use(middleware);
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
const hasValue = (value) =>
typeof value === "string" && value.trim().length > 0;
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
ApiProxy.get(async (req, res) => { ApiProxy.get(async (req, res) => {
const containerName = req.query.container; const containerName = req.query.container;
const casefolderID = req.query.casefolderID; const casefolderID = req.query.casefolderID;
@@ -15,14 +33,10 @@ ApiProxy.get(async (req, res) => {
const checkHash = req.query.hash; const checkHash = req.query.hash;
if ( if (
typeof containerName === "undefined" || !hasValue(containerName) ||
containerName.length === 0 || !hasValue(casefolderID) ||
typeof casefolderID === "undefined" || !hasValue(blobName) ||
casefolderID.length === 0 || !hasValue(checkHash)
typeof blobName === "undefined" ||
blobName.length === 0 ||
typeof checkHash === "undefined" ||
checkHash.length === 0
) { ) {
return respondError(res, { return respondError(res, {
status: 400, status: 400,
@@ -34,6 +48,23 @@ ApiProxy.get(async (req, res) => {
const casefolderIDTrimmed = casefolderID.trim(); const casefolderIDTrimmed = casefolderID.trim();
const blobNameTrimmed = blobName.trim(); const blobNameTrimmed = blobName.trim();
if (!isValidContainer(containerName)) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
const session = await getServerSession(req, res, authOptions(req, res));
if (
typeof session?.user?.id !== "string" ||
session.user.id.length === 0 ||
session.user.id !== containerName
) {
return forbidden(res);
}
const hashCandidatePaths = [ const hashCandidatePaths = [
"/api/file/deleteawaitingsubmissionfromblob?container=" + "/api/file/deleteawaitingsubmissionfromblob?container=" +
containerName + containerName +
+39 -8
View File
@@ -1,6 +1,8 @@
import { hashAPIPath } from "../../../actions/core/hash"; import { hashAPIPath } from "../../../actions/core/hash";
import { deleteBlob } from "../../../actions/azurestorage"; import { deleteBlob } from "../../../actions/azurestorage";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import nextConnect from "next-connect"; import nextConnect from "next-connect";
import middleware from "../middleware/middleware"; import middleware from "../middleware/middleware";
@@ -8,6 +10,22 @@ import middleware from "../middleware/middleware";
const ApiProxy = nextConnect(); const ApiProxy = nextConnect();
ApiProxy.use(middleware); ApiProxy.use(middleware);
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
const hasValue = (value) =>
typeof value === "string" && value.trim().length > 0;
const isValidContainer = (value) =>
typeof value === "string" &&
value.length >= 3 &&
value.length <= 63 &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);
ApiProxy.get(async (req, res) => { ApiProxy.get(async (req, res) => {
const containerName = req.query.container; const containerName = req.query.container;
const casefolderID = req.query.casefolderID; const casefolderID = req.query.casefolderID;
@@ -15,14 +33,10 @@ ApiProxy.get(async (req, res) => {
const checkHash = req.query.hash; const checkHash = req.query.hash;
if ( if (
typeof containerName === "undefined" || !hasValue(containerName) ||
containerName.length === 0 || !hasValue(casefolderID) ||
typeof casefolderID === "undefined" || !hasValue(blobName) ||
casefolderID.length === 0 || !hasValue(checkHash)
typeof blobName === "undefined" ||
blobName.length === 0 ||
typeof checkHash === "undefined" ||
checkHash.length === 0
) { ) {
return respondError(res, { return respondError(res, {
status: 400, status: 400,
@@ -34,6 +48,23 @@ ApiProxy.get(async (req, res) => {
const casefolderIDTrimmed = casefolderID.trim(); const casefolderIDTrimmed = casefolderID.trim();
const blobNameTrimmed = blobName.trim(); const blobNameTrimmed = blobName.trim();
if (!isValidContainer(containerName)) {
return respondError(res, {
status: 400,
code: "INVALID_REQUEST",
message: "Invalid request"
});
}
const session = await getServerSession(req, res, authOptions(req, res));
if (
typeof session?.user?.id !== "string" ||
session.user.id.length === 0 ||
session.user.id !== containerName
) {
return forbidden(res);
}
const hashCandidatePaths = [ const hashCandidatePaths = [
"/api/file/deleteblob?container=" + "/api/file/deleteblob?container=" +
containerName + containerName +
+18
View File
@@ -1,6 +1,8 @@
import { hashAPIPath } from "../../../actions/core/hash"; import { hashAPIPath } from "../../../actions/core/hash";
import { deleteBlobCase } from "../../../actions/azurestorage"; import { deleteBlobCase } from "../../../actions/azurestorage";
import { respondError, respondSuccess } from "../middleware/apiResponse"; import { respondError, respondSuccess } from "../middleware/apiResponse";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import nextConnect from "next-connect"; import nextConnect from "next-connect";
import middleware from "../middleware/middleware"; import middleware from "../middleware/middleware";
@@ -8,6 +10,13 @@ import middleware from "../middleware/middleware";
const ApiProxy = nextConnect(); const ApiProxy = nextConnect();
ApiProxy.use(middleware); ApiProxy.use(middleware);
const forbidden = (res) =>
respondError(res, {
status: 403,
code: "FORBIDDEN",
message: "Request not permitted"
});
ApiProxy.get(async (req, res) => { ApiProxy.get(async (req, res) => {
const containerName = req.query.container; const containerName = req.query.container;
const casefolderID = req.query.casefolderID; const casefolderID = req.query.casefolderID;
@@ -30,6 +39,15 @@ ApiProxy.get(async (req, res) => {
const casefolderIDTrimmed = casefolderID.trim(); const casefolderIDTrimmed = casefolderID.trim();
const session = await getServerSession(req, res, authOptions(req, res));
if (
typeof session?.user?.id !== "string" ||
session.user.id.length === 0 ||
session.user.id !== containerName
) {
return forbidden(res);
}
const hashCandidatePaths = [ const hashCandidatePaths = [
"/api/file/deleteblobcase?container=" + "/api/file/deleteblobcase?container=" +
containerName + containerName +

Some files were not shown because too many files have changed in this diff Show More