aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middlewares/validators/two-factor.ts
blob: 106b579b5d1690df1eaafe368488024593a474c0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import express from 'express'
import { body, param } from 'express-validator'
import { HttpStatusCode, UserRight } from '@shared/models'
import { exists, isIdValid } from '../../helpers/custom-validators/misc'
import { areValidationErrors, checkUserIdExist } from './shared'

const requestOrConfirmTwoFactorValidator = [
  param('id').custom(isIdValid),

  async (req: express.Request, res: express.Response, next: express.NextFunction) => {
    if (areValidationErrors(req, res)) return

    if (!await checkCanEnableOrDisableTwoFactor(req.params.id, res)) return

    if (res.locals.user.otpSecret) {
      return res.fail({
        status: HttpStatusCode.BAD_REQUEST_400,
        message: `Two factor is already enabled.`
      })
    }

    return next()
  }
]

const confirmTwoFactorValidator = [
  body('requestToken').custom(exists),
  body('otpToken').custom(exists),

  (req: express.Request, res: express.Response, next: express.NextFunction) => {
    if (areValidationErrors(req, res)) return

    return next()
  }
]

const disableTwoFactorValidator = [
  param('id').custom(isIdValid),

  async (req: express.Request, res: express.Response, next: express.NextFunction) => {
    if (areValidationErrors(req, res)) return

    if (!await checkCanEnableOrDisableTwoFactor(req.params.id, res)) return

    if (!res.locals.user.otpSecret) {
      return res.fail({
        status: HttpStatusCode.BAD_REQUEST_400,
        message: `Two factor is already disabled.`
      })
    }

    return next()
  }
]

// ---------------------------------------------------------------------------

export {
  requestOrConfirmTwoFactorValidator,
  confirmTwoFactorValidator,
  disableTwoFactorValidator
}

// ---------------------------------------------------------------------------

async function checkCanEnableOrDisableTwoFactor (userId: number | string, res: express.Response) {
  const authUser = res.locals.oauth.token.user

  if (!await checkUserIdExist(userId, res)) return

  if (res.locals.user.id !== authUser.id && authUser.hasRight(UserRight.MANAGE_USERS) !== true) {
    res.fail({
      status: HttpStatusCode.FORBIDDEN_403,
      message: `User ${authUser.username} does not have right to change two factor setting of this user.`
    })

    return false
  }

  return true
}