Generate passwords at initialization (client/admin passwords)
[oweals/peertube.git] / server / initializers / installer.js
1 'use strict'
2
3 const async = require('async')
4 const config = require('config')
5 const mkdirp = require('mkdirp')
6 const passwordGenerator = require('password-generator')
7 const path = require('path')
8
9 const checker = require('./checker')
10 const logger = require('../helpers/logger')
11 const peertubeCrypto = require('../helpers/peertubeCrypto')
12 const Users = require('../models/users')
13
14 const installer = {
15   installApplication: installApplication
16 }
17
18 function installApplication (callback) {
19   // Creates directories
20   createDirectoriesIfNotExist(function (err) {
21     if (err) return callback(err)
22
23     // ----------- Create the certificates if they don't already exist -----------
24     peertubeCrypto.createCertsIfNotExist(function (err) {
25       if (err) return callback(err)
26
27       createOAuthClientIfNotExist(function (err) {
28         if (err) return callback(err)
29
30         createOAuthUserIfNotExist(callback)
31       })
32     })
33   })
34 }
35
36 // ---------------------------------------------------------------------------
37
38 module.exports = installer
39
40 // ---------------------------------------------------------------------------
41
42 function createDirectoriesIfNotExist (callback) {
43   const storages = config.get('storage')
44
45   async.each(Object.keys(storages), function (key, callbackEach) {
46     const dir = storages[key]
47     mkdirp(path.join(__dirname, '..', '..', dir), callbackEach)
48   }, callback)
49 }
50
51 function createOAuthClientIfNotExist (callback) {
52   checker.clientsExist(function (err, exist) {
53     if (err) return callback(err)
54
55     // Nothing to do, clients already exist
56     if (exist === true) return callback(null)
57
58     logger.info('Creating a default OAuth Client.')
59
60     const secret = passwordGenerator(32, false)
61     Users.createClient(secret, [ 'password' ], function (err, id) {
62       if (err) return callback(err)
63
64       logger.info('Client id: ' + id)
65       logger.info('Client secret: ' + secret)
66
67       return callback(null)
68     })
69   })
70 }
71
72 function createOAuthUserIfNotExist (callback) {
73   checker.usersExist(function (err, exist) {
74     if (err) return callback(err)
75
76     // Nothing to do, users already exist
77     if (exist === true) return callback(null)
78
79     logger.info('Creating the administrator.')
80
81     const username = 'root'
82     const password = passwordGenerator(8, true)
83
84     Users.createUser(username, password, function (err) {
85       if (err) return callback(err)
86
87       logger.info('Username: ' + username)
88       logger.info('User password: ' + password)
89
90       return callback(null)
91     })
92   })
93 }