07ae76b63f43e68ac45bae7db20260d4c3fe8247
[oweals/peertube.git] / server / middlewares / validators / account.ts
1 import * as express from 'express'
2 import { param } from 'express-validator/check'
3 import { logger } from '../../helpers'
4 import { isAccountNameValid } from '../../helpers/custom-validators/accounts'
5 import { database as db } from '../../initializers/database'
6 import { AccountInstance } from '../../models'
7 import { checkErrors } from './utils'
8
9 const localAccountValidator = [
10   param('name').custom(isAccountNameValid).withMessage('Should have a valid account name'),
11
12   (req: express.Request, res: express.Response, next: express.NextFunction) => {
13     logger.debug('Checking localAccountValidator parameters', { parameters: req.params })
14
15     checkErrors(req, res, () => {
16       checkLocalAccountExists(req.params.name, res, next)
17     })
18   }
19 ]
20
21 // ---------------------------------------------------------------------------
22
23 export {
24   localAccountValidator
25 }
26
27 // ---------------------------------------------------------------------------
28
29 function checkLocalAccountExists (name: string, res: express.Response, callback: (err: Error, account: AccountInstance) => void) {
30   db.Account.loadLocalByName(name)
31     .then(account => {
32       if (!account) {
33         return res.status(404)
34           .send({ error: 'Account not found' })
35           .end()
36       }
37
38       res.locals.account = account
39       return callback(null, account)
40     })
41     .catch(err => {
42       logger.error('Error in account request validator.', err)
43       return res.sendStatus(500)
44     })
45 }