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
This commit is contained in:
Bobby Wibowo 2022-08-09 17:28:21 +07:00
parent 6ff735badb
commit 0a62002a6e
No known key found for this signature in database
GPG Key ID: 51C3A1E1E22D26CF

View File

@ -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}".`)
}
}