Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: migrate appendVerifiedSpcpResponses to TypeScript #693

Merged
merged 7 commits into from
Nov 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 0 additions & 37 deletions src/app/controllers/spcp.server.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,40 +49,3 @@ exports.encryptedVerifiedFields = (signingSecretKey) => {
}
}
}

/**
* Append additional verified responses(s) for SP and CP responses so that they show up in email response
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
exports.appendVerifiedSPCPResponses = function (req, res, next) {
const { form } = req
const { uinFin, userInfo } = res.locals
switch (form.authType) {
case 'SP':
req.body.parsedResponses.push({
question: 'SingPass Validated NRIC',
fieldType: 'authenticationSp',
isVisible: true,
answer: uinFin,
})
break
case 'CP':
// Add UEN to responses
req.body.parsedResponses.push({
question: 'CorpPass Validated UEN',
fieldType: 'authenticationCp',
isVisible: true,
answer: uinFin,
})
// Add UID to responses
req.body.parsedResponses.push({
question: 'CorpPass Validated UID',
fieldType: 'authenticationCp',
isVisible: true,
answer: userInfo,
})
break
}
return next()
}
16 changes: 0 additions & 16 deletions src/app/factories/spcp.factory.js

This file was deleted.

3 changes: 1 addition & 2 deletions src/app/modules/form/admin-form/admin-form.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { RequestHandler } from 'express'
import { ParamsDictionary } from 'express-serve-static-core'

import { createLoggerWithLabel } from '../../../../config/logger'
import { AuthType, IPopulatedForm } from '../../../../types'
import { AuthType, WithForm } from '../../../../types'
import { createReqMeta } from '../../../utils/request'
import * as SubmissionService from '../../submission/submission.service'
import * as UserService from '../../user/user.service'
Expand All @@ -18,7 +18,6 @@ import { assertHasReadPermissions, mapRouteError } from './admin-form.utils'

const logger = createLoggerWithLabel(module)

type WithForm<T> = T & { form: IPopulatedForm }
/**
* Handler for GET /adminform endpoint.
* @security session
Expand Down
14 changes: 6 additions & 8 deletions src/app/modules/form/admin-form/admin-form.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import {
MAX_UPLOAD_FILE_SIZE,
VALID_UPLOAD_FILE_TYPES,
} from '../../../../shared/constants'
import { AuthType, DashboardFormView, MyInfoAttribute } from '../../../../types'
import {
AuthType,
DashboardFormView,
MyInfoAttribute,
SpcpLocals,
} from '../../../../types'
import getFormModel from '../../../models/form.server.model'
import { DatabaseError } from '../../core/core.errors'
import { MissingUserError } from '../../user/user.errors'
Expand Down Expand Up @@ -167,13 +172,6 @@ export const createPresignedPostForLogos = (
return createPresignedPost(AwsConfig.logoS3Bucket, uploadParams)
}

type SpcpLocals =
| {
uinFin: string
hashedFields: Set<MyInfoAttribute>
}
| { uinFin: string; userInfo: string }
| { [key: string]: never } // empty object
export const getMockSpcpLocals = (
authType: AuthType,
myInfoAttrs: MyInfoAttribute[],
Expand Down
40 changes: 33 additions & 7 deletions src/app/modules/spcp/spcp.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,22 @@ import { StatusCodes } from 'http-status-codes'

import config from '../../../config/config'
import { createLoggerWithLabel } from '../../../config/logger'
import { AuthType, IPopulatedForm } from '../../../types'
import { AuthType, WithForm } from '../../../types'
import { createReqMeta } from '../../utils/request'
import * as FormService from '../form/form.service'
import { ProcessedFieldResponse } from '../submission/submission.types'

import { SpcpFactory } from './spcp.factory'
import { JwtName, LoginPageValidationResult } from './spcp.types'
import { extractJwt, mapRouteError } from './spcp.util'
import {
createCorppassParsedResponses,
createSingpassParsedResponses,
extractJwt,
mapRouteError,
} from './spcp.util'

const logger = createLoggerWithLabel(module)

// TODO (#42): remove these types when migrating away from middleware pattern
type WithForm<T> = T & {
form: IPopulatedForm
}

/**
* Generates redirect URL to Official SingPass/CorpPass log in page
* @param req - Express request object
Expand Down Expand Up @@ -245,3 +246,28 @@ export const handleLogin: (
return res.redirect(destination)
})
}

/**
* Append additional verified responses(s) for SP and CP responses so that they show up in email response
* @param req - Express request object
* @param res - Express response object
*/
export const appendVerifiedSPCPResponses: RequestHandler<
ParamsDictionary,
unknown,
{ parsedResponses: ProcessedFieldResponse[] }
> = (req, res, next) => {
const { form } = req as WithForm<typeof req>
const { uinFin, userInfo } = res.locals
switch (form.authType) {
case AuthType.SP:
req.body.parsedResponses.push(...createSingpassParsedResponses(uinFin))
break
case AuthType.CP:
req.body.parsedResponses.push(
...createCorppassParsedResponses(uinFin, userInfo),
)
break
}
return next()
}
39 changes: 38 additions & 1 deletion src/app/modules/spcp/spcp.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import crypto from 'crypto'
import { StatusCodes } from 'http-status-codes'

