Handle account name in client url
[oweals/peertube.git] / server / helpers / custom-validators / accounts.ts
1 import * as Bluebird from 'bluebird'
2 import { Response } from 'express'
3 import 'express-validator'
4 import * as validator from 'validator'
5 import { AccountModel } from '../../models/account/account'
6 import { isUserDescriptionValid, isUserUsernameValid } from './users'
7 import { exists } from './misc'
8
9 function isAccountNameValid (value: string) {
10   return isUserUsernameValid(value)
11 }
12
13 function isAccountIdValid (value: string) {
14   return exists(value)
15 }
16
17 function isAccountDescriptionValid (value: string) {
18   return isUserDescriptionValid(value)
19 }
20
21 function isAccountIdExist (id: number | string, res: Response, sendNotFound = true) {
22   let promise: Bluebird<AccountModel>
23
24   if (validator.isInt('' + id)) {
25     promise = AccountModel.load(+id)
26   } else { // UUID
27     promise = AccountModel.loadByUUID('' + id)
28   }
29
30   return isAccountExist(promise, res, sendNotFound)
31 }
32
33 function isLocalAccountNameExist (name: string, res: Response, sendNotFound = true) {
34   const promise = AccountModel.loadLocalByName(name)
35
36   return isAccountExist(promise, res, sendNotFound)
37 }
38
39 function isAccountNameWithHostExist (nameWithDomain: string, res: Response, sendNotFound = true) {
40   const [ accountName, host ] = nameWithDomain.split('@')
41
42   let promise: Bluebird<AccountModel>
43   if (!host) promise = AccountModel.loadLocalByName(accountName)
44   else promise = AccountModel.loadLocalByNameAndHost(accountName, host)
45
46   return isAccountExist(promise, res, sendNotFound)
47 }
48
49 async function isAccountExist (p: Bluebird<AccountModel>, res: Response, sendNotFound: boolean) {
50   const account = await p
51
52   if (!account) {
53     if (sendNotFound === true) {
54       res.status(404)
55          .send({ error: 'Account not found' })
56          .end()
57     }
58
59     return false
60   }
61
62   res.locals.account = account
63
64   return true
65 }
66
67 // ---------------------------------------------------------------------------
68
69 export {
70   isAccountIdValid,
71   isAccountIdExist,
72   isLocalAccountNameExist,
73   isAccountDescriptionValid,
74   isAccountNameWithHostExist,
75   isAccountNameValid
76 }