1 import { join } from 'path'
2 import * as config from 'config'
3 import * as passwordGenerator from 'password-generator'
4 import * as Promise from 'bluebird'
6 import { database as db } from './database'
7 import { USER_ROLES, CONFIG, LAST_MIGRATION_VERSION } from './constants'
8 import { clientsExist, usersExist } from './checker'
9 import { logger, createCertsIfNotExist, root, mkdirpPromise } from '../helpers'
11 function installApplication () {
12 return db.sequelize.sync()
13 .then(() => createDirectoriesIfNotExist())
14 .then(() => createCertsIfNotExist())
15 .then(() => createOAuthClientIfNotExist())
16 .then(() => createOAuthAdminIfNotExist())
19 // ---------------------------------------------------------------------------
25 // ---------------------------------------------------------------------------
27 function createDirectoriesIfNotExist () {
28 const storages = config.get('storage')
31 Object.keys(storages).forEach(key => {
32 const dir = storages[key]
33 tasks.push(mkdirpPromise(join(root(), dir)))
36 return Promise.all(tasks)
39 function createOAuthClientIfNotExist () {
40 return clientsExist().then(exist => {
41 // Nothing to do, clients already exist
42 if (exist === true) return undefined
44 logger.info('Creating a default OAuth Client.')
46 const id = passwordGenerator(32, false, /[a-z0-9]/)
47 const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
48 const client = db.OAuthClient.build({
51 grants: [ 'password', 'refresh_token' ],
55 return client.save().then(createdClient => {
56 logger.info('Client id: ' + createdClient.clientId)
57 logger.info('Client secret: ' + createdClient.clientSecret)
64 function createOAuthAdminIfNotExist () {
65 return usersExist().then(exist => {
66 // Nothing to do, users already exist
67 if (exist === true) return undefined
69 logger.info('Creating the administrator.')
71 const username = 'root'
72 const role = USER_ROLES.ADMIN
73 const email = CONFIG.ADMIN.EMAIL
74 const createOptions: { validate?: boolean } = {}
77 // Do not generate a random password for tests
78 if (process.env.NODE_ENV === 'test') {
81 if (process.env.NODE_APP_INSTANCE) {
82 password += process.env.NODE_APP_INSTANCE
85 // Our password is weak so do not validate it
86 createOptions.validate = false
88 password = passwordGenerator(8, true)
98 return db.User.create(userData, createOptions).then(createdUser => {
99 logger.info('Username: ' + username)
100 logger.info('User password: ' + password)
102 logger.info('Creating Application table.')
103 return db.Application.create({ migrationVersion: LAST_MIGRATION_VERSION })