diff --git a/controllers/utils/initDatabase.js b/controllers/utils/initDatabase.js index 0d0f963..7d8d580 100644 --- a/controllers/utils/initDatabase.js +++ b/controllers/utils/initDatabase.js @@ -1,3 +1,10 @@ +const logger = require('./../../logger') + +// Default root user's credentials +// Root user will only be created if "users" table is empty +const DEFAULT_ROOT_USERNAME = 'root' +const DEFAULT_ROOT_PASSWORD = 'changeme' + const initDatabase = async db => { // Create the tables we need to store galleries and files await db.schema.hasTable('albums').then(exists => { @@ -51,21 +58,23 @@ const initDatabase = async db => { } }) - const root = await db.table('users') - .where('username', 'root') - .first() + const usersCount = await db.table('users') + .count('id as count') + .then(rows => rows[0].count) - if (!root) { - const hash = await require('bcrypt').hash('changeme', 10) + if (usersCount === 0) { + const hash = await require('bcrypt').hash(DEFAULT_ROOT_PASSWORD, 10) const timestamp = Math.floor(Date.now() / 1000) - await db.table('users').insert({ - username: 'root', - password: hash, - token: require('randomstring').generate(64), - timestamp, - permission: require('./../permissionController').permissions.superadmin, - registration: timestamp - }) + await db.table('users') + .insert({ + username: DEFAULT_ROOT_USERNAME, + password: hash, + token: require('randomstring').generate(64), + timestamp, + permission: require('./../permissionController').permissions.superadmin, + registration: timestamp + }) + logger.log(`Created user "${DEFAULT_ROOT_USERNAME}" with password "${DEFAULT_ROOT_PASSWORD}".`) } }