roysathome.net/auth/auth.rb

82 lines
1.7 KiB
Ruby
Raw Normal View History

2023-12-11 00:31:30 +00:00
# Install Sinatra: gem install sinatra
2023-12-11 20:56:09 +00:00
require_relative "initialize_database"
require_relative "database_queries"
require_relative "cryptography"
2023-12-11 00:31:30 +00:00
require 'sinatra'
require 'json'
require 'sqlite3'
require 'jwt'
payload = { data: 'test', test: 'hello' }
hmac_secret = 'my$ecretK3y'
token = JWT.encode payload, hmac_secret, 'HS256'
2023-12-11 20:56:09 +00:00
#puts token
2023-12-11 00:31:30 +00:00
decoded_token = JWT.decode token, hmac_secret, true, { algorithm: 'HS256' }
2023-12-11 20:56:09 +00:00
#puts decoded_token
2023-12-11 00:31:30 +00:00
2023-12-11 20:56:09 +00:00
initialize_database
2023-12-11 00:31:30 +00:00
# Define a simple API endpoint
get '/api/greeting' do
content_type :json
{ greeting: 'Hello, World!' }.to_json
end
get '/api/greeting/:name' do
2023-12-11 20:56:09 +00:00
get_claims params[:name]
2023-12-11 00:31:30 +00:00
content_type :json
{ greeting: "Hello, #{params[:name]}!" }.to_json
end
2023-12-11 20:56:09 +00:00
post '/auth/login' do
username = params[:username]
password = params[:password]
request_hashed_password = hash_password password
user_id = get_user_id username
hashed_password = get_user_hashed_password user_id
puts hashed_password
puts request_hashed_password
unless hashed_password == request_hashed_password
status 401
'Unauthorized Access'
end
2023-12-11 00:31:30 +00:00
content_type :json
2023-12-11 20:56:09 +00:00
{ jwt: "Logged in" }.to_json
2023-12-11 00:31:30 +00:00
end
def get_jwt (username, expiry_time)
2023-12-11 20:56:09 +00:00
get_claims username
2023-12-11 00:31:30 +00:00
end
def get_claims (username)
2023-12-11 20:56:09 +00:00
puts "Getting claims for #{username}"
2023-12-11 00:31:30 +00:00
db = SQLite3::Database.new('./database/auth.db')
2023-12-11 20:56:09 +00:00
results = db.execute('
SELECT C.claim
FROM users U
INNER JOIN user_claims UC ON U.id = UC.user_id
INNER JOIN claims C ON UC.claim_id = U.id
WHERE u.username = ?
', username)
if results.empty?
puts 'No claims found.'
else
results.each do |column|
puts "#{column[0]}"
end
end
return results
2023-12-11 00:31:30 +00:00
end
# Run the application
# ruby your_file_name.rb