import { MAX_CARD_ATTEMPTS, ONECLICK_API_URL, } from '../../lib/constants' import { cardSession, orderSession } from '../../sessions' import { makeError, replies } from '@oyst/utils' import { merge, pick } from 'ramda' import { MFA } from '@oyst/mfa' import authorizeHandler from '../../handlers/authorize' import { authorize as headers } from '../../validators/headers' import { card as payload } from '../../validators/users' const { error, success } = replies export default { config: { pre: [authorizeHandler], validate: { headers, payload } }, handler: async (req, reply) => { try { const mobileDetect = require('mobile-detect') const md = new mobileDetect(req.headers['user-agent']) const sessionID = req.pre.authorization.data.id as string await cardSession.setMaxAttempts(sessionID, MAX_CARD_ATTEMPTS) await cardSession.increment(sessionID) const validation = await cardSession.isValid(sessionID) if (!validation.success) { await orderSession.del(sessionID) return error(makeError('CLICK-429', 'too-many-attempts'), reply) } const { phone } = await orderSession.getData<{ phone: string }>(sessionID, 'phone') if (!phone) { return error(makeError('CLICK-404', 'phone-not-found'), reply) } await cardSession.setData(sessionID, req.payload) await orderSession.setData(sessionID, { success: false }, 'mfa-validated') await orderSession.setData(sessionID, {}, 'login-user') const res = await MFA.sendSMS(phone, { code: { length: 4, alpha: false }, is_mobile: !!md.mobile(), type: 'oneclick.enroll', urls: { success: `${ONECLICK_API_URL}/v1/mfa/phone` } }, sessionID) await orderSession.setData(sessionID, { uuid: res.uuid }, 'phone-session') if (res.success) { return success(merge({ channel: `phone-checker-${res.id}`, code: true, retry_request: { key: 'phone', method: 'POST', path: '/mfa/resend' }, sms: true }, pick(['event', 'id', 'phone', 'can_retry'], res)), reply) } const err = res.can_retry ? makeError('MFA-500', 'sms-not-sent') : makeError('MFA-429', 'too-many-attempts') error(err, reply) } catch (err) { error(makeError(err), reply) } }, method: 'POST', path: '/v1/users/card' }