@gov-cy/govcy-express-services 1.0.0-alpha.2 → 1.0.0-alpha.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1051 -83
- package/package.json +10 -3
- package/src/auth/cyLoginAuth.mjs +2 -1
- package/src/index.mjs +20 -1
- package/src/middleware/cyLoginAuth.mjs +11 -1
- package/src/middleware/govcyCsrf.mjs +15 -1
- package/src/middleware/govcyFileDeleteHandler.mjs +320 -0
- package/src/middleware/govcyFileUpload.mjs +36 -0
- package/src/middleware/govcyFileViewHandler.mjs +161 -0
- package/src/middleware/govcyFormsPostHandler.mjs +1 -1
- package/src/middleware/govcyHttpErrorHandler.mjs +4 -3
- package/src/middleware/govcyPDFRender.mjs +3 -1
- package/src/middleware/govcyPageHandler.mjs +3 -3
- package/src/middleware/govcyPageRender.mjs +10 -0
- package/src/middleware/govcyReviewPageHandler.mjs +4 -1
- package/src/middleware/govcyReviewPostHandler.mjs +1 -1
- package/src/middleware/govcySuccessPageHandler.mjs +2 -3
- package/src/public/js/govcyFiles.js +299 -0
- package/src/public/js/govcyForms.js +19 -8
- package/src/resources/govcyResources.mjs +85 -4
- package/src/utils/govcyApiDetection.mjs +17 -0
- package/src/utils/govcyApiRequest.mjs +30 -5
- package/src/utils/govcyApiResponse.mjs +31 -0
- package/src/utils/govcyConstants.mjs +5 -1
- package/src/utils/govcyDataLayer.mjs +211 -11
- package/src/utils/govcyExpressions.mjs +1 -1
- package/src/utils/govcyFormHandling.mjs +81 -5
- package/src/utils/govcyHandleFiles.mjs +307 -0
- package/src/utils/govcyLoadSubmissionDataAPIs.mjs +10 -3
- package/src/utils/govcySubmitData.mjs +186 -106
- package/src/utils/govcyTempSave.mjs +2 -1
- package/src/utils/govcyValidator.mjs +7 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gov-cy/govcy-express-services",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.20",
|
|
4
4
|
"description": "An Express-based system that dynamically renders services using @gov-cy/govcy-frontend-renderer and posts data to a submission API.",
|
|
5
5
|
"author": "DMRID - DSF Team",
|
|
6
6
|
"license": "MIT",
|
|
@@ -44,22 +44,29 @@
|
|
|
44
44
|
"test:integration": "mocha --recursive tests/integration/**/*.test.mjs",
|
|
45
45
|
"test:package": "mocha --recursive tests/package/**/*.test.mjs",
|
|
46
46
|
"test:functional": "mocha --timeout 30000 --recursive tests/functional/**/*.test.mjs",
|
|
47
|
-
"test:watch": "mocha --watch --timeout 60000 tests/**/*.test.mjs"
|
|
47
|
+
"test:watch": "mocha --watch --timeout 60000 tests/**/*.test.mjs",
|
|
48
|
+
"coverage": "c8 --reporter=html --reporter=text --reporter=lcov --reporter=json-summary npm test",
|
|
49
|
+
"coverage:report": "c8 report",
|
|
50
|
+
"coverage:badge": "coverage-badges --output ./coverage-badges.svg"
|
|
48
51
|
},
|
|
49
52
|
"dependencies": {
|
|
50
53
|
"@gov-cy/dsf-email-templates": "^2.1.0",
|
|
51
|
-
"@gov-cy/govcy-frontend-renderer": "^1.
|
|
54
|
+
"@gov-cy/govcy-frontend-renderer": "^1.24.0",
|
|
52
55
|
"axios": "^1.9.0",
|
|
53
56
|
"cookie-parser": "^1.4.7",
|
|
54
57
|
"dotenv": "^16.3.1",
|
|
55
58
|
"express": "^4.18.2",
|
|
56
59
|
"express-session": "^1.17.3",
|
|
60
|
+
"form-data": "^4.0.4",
|
|
61
|
+
"multer": "^2.0.2",
|
|
57
62
|
"openid-client": "^6.3.4",
|
|
58
63
|
"puppeteer": "^24.6.0"
|
|
59
64
|
},
|
|
60
65
|
"devDependencies": {
|
|
66
|
+
"c8": "^10.1.3",
|
|
61
67
|
"chai": "^5.2.0",
|
|
62
68
|
"chai-http": "^5.1.1",
|
|
69
|
+
"coverage-badges-cli": "^2.2.0",
|
|
63
70
|
"mocha": "^11.1.0",
|
|
64
71
|
"mochawesome": "^7.1.3",
|
|
65
72
|
"nodemon": "^3.0.2",
|
package/src/auth/cyLoginAuth.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import * as client from 'openid-client';
|
|
|
2
2
|
import { getEnvVariable } from '../utils/govcyEnvVariables.mjs';
|
|
3
3
|
import { logger } from "../utils/govcyLogger.mjs";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
/* c8 ignore start */
|
|
6
6
|
// OpenID Configuration
|
|
7
7
|
const issuerUrl = getEnvVariable('CYLOGIN_ISSUER_URL');
|
|
8
8
|
const clientId = getEnvVariable('CYLOGIN_CLIENT_ID');
|
|
@@ -131,3 +131,4 @@ export function getLogoutUrl(id_token_hint = '') {
|
|
|
131
131
|
|
|
132
132
|
// Export config if needed elsewhere
|
|
133
133
|
export { config };
|
|
134
|
+
/* c8 ignore end */
|
package/src/index.mjs
CHANGED
|
@@ -24,6 +24,9 @@ import { govcyManifestHandler } from './middleware/govcyManifestHandler.mjs';
|
|
|
24
24
|
import { govcyRoutePageHandler } from './middleware/govcyRoutePageHandler.mjs';
|
|
25
25
|
import { govcyServiceEligibilityHandler } from './middleware/govcyServiceEligibilityHandler.mjs';
|
|
26
26
|
import { govcyLoadSubmissionData } from './middleware/govcyLoadSubmissionData.mjs';
|
|
27
|
+
import { govcyFileUpload } from './middleware/govcyFileUpload.mjs';
|
|
28
|
+
import { govcyFileDeletePageHandler, govcyFileDeletePostHandler } from './middleware/govcyFileDeleteHandler.mjs';
|
|
29
|
+
import { govcyFileViewHandler } from './middleware/govcyFileViewHandler.mjs';
|
|
27
30
|
import { isProdOrStaging , getEnvVariable, whatsIsMyEnvironment } from './utils/govcyEnvVariables.mjs';
|
|
28
31
|
import { logger } from "./utils/govcyLogger.mjs";
|
|
29
32
|
|
|
@@ -128,6 +131,14 @@ export default function initializeGovCyExpressService(){
|
|
|
128
131
|
|
|
129
132
|
// 📝 -- ROUTE: Serve manifest.json dynamically for each site
|
|
130
133
|
app.get('/:siteId/manifest.json', serviceConfigDataMiddleware, govcyManifestHandler());
|
|
134
|
+
|
|
135
|
+
// 🗃️ -- ROUTE: Handle POST requests for file uploads for a page.
|
|
136
|
+
app.post('/apis/:siteId/:pageUrl/upload',
|
|
137
|
+
serviceConfigDataMiddleware,
|
|
138
|
+
requireAuth, // UNCOMMENT
|
|
139
|
+
naturalPersonPolicy, // UNCOMMENT
|
|
140
|
+
govcyServiceEligibilityHandler(true), // UNCOMMENT
|
|
141
|
+
govcyFileUpload);
|
|
131
142
|
|
|
132
143
|
// 🏠 -- ROUTE: Handle route with only siteId (/:siteId or /:siteId/)
|
|
133
144
|
app.get('/:siteId', serviceConfigDataMiddleware, requireAuth, naturalPersonPolicy, govcyServiceEligibilityHandler(true),govcyLoadSubmissionData(),govcyPageHandler(), renderGovcyPage());
|
|
@@ -141,16 +152,24 @@ export default function initializeGovCyExpressService(){
|
|
|
141
152
|
// ✅ -- ROUTE: Add Success Page Route (BEFORE the dynamic route)
|
|
142
153
|
app.get('/:siteId/success',serviceConfigDataMiddleware, requireAuth, naturalPersonPolicy, govcyServiceEligibilityHandler(), govcySuccessPageHandler(), renderGovcyPage());
|
|
143
154
|
|
|
155
|
+
// 👀🗃️ -- ROUTE: View file (BEFORE the dynamic route)
|
|
156
|
+
app.get('/:siteId/:pageUrl/view-file/:elementName', serviceConfigDataMiddleware, requireAuth, naturalPersonPolicy, govcyServiceEligibilityHandler(), govcyLoadSubmissionData(), govcyFileViewHandler());
|
|
157
|
+
|
|
158
|
+
// ❌🗃️ -- ROUTE: Delete file (BEFORE the dynamic route)
|
|
159
|
+
app.get('/:siteId/:pageUrl/delete-file/:elementName', serviceConfigDataMiddleware, requireAuth, naturalPersonPolicy, govcyServiceEligibilityHandler(), govcyLoadSubmissionData(), govcyFileDeletePageHandler(), renderGovcyPage());
|
|
160
|
+
|
|
144
161
|
// 📝 -- ROUTE: Dynamic route to render pages based on siteId and pageUrl, using govcyPageHandler middleware
|
|
145
162
|
app.get('/:siteId/:pageUrl', serviceConfigDataMiddleware, requireAuth, naturalPersonPolicy, govcyServiceEligibilityHandler(true), govcyLoadSubmissionData(), govcyPageHandler(), renderGovcyPage());
|
|
146
163
|
|
|
164
|
+
// ❌🗃️📥 -- ROUTE: Handle POST requests for delete file
|
|
165
|
+
app.post('/:siteId/:pageUrl/delete-file/:elementName', serviceConfigDataMiddleware, requireAuth, naturalPersonPolicy, govcyServiceEligibilityHandler(true), govcyFileDeletePostHandler());
|
|
166
|
+
|
|
147
167
|
// 📥 -- ROUTE: Handle POST requests for review page. The `submit` action
|
|
148
168
|
app.post('/:siteId/review', serviceConfigDataMiddleware, requireAuth, naturalPersonPolicy, govcyServiceEligibilityHandler(), govcyReviewPostHandler());
|
|
149
169
|
|
|
150
170
|
// 👀📥 -- ROUTE: Handle POST requests (Form Submissions) based on siteId and pageUrl, using govcyFormsPostHandler middleware
|
|
151
171
|
app.post('/:siteId/:pageUrl', serviceConfigDataMiddleware, requireAuth, naturalPersonPolicy, govcyServiceEligibilityHandler(true), govcyFormsPostHandler());
|
|
152
172
|
|
|
153
|
-
|
|
154
173
|
// post for /:siteId/review
|
|
155
174
|
|
|
156
175
|
// 🔹 Catch 404 errors (must be after all routes)
|
|
@@ -7,7 +7,10 @@
|
|
|
7
7
|
import { getLoginUrl, handleCallback, getLogoutUrl } from '../auth/cyLoginAuth.mjs';
|
|
8
8
|
import { logger } from "../utils/govcyLogger.mjs";
|
|
9
9
|
import { handleMiddlewareError } from "../utils/govcyUtils.mjs";
|
|
10
|
+
import { errorResponse } from "../utils/govcyApiResponse.mjs";
|
|
11
|
+
import { isApiRequest } from '../utils/govcyApiDetection.mjs';
|
|
10
12
|
|
|
13
|
+
/* c8 ignore start */
|
|
11
14
|
/**
|
|
12
15
|
* Middleware to check if the user is authenticated. If not, redirect to the login page.
|
|
13
16
|
*
|
|
@@ -17,6 +20,12 @@ import { handleMiddlewareError } from "../utils/govcyUtils.mjs";
|
|
|
17
20
|
*/
|
|
18
21
|
export function requireAuth(req, res, next) {
|
|
19
22
|
if (!req.session.user) {
|
|
23
|
+
if (isApiRequest(req)) {
|
|
24
|
+
const err = new Error("Unauthorized: user not authenticated");
|
|
25
|
+
err.status = 401;
|
|
26
|
+
return next(err);
|
|
27
|
+
}
|
|
28
|
+
|
|
20
29
|
// Store the original URL before redirecting to login
|
|
21
30
|
req.session.redirectAfterLogin = req.originalUrl;
|
|
22
31
|
return res.redirect('/login');
|
|
@@ -128,4 +137,5 @@ export function handleLogout() {
|
|
|
128
137
|
res.redirect(logoutUrl);
|
|
129
138
|
});
|
|
130
139
|
};
|
|
131
|
-
}
|
|
140
|
+
}
|
|
141
|
+
/* c8 ignore end */
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
|
|
2
2
|
import { handleMiddlewareError } from "../utils/govcyUtils.mjs";
|
|
3
|
+
import { errorResponse } from '../utils/govcyApiResponse.mjs';
|
|
4
|
+
import { isApiRequest } from '../utils/govcyApiDetection.mjs';
|
|
5
|
+
|
|
3
6
|
/**
|
|
4
7
|
* Middleware to handle CSRF token generation and validation.
|
|
5
8
|
*
|
|
@@ -14,7 +17,18 @@ export function govcyCsrfMiddleware(req, res, next) {
|
|
|
14
17
|
}
|
|
15
18
|
|
|
16
19
|
req.csrfToken = () => req.session.csrfToken;
|
|
17
|
-
|
|
20
|
+
|
|
21
|
+
if (
|
|
22
|
+
req.method === 'POST' &&
|
|
23
|
+
req.headers['content-type']?.includes('multipart/form-data') &&
|
|
24
|
+
isApiRequest(req)) {
|
|
25
|
+
const tokenFromHeader = req.get('X-CSRF-Token');
|
|
26
|
+
// UNCOMMENT
|
|
27
|
+
if (!tokenFromHeader || tokenFromHeader !== req.session.csrfToken) {
|
|
28
|
+
return res.status(400).json(errorResponse(403, 'Invalid CSRF token'));
|
|
29
|
+
}
|
|
30
|
+
return next();
|
|
31
|
+
}
|
|
18
32
|
// Check token on POST requests
|
|
19
33
|
if (req.method === 'POST') {
|
|
20
34
|
const tokenFromBody = req.body._csrf;
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import * as govcyResources from "../resources/govcyResources.mjs";
|
|
2
|
+
import * as dataLayer from "../utils/govcyDataLayer.mjs";
|
|
3
|
+
import { logger } from "../utils/govcyLogger.mjs";
|
|
4
|
+
import { pageContainsFileInput } from "../utils/govcyHandleFiles.mjs";
|
|
5
|
+
import { whatsIsMyEnvironment, getEnvVariable, getEnvVariableBool } from '../utils/govcyEnvVariables.mjs';
|
|
6
|
+
import { handleMiddlewareError } from "../utils/govcyUtils.mjs";
|
|
7
|
+
import { getPageConfigData } from "../utils/govcyLoadConfigData.mjs";
|
|
8
|
+
import { evaluatePageConditions } from "../utils/govcyExpressions.mjs";
|
|
9
|
+
import { govcyApiRequest } from "../utils/govcyApiRequest.mjs";
|
|
10
|
+
import { URL } from "url";
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Middleware to handle the delete file page.
|
|
15
|
+
* This middleware processes the delete file page, populates the question, and shows validation errors.
|
|
16
|
+
*/
|
|
17
|
+
export function govcyFileDeletePageHandler() {
|
|
18
|
+
return (req, res, next) => {
|
|
19
|
+
try {
|
|
20
|
+
const { siteId, pageUrl, elementName } = req.params;
|
|
21
|
+
|
|
22
|
+
// Create a deep copy of the service to avoid modifying the original
|
|
23
|
+
let serviceCopy = req.serviceData;
|
|
24
|
+
|
|
25
|
+
// ⤵️ Find the current page based on the URL
|
|
26
|
+
const page = getPageConfigData(serviceCopy, pageUrl);
|
|
27
|
+
|
|
28
|
+
// deep copy the page template to avoid modifying the original
|
|
29
|
+
const pageTemplateCopy = JSON.parse(JSON.stringify(page.pageTemplate));
|
|
30
|
+
|
|
31
|
+
// ----- Conditional logic comes here
|
|
32
|
+
// ✅ Skip this POST handler if the page's conditions evaluate to true (redirect away)
|
|
33
|
+
const conditionResult = evaluatePageConditions(page, req.session, siteId, req);
|
|
34
|
+
if (conditionResult.result === false) {
|
|
35
|
+
logger.debug("⛔️ Page condition evaluated to true on POST — skipping form save and redirecting:", conditionResult);
|
|
36
|
+
return res.redirect(govcyResources.constructPageUrl(siteId, conditionResult.redirect));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Validate the field: Only allow delete if the page contains a fileInput with the given name
|
|
40
|
+
const fileInputElement = pageContainsFileInput(pageTemplateCopy, elementName);
|
|
41
|
+
if (!fileInputElement) {
|
|
42
|
+
return handleMiddlewareError(`File input [${elementName}] not allowed on this page`, 404, next);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Validate if the file input has a label
|
|
46
|
+
if (!fileInputElement?.params?.label) {
|
|
47
|
+
return handleMiddlewareError(`File input [${elementName}] does not have a label`, 404, next);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
//get element data
|
|
51
|
+
const elementData = dataLayer.getFormDataValue(req.session, siteId, pageUrl, elementName)
|
|
52
|
+
|
|
53
|
+
// If the element data is not found, return an error response
|
|
54
|
+
if (!elementData || !elementData?.sha256 || !elementData?.fileId) {
|
|
55
|
+
return handleMiddlewareError(`File input [${elementName}] data not found on this page`, 404, next);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Deep copy page title (so we don’t mutate template)
|
|
59
|
+
const pageTitle = JSON.parse(JSON.stringify(govcyResources.staticResources.text.deleteFileTitle));
|
|
60
|
+
|
|
61
|
+
// Replace label placeholders on page title
|
|
62
|
+
for (const lang of Object.keys(pageTitle)) {
|
|
63
|
+
const labelForLang = fileInputElement.params.label[lang] || fileInputElement.params.label.el || "";
|
|
64
|
+
pageTitle[lang] = pageTitle[lang].replace("{{file}}", labelForLang);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
// Deep copy renderer pageData from
|
|
69
|
+
let pageData = JSON.parse(JSON.stringify(govcyResources.staticResources.rendererPageData));
|
|
70
|
+
|
|
71
|
+
// Handle isTesting
|
|
72
|
+
pageData.site.isTesting = (whatsIsMyEnvironment() === "staging");
|
|
73
|
+
|
|
74
|
+
// Base page template structure
|
|
75
|
+
let pageTemplate = {
|
|
76
|
+
sections: [
|
|
77
|
+
{
|
|
78
|
+
name: "beforeMain",
|
|
79
|
+
elements: [govcyResources.staticResources.elements.backLink]
|
|
80
|
+
}
|
|
81
|
+
]
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
//contruct the warning if the file was uploaded more than once
|
|
85
|
+
const warningSameFile = {
|
|
86
|
+
element: "warning",
|
|
87
|
+
params: {
|
|
88
|
+
text: govcyResources.staticResources.text.deleteSameFileWarning,
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const showSameFileWarning = dataLayer.isFileUsedInSiteInputDataAgain(
|
|
93
|
+
req.session,
|
|
94
|
+
siteId,
|
|
95
|
+
elementData
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
// Construct page title
|
|
99
|
+
const pageRadios = {
|
|
100
|
+
element: "radios",
|
|
101
|
+
params: {
|
|
102
|
+
id: "deleteFile",
|
|
103
|
+
name: "deleteFile",
|
|
104
|
+
legend: pageTitle,
|
|
105
|
+
isPageHeading: true,
|
|
106
|
+
classes: "govcy-mb-6",// only include the warning block when the file is referenced >1 times
|
|
107
|
+
elements: showSameFileWarning ? [warningSameFile] : [],
|
|
108
|
+
items: [
|
|
109
|
+
{
|
|
110
|
+
value: "yes",
|
|
111
|
+
text: govcyResources.staticResources.text.deleteYesOption
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
value: "no",
|
|
115
|
+
text: govcyResources.staticResources.text.deleteNoOption
|
|
116
|
+
}
|
|
117
|
+
]
|
|
118
|
+
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
//-------------
|
|
122
|
+
|
|
123
|
+
// Construct submit button
|
|
124
|
+
const formElement = {
|
|
125
|
+
element: "form",
|
|
126
|
+
params: {
|
|
127
|
+
action: govcyResources.constructPageUrl(siteId, `${pageUrl}/delete-file/${elementName}`, (req.query.route === "review" ? "review" : "")),
|
|
128
|
+
method: "POST",
|
|
129
|
+
elements: [
|
|
130
|
+
pageRadios,
|
|
131
|
+
{
|
|
132
|
+
element: "button",
|
|
133
|
+
params: {
|
|
134
|
+
type: "submit",
|
|
135
|
+
text: govcyResources.staticResources.text.continue
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
govcyResources.csrfTokenInput(req.csrfToken())
|
|
139
|
+
]
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// --------- Handle Validation Errors ---------
|
|
144
|
+
// Check if validation errors exist in the request
|
|
145
|
+
const validationErrors = [];
|
|
146
|
+
let mainElements = [];
|
|
147
|
+
if (req?.query?.hasError) {
|
|
148
|
+
validationErrors.push({
|
|
149
|
+
link: '#deleteFile-option-1',
|
|
150
|
+
text: govcyResources.staticResources.text.deleteFileValidationError
|
|
151
|
+
});
|
|
152
|
+
mainElements.push(govcyResources.errorSummary(validationErrors));
|
|
153
|
+
formElement.params.elements[0].params.error = govcyResources.staticResources.text.deleteFileValidationError;
|
|
154
|
+
}
|
|
155
|
+
//--------- End Handle Validation Errors ---------
|
|
156
|
+
|
|
157
|
+
// Add elements to the main section, the H1, summary list, the submit button and the JS
|
|
158
|
+
mainElements.push(formElement);
|
|
159
|
+
// Append generated summary list to the page template
|
|
160
|
+
pageTemplate.sections.push({ name: "main", elements: mainElements });
|
|
161
|
+
|
|
162
|
+
//if user is logged in add he user bane section in the page template
|
|
163
|
+
if (dataLayer.getUser(req.session)) {
|
|
164
|
+
pageTemplate.sections.push(govcyResources.userNameSection(dataLayer.getUser(req.session).name)); // Add user name section
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
//prepare pageData
|
|
168
|
+
pageData.site = serviceCopy.site;
|
|
169
|
+
pageData.pageData.title = pageTitle;
|
|
170
|
+
|
|
171
|
+
// Attach processed page data to the request
|
|
172
|
+
req.processedPage = {
|
|
173
|
+
pageData: pageData,
|
|
174
|
+
pageTemplate: pageTemplate
|
|
175
|
+
};
|
|
176
|
+
logger.debug("Processed delete file page data:", req.processedPage);
|
|
177
|
+
next();
|
|
178
|
+
} catch (error) {
|
|
179
|
+
return next(error); // Pass error to govcyHttpErrorHandler
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Middleware to handle delete file post form processing
|
|
187
|
+
* This middleware processes the post, validates the form and handles the file data layer
|
|
188
|
+
*/
|
|
189
|
+
export function govcyFileDeletePostHandler() {
|
|
190
|
+
return async (req, res, next) => {
|
|
191
|
+
try {
|
|
192
|
+
// Extract siteId and pageUrl from request
|
|
193
|
+
let { siteId, pageUrl, elementName } = req.params;
|
|
194
|
+
|
|
195
|
+
// get service data
|
|
196
|
+
let serviceCopy = req.serviceData;
|
|
197
|
+
|
|
198
|
+
// 🔍 Find the page by pageUrl
|
|
199
|
+
const page = getPageConfigData(serviceCopy, pageUrl);
|
|
200
|
+
|
|
201
|
+
// Deep copy pageTemplate to avoid modifying the original
|
|
202
|
+
const pageTemplateCopy = JSON.parse(JSON.stringify(page.pageTemplate));
|
|
203
|
+
|
|
204
|
+
// ----- Conditional logic comes here
|
|
205
|
+
// Check if the page has conditions and apply logic
|
|
206
|
+
const conditionResult = evaluatePageConditions(page, req.session, siteId, req);
|
|
207
|
+
if (conditionResult.result === false) {
|
|
208
|
+
logger.debug("⛔️ Page condition evaluated to true on POST — skipping form save and redirecting:", conditionResult);
|
|
209
|
+
return res.redirect(govcyResources.constructPageUrl(siteId, conditionResult.redirect));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Validate the field: Only allow delete if the page contains a fileInput with the given name
|
|
213
|
+
const fileInputElement = pageContainsFileInput(pageTemplateCopy, elementName);
|
|
214
|
+
if (!fileInputElement) {
|
|
215
|
+
return handleMiddlewareError(`File input [${elementName}] not allowed on this page`, 404, next);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
//get element data
|
|
219
|
+
const elementData = dataLayer.getFormDataValue(req.session, siteId, pageUrl, elementName)
|
|
220
|
+
|
|
221
|
+
// If the element data is not found, return an error response
|
|
222
|
+
if (!elementData || !elementData?.sha256 || !elementData?.fileId) {
|
|
223
|
+
return handleMiddlewareError(`File input [${elementName}] data not found on this page`, 404, next);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// the page base return url
|
|
227
|
+
const pageBaseReturnUrl = `http://localhost:3000/${siteId}/${pageUrl}`;
|
|
228
|
+
|
|
229
|
+
//check if input `deleteFile` has a value
|
|
230
|
+
if (!req?.body?.deleteFile ||
|
|
231
|
+
(req.body.deleteFile !== "yes" && req.body.deleteFile !== "no")) {
|
|
232
|
+
logger.debug("⛔️ No deleteFile value provided on POST — skipping form save and redirecting:", req.body);
|
|
233
|
+
//construct the page url with error
|
|
234
|
+
let myUrl = new URL(pageBaseReturnUrl + `/delete-file/${elementName}`);
|
|
235
|
+
//check if the route is review
|
|
236
|
+
if (req.query.route === "review") {
|
|
237
|
+
myUrl.searchParams.set("route", "review");
|
|
238
|
+
}
|
|
239
|
+
//set the error flag
|
|
240
|
+
myUrl.searchParams.set("hasError", "1");
|
|
241
|
+
|
|
242
|
+
//redirect to the same page with error summary (relative path)
|
|
243
|
+
return res.redirect(govcyResources.constructErrorSummaryUrl(myUrl.pathname + myUrl.search));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
//if no validation errors
|
|
247
|
+
if (req.body.deleteFile === "yes") {
|
|
248
|
+
// Try to delete the file via the delete API.
|
|
249
|
+
// If it fails, log the error but continue to remove the file from the session
|
|
250
|
+
try {
|
|
251
|
+
// Get the delete file configuration
|
|
252
|
+
const deleteCfg = serviceCopy?.site?.fileDeleteAPIEndpoint;
|
|
253
|
+
// Check if download file configuration is available
|
|
254
|
+
if (!deleteCfg?.url || !deleteCfg?.clientKey || !deleteCfg?.serviceId) {
|
|
255
|
+
return handleMiddlewareError(`File delete APU configuration not found`, 404, next);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Environment vars
|
|
259
|
+
const allowSelfSignedCerts = getEnvVariableBool("ALLOW_SELF_SIGNED_CERTIFICATES", false);
|
|
260
|
+
let url = getEnvVariable(deleteCfg.url || "", false);
|
|
261
|
+
const clientKey = getEnvVariable(deleteCfg.clientKey || "", false);
|
|
262
|
+
const serviceId = getEnvVariable(deleteCfg.serviceId || "", false);
|
|
263
|
+
const dsfGtwKey = getEnvVariable(deleteCfg?.dsfgtwApiKey || "", "");
|
|
264
|
+
const method = (deleteCfg?.method || "GET").toLowerCase();
|
|
265
|
+
|
|
266
|
+
// Check if the upload API is configured correctly
|
|
267
|
+
if (!url || !clientKey) {
|
|
268
|
+
return handleMiddlewareError(`Missing environment variables for upload`, 404, next);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Construct the URL with tag being the elementName
|
|
272
|
+
url += `/${encodeURIComponent(elementData.fileId)}/${encodeURIComponent(elementData.sha256)}`;
|
|
273
|
+
|
|
274
|
+
// Get the user
|
|
275
|
+
const user = dataLayer.getUser(req.session);
|
|
276
|
+
// Perform the delete request
|
|
277
|
+
const response = await govcyApiRequest(
|
|
278
|
+
method,
|
|
279
|
+
url,
|
|
280
|
+
{},
|
|
281
|
+
true,
|
|
282
|
+
user,
|
|
283
|
+
{
|
|
284
|
+
accept: "text/plain",
|
|
285
|
+
"client-key": clientKey,
|
|
286
|
+
"service-id": serviceId,
|
|
287
|
+
...(dsfGtwKey !== "" && { "dsfgtw-api-key": dsfGtwKey })
|
|
288
|
+
},
|
|
289
|
+
3,
|
|
290
|
+
allowSelfSignedCerts
|
|
291
|
+
);
|
|
292
|
+
|
|
293
|
+
// If not succeeded, handle error
|
|
294
|
+
if (!response?.Succeeded) {
|
|
295
|
+
logger.error("fileDeleteAPIEndpoint returned succeeded false");
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
} catch (error) {
|
|
299
|
+
logger.error(`fileDeleteAPIEndpoint Call failed: ${error.message}`);
|
|
300
|
+
}
|
|
301
|
+
// if succeeded all good
|
|
302
|
+
// dataLayer.storePageDataElement(req.session, siteId, pageUrl, elementName, "");
|
|
303
|
+
dataLayer.removeAllFilesFromSite(req.session, siteId, { fileId: elementData.fileId, sha256: elementData.sha256 });
|
|
304
|
+
logger.info(`File deleted by user`, { siteId, pageUrl, elementName });
|
|
305
|
+
}
|
|
306
|
+
// construct the page url
|
|
307
|
+
let myUrl = new URL(pageBaseReturnUrl);
|
|
308
|
+
//check if the route is review
|
|
309
|
+
if (req.query.route === "review") {
|
|
310
|
+
myUrl.searchParams.set("route", "review");
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// redirect to the page (relative path)
|
|
314
|
+
res.redirect(myUrl.pathname + myUrl.search);
|
|
315
|
+
} catch (error) {
|
|
316
|
+
logger.error("Error in govcyFileDeletePostHandler middleware:", error.message);
|
|
317
|
+
return next(error); // Pass error to govcyHttpErrorHandler
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import multer from 'multer';
|
|
2
|
+
import { logger } from '../utils/govcyLogger.mjs';
|
|
3
|
+
import { successResponse, errorResponse } from '../utils/govcyApiResponse.mjs';
|
|
4
|
+
import { ALLOWED_MULTER_FILE_SIZE_MB } from "../utils/govcyConstants.mjs";
|
|
5
|
+
import { handleFileUpload } from "../utils/govcyHandleFiles.mjs";
|
|
6
|
+
|
|
7
|
+
// Configure multer to store the file in memory (not disk) and limit the size to 10MB
|
|
8
|
+
const upload = multer({
|
|
9
|
+
storage: multer.memoryStorage(),
|
|
10
|
+
limits: { fileSize: ALLOWED_MULTER_FILE_SIZE_MB * 1024 * 1024 } // 10MB
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
export const govcyFileUpload = [
|
|
17
|
+
upload.single('file'), // multer parses the uploaded file and stores it in req.file
|
|
18
|
+
|
|
19
|
+
async function govcyUploadHandler(req, res) {
|
|
20
|
+
const result = await handleFileUpload({
|
|
21
|
+
service: req.serviceData,
|
|
22
|
+
store: req.session,
|
|
23
|
+
siteId: req.params.siteId,
|
|
24
|
+
pageUrl: req.params.pageUrl,
|
|
25
|
+
elementName: req.body?.elementName,
|
|
26
|
+
file: req.file
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
if (result.status !== 200) {
|
|
30
|
+
logger.error("Upload failed", result);
|
|
31
|
+
return res.status(result.status).json(errorResponse(result.dataStatus, result.errorMessage || 'File upload failed'));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return res.json(successResponse(result.data));
|
|
35
|
+
}
|
|
36
|
+
];
|