3c5a77df9ac478e518b3b65f30a7fe6b4ca49db7
[oweals/peertube.git] / server / initializers / installer.ts
1 import { join } from 'path'
2 import * as config from 'config'
3 import * as passwordGenerator from 'password-generator'
4 import * as Promise from 'bluebird'
5
6 import { database as db } from './database'
7 import { USER_ROLES, CONFIG, LAST_MIGRATION_VERSION, CACHE } from './constants'
8 import { clientsExist, usersExist } from './checker'
9 import { logger, createCertsIfNotExist, root, mkdirpPromise, rimrafPromise } from '../helpers'
10
11 function installApplication () {
12   return db.sequelize.sync()
13     .then(() => removeCacheDirectories())
14     .then(() => createDirectoriesIfNotExist())
15     .then(() => createCertsIfNotExist())
16     .then(() => createOAuthClientIfNotExist())
17     .then(() => createOAuthAdminIfNotExist())
18 }
19
20 // ---------------------------------------------------------------------------
21
22 export {
23   installApplication
24 }
25
26 // ---------------------------------------------------------------------------
27
28 function removeCacheDirectories () {
29   const cacheDirectories = CACHE.DIRECTORIES
30
31   const tasks = []
32
33   // Cache directories
34   Object.keys(cacheDirectories).forEach(key => {
35     const dir = cacheDirectories[key]
36     tasks.push(rimrafPromise(dir))
37   })
38
39   return Promise.all(tasks)
40 }
41
42 function createDirectoriesIfNotExist () {
43   const storages = CONFIG.STORAGE
44   const cacheDirectories = CACHE.DIRECTORIES
45
46   const tasks = []
47   Object.keys(storages).forEach(key => {
48     const dir = storages[key]
49     tasks.push(mkdirpPromise(dir))
50   })
51
52   // Cache directories
53   Object.keys(cacheDirectories).forEach(key => {
54     const dir = cacheDirectories[key]
55     tasks.push(mkdirpPromise(dir))
56   })
57
58   return Promise.all(tasks)
59 }
60
61 function createOAuthClientIfNotExist () {
62   return clientsExist().then(exist => {
63     // Nothing to do, clients already exist
64     if (exist === true) return undefined
65
66     logger.info('Creating a default OAuth Client.')
67
68     const id = passwordGenerator(32, false, /[a-z0-9]/)
69     const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
70     const client = db.OAuthClient.build({
71       clientId: id,
72       clientSecret: secret,
73       grants: [ 'password', 'refresh_token' ],
74       redirectUris: null
75     })
76
77     return client.save().then(createdClient => {
78       logger.info('Client id: ' + createdClient.clientId)
79       logger.info('Client secret: ' + createdClient.clientSecret)
80
81       return undefined
82     })
83   })
84 }
85
86 function createOAuthAdminIfNotExist () {
87   return usersExist().then(exist => {
88     // Nothing to do, users already exist
89     if (exist === true) return undefined
90
91     logger.info('Creating the administrator.')
92
93     const username = 'root'
94     const role = USER_ROLES.ADMIN
95     const email = CONFIG.ADMIN.EMAIL
96     const createOptions: { validate?: boolean } = {}
97     let password = ''
98
99     // Do not generate a random password for tests
100     if (process.env.NODE_ENV === 'test') {
101       password = 'test'
102
103       if (process.env.NODE_APP_INSTANCE) {
104         password += process.env.NODE_APP_INSTANCE
105       }
106
107       // Our password is weak so do not validate it
108       createOptions.validate = false
109     } else {
110       password = passwordGenerator(8, true)
111     }
112
113     const userData = {
114       username,
115       email,
116       password,
117       role
118     }
119
120     return db.User.create(userData, createOptions).then(createdUser => {
121       logger.info('Username: ' + username)
122       logger.info('User password: ' + password)
123
124       logger.info('Creating Application table.')
125       return db.Application.create({ migrationVersion: LAST_MIGRATION_VERSION })
126     })
127   })
128 }