aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middlewares/validators/shared/user-registrations.ts
blob: dbc7dda0696c9b9e96234688968dbbcfd29ce819 (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
import express from 'express'
import { UserRegistrationModel } from '@server/models/user/user-registration'
import { MRegistration } from '@server/types/models'
import { forceNumber, pick } from '@shared/core-utils'
import { HttpStatusCode } from '@shared/models'

function checkRegistrationIdExist (idArg: number | string, res: express.Response) {
  const id = forceNumber(idArg)
  return checkRegistrationExist(() => UserRegistrationModel.load(id), res)
}

function checkRegistrationEmailExist (email: string, res: express.Response, abortResponse = true) {
  return checkRegistrationExist(() => UserRegistrationModel.loadByEmail(email), res, abortResponse)
}

async function checkRegistrationHandlesDoNotAlreadyExist (options: {
  username: string
  channelHandle: string
  email: string
  res: express.Response
}) {
  const { res } = options

  const registration = await UserRegistrationModel.loadByEmailOrHandle(pick(options, [ 'username', 'email', 'channelHandle' ]))

  if (registration) {
    res.fail({
      status: HttpStatusCode.CONFLICT_409,
      message: 'Registration with this username, channel name or email already exists.'
    })
    return false
  }

  return true
}

async function checkRegistrationExist (finder: () => Promise<MRegistration>, res: express.Response, abortResponse = true) {
  const registration = await finder()

  if (!registration) {
    if (abortResponse === true) {
      res.fail({
        status: HttpStatusCode.NOT_FOUND_404,
        message: 'User not found'
      })
    }

    return false
  }

  res.locals.userRegistration = registration
  return true
}

export {
  checkRegistrationIdExist,
  checkRegistrationEmailExist,
  checkRegistrationHandlesDoNotAlreadyExist,
  checkRegistrationExist
}