1 import * as passwordGenerator from 'password-generator'
2 import * as Promise from 'bluebird'
4 import { database as db } from './database'
5 import { USER_ROLES, CONFIG, LAST_MIGRATION_VERSION, CACHE } from './constants'
6 import { clientsExist, usersExist } from './checker'
7 import { logger, createCertsIfNotExist, mkdirpPromise, rimrafPromise } from '../helpers'
9 function installApplication () {
10 return db.sequelize.sync()
11 .then(() => removeCacheDirectories())
12 .then(() => createDirectoriesIfNotExist())
13 .then(() => createCertsIfNotExist())
14 .then(() => createOAuthClientIfNotExist())
15 .then(() => createOAuthAdminIfNotExist())
18 // ---------------------------------------------------------------------------
24 // ---------------------------------------------------------------------------
26 function removeCacheDirectories () {
27 const cacheDirectories = CACHE.DIRECTORIES
32 Object.keys(cacheDirectories).forEach(key => {
33 const dir = cacheDirectories[key]
34 tasks.push(rimrafPromise(dir))
37 return Promise.all(tasks)
40 function createDirectoriesIfNotExist () {
41 const storages = CONFIG.STORAGE
42 const cacheDirectories = CACHE.DIRECTORIES
45 Object.keys(storages).forEach(key => {
46 const dir = storages[key]
47 tasks.push(mkdirpPromise(dir))
51 Object.keys(cacheDirectories).forEach(key => {
52 const dir = cacheDirectories[key]
53 tasks.push(mkdirpPromise(dir))
56 return Promise.all(tasks)
59 function createOAuthClientIfNotExist () {
60 return clientsExist().then(exist => {
61 // Nothing to do, clients already exist
62 if (exist === true) return undefined
64 logger.info('Creating a default OAuth Client.')
66 const id = passwordGenerator(32, false, /[a-z0-9]/)
67 const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
68 const client = db.OAuthClient.build({
71 grants: [ 'password', 'refresh_token' ],
75 return client.save().then(createdClient => {
76 logger.info('Client id: ' + createdClient.clientId)
77 logger.info('Client secret: ' + createdClient.clientSecret)
84 function createOAuthAdminIfNotExist () {
85 return usersExist().then(exist => {
86 // Nothing to do, users already exist
87 if (exist === true) return undefined
89 logger.info('Creating the administrator.')
91 const username = 'root'
92 const role = USER_ROLES.ADMIN
93 const email = CONFIG.ADMIN.EMAIL
94 const createOptions: { validate?: boolean } = {}
97 // Do not generate a random password for tests
98 if (process.env.NODE_ENV === 'test') {
101 if (process.env.NODE_APP_INSTANCE) {
102 password += process.env.NODE_APP_INSTANCE
105 // Our password is weak so do not validate it
106 createOptions.validate = false
108 password = passwordGenerator(8, true)
118 return db.User.create(userData, createOptions).then(createdUser => {
119 logger.info('Username: ' + username)
120 logger.info('User password: ' + password)
122 logger.info('Creating Application table.')
123 return db.Application.create({ migrationVersion: LAST_MIGRATION_VERSION })