Increase access_token lifetime
[oweals/peertube.git] / server / initializers / installer.ts
1 import * as passwordGenerator from 'password-generator'
2 import { UserRole } from '../../shared'
3 import { mkdirpPromise, rimrafPromise } from '../helpers/core-utils'
4 import { logger } from '../helpers/logger'
5 import { createApplicationActor, createUserAccountAndChannel } from '../lib/user'
6 import { UserModel } from '../models/account/user'
7 import { ApplicationModel } from '../models/application/application'
8 import { OAuthClientModel } from '../models/oauth/oauth-client'
9 import { applicationExist, clientsExist, usersExist } from './checker'
10 import { CACHE, CONFIG, LAST_MIGRATION_VERSION } from './constants'
11 import { sequelizeTypescript } from './database'
12
13 async function installApplication () {
14   try {
15     await sequelizeTypescript.sync()
16     await removeCacheDirectories()
17     await createDirectoriesIfNotExist()
18     await createApplicationIfNotExist()
19     await createOAuthClientIfNotExist()
20     await createOAuthAdminIfNotExist()
21   } catch (err) {
22     logger.error('Cannot install application.', { err })
23     process.exit(-1)
24   }
25 }
26
27 // ---------------------------------------------------------------------------
28
29 export {
30   installApplication
31 }
32
33 // ---------------------------------------------------------------------------
34
35 function removeCacheDirectories () {
36   const cacheDirectories = CACHE.DIRECTORIES
37
38   const tasks: Promise<any>[] = []
39
40   // Cache directories
41   for (const key of Object.keys(cacheDirectories)) {
42     const dir = cacheDirectories[key]
43     tasks.push(rimrafPromise(dir))
44   }
45
46   return Promise.all(tasks)
47 }
48
49 function createDirectoriesIfNotExist () {
50   const storage = CONFIG.STORAGE
51   const cacheDirectories = CACHE.DIRECTORIES
52
53   const tasks = []
54   for (const key of Object.keys(storage)) {
55     const dir = storage[key]
56     tasks.push(mkdirpPromise(dir))
57   }
58
59   // Cache directories
60   for (const key of Object.keys(cacheDirectories)) {
61     const dir = cacheDirectories[key]
62     tasks.push(mkdirpPromise(dir))
63   }
64
65   return Promise.all(tasks)
66 }
67
68 async function createOAuthClientIfNotExist () {
69   const exist = await clientsExist()
70   // Nothing to do, clients already exist
71   if (exist === true) return undefined
72
73   logger.info('Creating a default OAuth Client.')
74
75   const id = passwordGenerator(32, false, /[a-z0-9]/)
76   const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
77   const client = new OAuthClientModel({
78     clientId: id,
79     clientSecret: secret,
80     grants: [ 'password', 'refresh_token' ],
81     redirectUris: null
82   })
83
84   const createdClient = await client.save()
85   logger.info('Client id: ' + createdClient.clientId)
86   logger.info('Client secret: ' + createdClient.clientSecret)
87
88   return undefined
89 }
90
91 async function createOAuthAdminIfNotExist () {
92   const exist = await usersExist()
93   // Nothing to do, users already exist
94   if (exist === true) return undefined
95
96   logger.info('Creating the administrator.')
97
98   const username = 'root'
99   const role = UserRole.ADMINISTRATOR
100   const email = CONFIG.ADMIN.EMAIL
101   let validatePassword = true
102   let password = ''
103
104   // Do not generate a random password for tests
105   if (process.env.NODE_ENV === 'test') {
106     password = 'test'
107
108     if (process.env.NODE_APP_INSTANCE) {
109       password += process.env.NODE_APP_INSTANCE
110     }
111
112     // Our password is weak so do not validate it
113     validatePassword = false
114   } else {
115     password = passwordGenerator(16, true)
116   }
117
118   const userData = {
119     username,
120     email,
121     password,
122     role,
123     nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
124     videoQuota: -1
125   }
126   const user = new UserModel(userData)
127
128   await createUserAccountAndChannel(user, validatePassword)
129   logger.info('Username: ' + username)
130   logger.info('User password: ' + password)
131 }
132
133 async function createApplicationIfNotExist () {
134   const exist = await applicationExist()
135   // Nothing to do, application already exist
136   if (exist === true) return undefined
137
138   logger.info('Creating application account.')
139
140   const application = await ApplicationModel.create({
141     migrationVersion: LAST_MIGRATION_VERSION
142   })
143
144   return createApplicationActor(application.id)
145 }