roysathome.net/auth/initialize_database.rb

73 lines
2.7 KiB
Ruby

require_relative "cryptography"
require 'sqlite3'
def initialize_database
puts 'Checking if database needs initializing.'
database_path = DATA_LOCATION + DATABASE_SUBPATH
file_path = DATA_LOCATION + FILE_STORAGE_LOCATION
puts "Checking if directory '#{DATA_LOCATION}' exists."
unless Dir.exist?(DATA_LOCATION)
puts "Directory '#{DATA_LOCATION}' does not exist."
Dir.mkdir(DATA_LOCATION)
puts "Directory '#{DATA_LOCATION}' created successfully."
end
puts "Checking if directory '#{database_path}' exists."
unless Dir.exist?(database_path)
puts "Directory '#{database_path}' does not exist."
Dir.mkdir(database_path)
puts "Directory '#{database_path}' created successfully."
end
puts "Checking if directory '#{file_path}' exists."
unless Dir.exist?(file_path)
puts "Directory '#{file_path}' does not exist."
Dir.mkdir(file_path)
puts "Directory '#{file_path}' created successfully."
end
db = SQLite3::Database.new( DATA_LOCATION + DATABASE_SUBPATH + DATABASE_NAME )#'./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, is_admin INTEGER)')
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 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 (?)', ['is_machine'])
db.execute('INSERT INTO claims (claim) VALUES (?)', ['is_user'])
db.execute('INSERT INTO claims (claim) VALUES (?)', ['add_claim_to_user'])
db.execute('INSERT INTO claims (claim) VALUES (?)', ['remove_claim_from_user'])
end
result = db.get_first_value('SELECT COUNT(*) FROM users')
if result == 0
puts 'Default admin user added.'
create_new_user('admin', 'pass123', 1)
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
else
puts 'Table already contains data. Skipping default user creation.'
end
end