]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/custom-validators/accounts.ts
a6d7f2b821a0ca773d00378d5df6fc1e587080dc
[github/Chocobozzz/PeerTube.git] / server / helpers / custom-validators / accounts.ts
1 import * as Bluebird from 'bluebird'
2 import * as express from 'express'
3 import 'express-validator'
4 import * as validator from 'validator'
5 import { database as db } from '../../initializers'
6 import { AccountInstance } from '../../models'
7 import { logger } from '../logger'
8 import { isUserUsernameValid } from './users'
9
10 function isAccountNameValid (value: string) {
11 return isUserUsernameValid(value)
12 }
13
14 function checkAccountIdExists (id: number | string, res: express.Response, callback: (err: Error, account: AccountInstance) => any) {
15 let promise: Bluebird<AccountInstance>
16
17 if (validator.isInt('' + id)) {
18 promise = db.Account.load(+id)
19 } else { // UUID
20 promise = db.Account.loadByUUID('' + id)
21 }
22
23 return checkAccountExists(promise, res, callback)
24 }
25
26 function checkLocalAccountNameExists (name: string, res: express.Response, callback: (err: Error, account: AccountInstance) => any) {
27 const p = db.Account.loadLocalByName(name)
28
29 return checkAccountExists(p, res, callback)
30 }
31
32 function checkAccountExists (p: Bluebird<AccountInstance>, res: express.Response, callback: (err: Error, account: AccountInstance) => any) {
33 p.then(account => {
34 if (!account) {
35 return res.status(404)
36 .send({ error: 'Account not found' })
37 .end()
38 }
39
40 res.locals.account = account
41 return callback(null, account)
42 })
43 .catch(err => {
44 logger.error('Error in account request validator.', err)
45 return res.sendStatus(500)
46 })
47 }
48
49 // ---------------------------------------------------------------------------
50
51 export {
52 checkAccountIdExists,
53 checkLocalAccountNameExists,
54 isAccountNameValid
55 }