1 import express from 'express'
2 import { body, param } from 'express-validator'
3 import { HttpStatusCode, UserRight } from '@shared/models'
4 import { exists, isIdValid } from '../../helpers/custom-validators/misc'
5 import { areValidationErrors, checkUserIdExist } from './shared'
7 const requestOrConfirmTwoFactorValidator = [
8 param('id').custom(isIdValid),
10 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
11 if (areValidationErrors(req, res)) return
13 if (!await checkCanEnableOrDisableTwoFactor(req.params.id, res)) return
15 if (res.locals.user.otpSecret) {
17 status: HttpStatusCode.BAD_REQUEST_400,
18 message: `Two factor is already enabled.`
26 const confirmTwoFactorValidator = [
27 body('requestToken').custom(exists),
28 body('otpToken').custom(exists),
30 (req: express.Request, res: express.Response, next: express.NextFunction) => {
31 if (areValidationErrors(req, res)) return
37 const disableTwoFactorValidator = [
38 param('id').custom(isIdValid),
40 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
41 if (areValidationErrors(req, res)) return
43 if (!await checkCanEnableOrDisableTwoFactor(req.params.id, res)) return
45 if (!res.locals.user.otpSecret) {
47 status: HttpStatusCode.BAD_REQUEST_400,
48 message: `Two factor is already disabled.`
56 // ---------------------------------------------------------------------------
59 requestOrConfirmTwoFactorValidator,
60 confirmTwoFactorValidator,
61 disableTwoFactorValidator
64 // ---------------------------------------------------------------------------
66 async function checkCanEnableOrDisableTwoFactor (userId: number | string, res: express.Response) {
67 const authUser = res.locals.oauth.token.user
69 if (!await checkUserIdExist(userId, res)) return
71 if (res.locals.user.id !== authUser.id && authUser.hasRight(UserRight.MANAGE_USERS) !== true) {
73 status: HttpStatusCode.FORBIDDEN_403,
74 message: `User ${authUser.username} does not have right to change two factor setting of this user.`