]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/utils.ts
Add ability to limit user registrations
[github/Chocobozzz/PeerTube.git] / server / helpers / utils.ts
1 import * as express from 'express'
2 import * as Promise from 'bluebird'
3
4 import { pseudoRandomBytesPromise } from './core-utils'
5 import { CONFIG, database as db } from '../initializers'
6 import { ResultList } from '../../shared'
7
8 function badRequest (req: express.Request, res: express.Response, next: express.NextFunction) {
9 res.type('json').status(400).end()
10 }
11
12 function generateRandomString (size: number) {
13 return pseudoRandomBytesPromise(size).then(raw => raw.toString('hex'))
14 }
15
16 interface FormatableToJSON {
17 toFormatedJSON ()
18 }
19
20 function getFormatedObjects<U, T extends FormatableToJSON> (objects: T[], objectsTotal: number) {
21 const formatedObjects: U[] = []
22
23 objects.forEach(object => {
24 formatedObjects.push(object.toFormatedJSON())
25 })
26
27 const res: ResultList<U> = {
28 total: objectsTotal,
29 data: formatedObjects
30 }
31
32 return res
33 }
34
35 function isSignupAllowed () {
36 if (CONFIG.SIGNUP.ENABLED === false) {
37 return Promise.resolve(false)
38 }
39
40 // No limit and signup is enabled
41 if (CONFIG.SIGNUP.LIMIT === -1) {
42 return Promise.resolve(true)
43 }
44
45 return db.User.countTotal().then(totalUsers => {
46 return totalUsers < CONFIG.SIGNUP.LIMIT
47 })
48 }
49
50 // ---------------------------------------------------------------------------
51
52 export {
53 badRequest,
54 generateRandomString,
55 getFormatedObjects,
56 isSignupAllowed
57 }