aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/custom-validators/users.ts
blob: 750563adab77f769d8da779b35f9b7693c4fdc0e (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
import { values } from 'lodash'
import * as validator from 'validator'

import { exists } from './misc'
import { CONSTRAINTS_FIELDS, USER_ROLES } from '../../initializers'
import { UserRole } from '../../../shared'

const USERS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.USERS

function isUserPasswordValid (value: string) {
  return validator.isLength(value, USERS_CONSTRAINTS_FIELDS.PASSWORD)
}

function isUserRoleValid (value: string) {
  return values(USER_ROLES).indexOf(value as UserRole) !== -1
}

function isUserUsernameValid (value: string) {
  const max = USERS_CONSTRAINTS_FIELDS.USERNAME.max
  const min = USERS_CONSTRAINTS_FIELDS.USERNAME.min
  return exists(value) && validator.matches(value, new RegExp(`^[a-zA-Z0-9._]{${min},${max}}$`))
}

function isUserDisplayNSFWValid (value: any) {
  return typeof value === 'boolean' || (typeof value === 'string' && validator.isBoolean(value))
}

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

export {
  isUserPasswordValid,
  isUserRoleValid,
  isUserUsernameValid,
  isUserDisplayNSFWValid
}

declare global {
  namespace ExpressValidator {
    export interface Validator {
      isUserPasswordValid,
      isUserRoleValid,
      isUserUsernameValid,
      isUserDisplayNSFWValid
    }
  }
}