Skip to content

Commit

Permalink
feat: setup admin user via env variables
Browse files Browse the repository at this point in the history
  • Loading branch information
sjdonado committed Nov 27, 2024
1 parent 3fa30b3 commit dfb6b10
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
23 changes: 21 additions & 2 deletions app/services/cli.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ require "../lib/*"
require "../models/*"

module App::Services::Cli
def self.create_user(name)
def self.create_user(name, api_key = nil)
user = App::Models::User.new
user.id = UUID.v4.to_s
user.name = name
user.api_key = Random::Secure.urlsafe_base64()
user.api_key = api_key || Random::Secure.urlsafe_base64()

changeset = App::Lib::Database.insert(user)
return changeset.errors if !changeset.valid?
Expand Down Expand Up @@ -35,4 +35,23 @@ module App::Services::Cli

"User with ID #{user_id} deleted successfully"
end

def self.setup_admin_user
admin_name = ENV["ADMIN_NAME"]
admin_api_key = ENV["ADMIN_API_KEY"]

if admin_name && admin_api_key
# Query to check if admin user already exists
query = App::Lib::Database::Query.where(name: admin_name, api_key: admin_api_key).limit(1)
existing_user = App::Lib::Database.all(App::Models::User, query).first?

return if existing_user

puts "Admin user setup detected. Creating admin user..."
result = create_user(admin_name, admin_api_key)
puts result
else
puts "Admin setup skipped: Missing ADMIN_NAME or ADMIN_API_KEY environment variables."
end
end
end
2 changes: 2 additions & 0 deletions bit.cr
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ require "./app/routes"
add_context_storage_type(App::Models::User)
add_handler(App::Middlewares::Auth.new)

App::Services::Cli.setup_admin_user

Kemal.run
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ services:
build: .
environment:
ENV: production
ADMIN_NAME: 'Tester'
ADMIN_API_KEY: '0p+mDvbpZGLPGVCXnV+EDduR9Blkv27Dhq9XSzSbdQY='
ports:
- 4000:4000
volumes:
Expand Down

0 comments on commit dfb6b10

Please sign in to comment.