From 82bcd03f15d8e3d46d2be4bd7c3fc9d411807529 Mon Sep 17 00:00:00 2001 From: Alex Ling Date: Wed, 3 Jun 2020 08:20:40 +0000 Subject: [PATCH] Always create initial user if the DB is empty when started --- src/storage.cr | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/storage.cr b/src/storage.cr index f577557..e4cbec1 100644 --- a/src/storage.cr +++ b/src/storage.cr @@ -47,23 +47,30 @@ class Storage Logger.fatal "Error when checking tables in DB: #{e}" raise e end + + # If the DB is initialized through CLI but no user is added, we need + # to create the admin user when first starting the app + user_count = db.query_one "select count(*) from users", as: Int32 + init_admin if init_user && user_count == 0 else Logger.debug "Creating DB file at #{@path}" db.exec "create unique index username_idx on users (username)" db.exec "create unique index token_idx on users (token)" - if init_user - random_pw = random_str - hash = hash_password random_pw - db.exec "insert into users values (?, ?, ?, ?)", - "admin", hash, nil, 1 - Logger.log "Initial user created. You can log in with " \ - "#{{"username" => "admin", "password" => random_pw}}" - end + init_admin if init_user end end end + macro init_admin + random_pw = random_str + hash = hash_password random_pw + db.exec "insert into users values (?, ?, ?, ?)", + "admin", hash, nil, 1 + Logger.log "Initial user created. You can log in with " \ + "#{{"username" => "admin", "password" => random_pw}}" + end + def verify_user(username, password) DB.open "sqlite3://#{@path}" do |db| begin