(
...[router, { libraries, queries }]: RouterInitArgs<T>
)
| 13 | const codeType = TemplateType.Generic; |
| 14 | |
| 15 | export default function verificationCodeRoutes<T extends ManagementApiRouter>( |
| 16 | ...[router, { libraries, queries }]: RouterInitArgs<T> |
| 17 | ) { |
| 18 | const { |
| 19 | passcodes: { createPasscode, sendPasscode, verifyPasscode }, |
| 20 | } = libraries; |
| 21 | |
| 22 | router.post( |
| 23 | '/verification-codes', |
| 24 | koaGuard({ |
| 25 | body: requestVerificationCodePayloadGuard, |
| 26 | status: [204, 400, 429, 501], |
| 27 | }), |
| 28 | async (ctx, next) => { |
| 29 | const recipient = 'email' in ctx.guard.body ? ctx.guard.body.email : ctx.guard.body.phone; |
| 30 | // Create the passcode inside `send` so a rate-limited request neither creates a passcode nor |
| 31 | // deletes the recipient's existing unconsumed one (createPasscode replaces prior codes). |
| 32 | const send = async () => { |
| 33 | const code = await createPasscode(undefined, codeType, ctx.guard.body); |
| 34 | return sendPasscode(code, { ip: ctx.request.ip }); |
| 35 | }; |
| 36 | |
| 37 | await withMessageRateGuard( |
| 38 | await buildMessageRateGuard(queries), |
| 39 | { action: SentinelActivityAction.VerificationCodeSend, recipient }, |
| 40 | send |
| 41 | ); |
| 42 | |
| 43 | ctx.status = 204; |
| 44 | |
| 45 | return next(); |
| 46 | } |
| 47 | ); |
| 48 | |
| 49 | router.post( |
| 50 | '/verification-codes/verify', |
| 51 | koaGuard({ |
| 52 | body: verifyVerificationCodePayloadGuard, |
| 53 | status: [204, 400], |
| 54 | }), |
| 55 | async (ctx, next) => { |
| 56 | const { verificationCode, ...identifier } = ctx.guard.body; |
| 57 | await verifyPasscode(undefined, codeType, verificationCode, identifier); |
| 58 | |
| 59 | ctx.status = 204; |
| 60 | |
| 61 | return next(); |
| 62 | } |
| 63 | ); |
| 64 | } |
no test coverage detected