roysathome.net/auth/initialize_database.rb

50 lines
1.9 KiB
Ruby

require_relative "cryptography"
require 'sqlite3'
def initialize_database
puts 'Checking if database needs initializing.'
directory_path = './database'
unless File.directory?(directory_path)
# If not, create the directory
Dir.mkdir(directory_path)
puts "Directory '#{directory_path}' created successfully."
end
db = SQLite3::Database.new('./database/auth.db')
puts 'Creating tables if necessary.'
db.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, hashed_password TEXT, salt TEXT)')
db.execute('CREATE TABLE IF NOT EXISTS claims (id INTEGER PRIMARY KEY, claim TEXT)')
db.execute('CREATE TABLE IF NOT EXISTS user_claims (id INTEGER PRIMARY KEY, user_id INTEGER, claim_id INTEGER)')
result = db.get_first_value('SELECT COUNT(*) FROM users')
if result == 0
hashed_password = hash_password 'pass123'
puts 'Default admin user added.'
db.execute('INSERT INTO users (username, hashed_password) VALUES (?, ?)', ['admin', hashed_password])
else
puts 'Table already contains data. Skipping default user creation.'
end
result = db.get_first_value('SELECT COUNT(*) FROM claims')
if result == 0
db.execute('INSERT INTO claims (claim) VALUES (?)', ['add_user'])
db.execute('INSERT INTO claims (claim) VALUES (?)', ['remove_user'])
db.execute('INSERT INTO claims (claim) VALUES (?)', ['add_claim_to_user'])
db.execute('INSERT INTO claims (claim) VALUES (?)', ['remove_claim_from_user'])
end
admin_user_id = db.get_first_value('SELECT id FROM users WHERE username = ?', ['admin'])
claim_ids = db.execute('SELECT id FROM claims')
claim_ids.each do |claim_id|
db.execute('INSERT INTO user_claims (user_id, claim_id) VALUES (?, ?)', [admin_user_id, claim_id])
end
end