Skip to content
This repository was archived by the owner on Mar 23, 2025. It is now read-only.

Commit 82bcd03

Browse files
committed
Always create initial user if the DB is empty when started
1 parent fe799f3 commit 82bcd03

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

src/storage.cr

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,23 +47,30 @@ class Storage
4747
Logger.fatal "Error when checking tables in DB: #{e}"
4848
raise e
4949
end
50+
51+
# If the DB is initialized through CLI but no user is added, we need
52+
# to create the admin user when first starting the app
53+
user_count = db.query_one "select count(*) from users", as: Int32
54+
init_admin if init_user && user_count == 0
5055
else
5156
Logger.debug "Creating DB file at #{@path}"
5257
db.exec "create unique index username_idx on users (username)"
5358
db.exec "create unique index token_idx on users (token)"
5459

55-
if init_user
56-
random_pw = random_str
57-
hash = hash_password random_pw
58-
db.exec "insert into users values (?, ?, ?, ?)",
59-
"admin", hash, nil, 1
60-
Logger.log "Initial user created. You can log in with " \
61-
"#{{"username" => "admin", "password" => random_pw}}"
62-
end
60+
init_admin if init_user
6361
end
6462
end
6563
end
6664

65+
macro init_admin
66+
random_pw = random_str
67+
hash = hash_password random_pw
68+
db.exec "insert into users values (?, ?, ?, ?)",
69+
"admin", hash, nil, 1
70+
Logger.log "Initial user created. You can log in with " \
71+
"#{{"username" => "admin", "password" => random_pw}}"
72+
end
73+
6774
def verify_user(username, password)
6875
DB.open "sqlite3://#{@path}" do |db|
6976
begin

0 commit comments

Comments
 (0)