From 0a62002a6e6293e10a2e10b764e2be1252b99acd Mon Sep 17 00:00:00 2001 From: Bobby Wibowo Date: Tue, 9 Aug 2022 17:28:21 +0700 Subject: [PATCH] fix: re-create "root" user if users table is empty previously it'd always re-create it if "root" user itself is missing from users table this facilitates not having "root" user altogether --- controllers/utils/initDatabase.js | 35 +++++++++++++++++++------------ 1 file changed, 22 insertions(+), 13 deletions(-) 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}".`) } }