import { createLoggerWithLabel } from '../../../config/logger'
import { AuthType, MapRouteError } from '../../../types'
import { AuthType, BasicField, MapRouteError } from '../../../types'
import { MissingFeatureError } from '../core/core.errors'
import { ProcessedSingleAnswerResponse } from '../submission/submission.types'

import {
CreateRedirectUrlError,
Expand Down Expand Up @@ -114,6 +115,42 @@ export const extractJwt = (
}
}

export const createSingpassParsedResponses = (
uinFin: string,
): ProcessedSingleAnswerResponse[] => {
return [
{
_id: '',
question: 'SingPass Validated NRIC',
fieldType: 'authenticationSp' as BasicField,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add typings for this? Then we can update fieldType to be a union of these typings

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idk, I wasn't really sure how to deal with this. one option is to create types for 'authenticationSp' and 'authenticationCp'. but actually this fieldType isn't even used anywhere, I just left it in because fieldType is a required field for ProcessedFieldResponse. I was hoping that when we eventually disentangle email-submissions.server.controller.js, we'll find a better way to handle SPCP fields than creating fake fieldTypes.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tl;dr I left it like this because I thought types wouldn't be useful

isVisible: true,
answer: uinFin,
},
]
}

export const createCorppassParsedResponses = (
uinFin: string,
userInfo: string,
): ProcessedSingleAnswerResponse[] => {
return [
{
_id: '',
question: 'CorpPass Validated UEN',
fieldType: 'authenticationCp' as BasicField,
isVisible: true,
answer: uinFin,
},
{
_id: '',
question: 'CorpPass Validated UID',
fieldType: 'authenticationCp' as BasicField,
isVisible: true,
answer: userInfo,
},
]
}

export const mapRouteError: MapRouteError = (error) => {
switch (error.constructor) {
case MissingFeatureError:
Expand Down
5 changes: 2 additions & 3 deletions src/app/routes/admin-forms.server.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,11 @@ let submissions = require('../../app/controllers/submissions.server.controller')
const emailSubmissions = require('../../app/controllers/email-submissions.server.controller')
let encryptSubmissions = require('../../app/controllers/encrypt-submissions.server.controller')
let PERMISSIONS = require('../utils/permission-levels').default
const spcpFactory = require('../factories/spcp.factory')
const webhookVerifiedContentFactory = require('../factories/webhook-verified-content.factory')
const AdminFormController = require('../modules/form/admin-form/admin-form.controller')
const { withUserAuthentication } = require('../modules/auth/auth.middlewares')
const EncryptSubmissionController = require('../modules/submission/encrypt-submission/encrypt-submission.controller')

const SpcpController = require('../modules/spcp/spcp.controller')
const YYYY_MM_DD_REGEX = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/

const emailValOpts = {
Expand Down Expand Up @@ -342,7 +341,7 @@ module.exports = function (app) {
emailSubmissions.validateEmailSubmission,
AdminFormController.passThroughSpcp,
submissions.injectAutoReplyInfo,
spcpFactory.appendVerifiedSPCPResponses,
SpcpController.appendVerifiedSPCPResponses,
emailSubmissions.prepareEmailSubmission,
adminForms.passThroughSaveMetadataToDb,
emailSubmissions.sendAdminEmail,
Expand Down
3 changes: 1 addition & 2 deletions src/app/routes/public-forms.server.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ const encryptSubmissions = require('../../app/controllers/encrypt-submissions.se
const emailSubmissions = require('../../app/controllers/email-submissions.server.controller')
const myInfoController = require('../../app/controllers/myinfo.server.controller')
const { celebrate, Joi, Segments } = require('celebrate')
const spcpFactory = require('../factories/spcp.factory')
const webhookVerifiedContentFactory = require('../factories/webhook-verified-content.factory')
const { CaptchaFactory } = require('../factories/captcha.factory')
const { limitRate } = require('../utils/limit-rate')
Expand Down Expand Up @@ -192,7 +191,7 @@ module.exports = function (app) {
emailSubmissions.validateEmailSubmission,
myInfoController.verifyMyInfoVals,
submissions.injectAutoReplyInfo,
spcpFactory.appendVerifiedSPCPResponses,
SpcpController.appendVerifiedSPCPResponses,
emailSubmissions.prepareEmailSubmission,
emailSubmissions.saveMetadataToDb,
emailSubmissions.sendAdminEmail,
Expand Down
8 changes: 8 additions & 0 deletions src/types/express.locals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,11 @@ export type ResWithUinFin<T> = T & {
export type ResWithHashedFields<T> = T & {
locals: { hashedFields?: Set<MyInfoAttribute> }
}

export type SpcpLocals =
| {
uinFin: string
hashedFields: Set<MyInfoAttribute>
}
| { uinFin: string; userInfo: string }
| { [key: string]: never } // empty object
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,9 @@ describe('Email Submissions Controller', () => {
},
},
)
const spcpController = spec(
'dist/backend/app/controllers/spcp.server.controller',
{
mongoose: Object.assign(mongoose, { '@noCallThru': true }),
'../../config/ndi-config': {},
},
)
const spcpController = spec('dist/backend/app/modules/spcp/spcp.controller', {
mongoose: Object.assign(mongoose, { '@noCallThru': true }),
})

beforeAll(async () => await dbHandler.connect())
beforeEach(() => {
Expand Down