roysathome.net/auth/auth.rb

81 lines
2.0 KiB
Ruby

# Install Sinatra: gem install sinatra
require 'sinatra'
require 'json'
require 'sqlite3'
require 'jwt'
payload = { data: 'test', test: 'hello' }
hmac_secret = 'my$ecretK3y'
token = JWT.encode payload, hmac_secret, 'HS256'
puts token
decoded_token = JWT.decode token, hmac_secret, true, { algorithm: 'HS256' }
puts decoded_token
#########
# Check if the directory exists
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')
db.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, hashed_password 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)')
db.execute('INSERT INTO claims (claim) VALUES (?)', 'add_user')
db.execute('INSERT INTO claims (claim) VALUES (?)', 'remove_user')
# Check if the users table is empty
result = db.get_first_value('SELECT COUNT(*) FROM users')
if result == 0
db.execute('INSERT INTO users (username, hashed_password) VALUES (?, ?)', ['admin', 'password'])
puts 'Default admin user added.'
else
puts 'Table already contains data. Skipping default user creation.'
end
results = db.execute('SELECT * FROM users')
results.each do |row|
puts "ID: #{row[0]}, Username: #{row[1]}, Hashed Password: #{row[2]}"
end
##############
# Define a simple API endpoint
get '/api/greeting' do
content_type :json
{ greeting: 'Hello, World!' }.to_json
end
get '/api/greeting/:name' do
content_type :json
{ greeting: "Hello, #{params[:name]}!" }.to_json
end
post '/auth' do
content_type :json
{ jwt: }
end
def get_jwt (username, expiry_time)
claims = []
end
def get_claims (username)
db = SQLite3::Database.new('./database/auth.db')
db.execute('')
end
# Run the application
# ruby your_file_name.rb