Users & Auth
This commit is contained in:
23
app/commands/authenticate_user.rb
Normal file
23
app/commands/authenticate_user.rb
Normal file
@ -0,0 +1,23 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class AuthenticateUser < Imperator::Command
|
||||
include ActiveModel::Validations
|
||||
|
||||
string :email
|
||||
string :password
|
||||
|
||||
validates :email, presence: true
|
||||
validates :password, presence: true
|
||||
|
||||
def action
|
||||
JsonWebToken.encode(user_id: user.id) if user
|
||||
end
|
||||
|
||||
def user
|
||||
user = @user ||= User.find_by(email: @email)
|
||||
return user if user&.authenticate(@password)
|
||||
|
||||
errors.add :user_authentication, 'invalid credentials'
|
||||
nil
|
||||
end
|
||||
end
|
37
app/commands/authorize_request.rb
Normal file
37
app/commands/authorize_request.rb
Normal file
@ -0,0 +1,37 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class AuthorizeRequest < Imperator::Command
|
||||
include ActiveModel::Validations
|
||||
|
||||
attr_reader :headers
|
||||
|
||||
def initialize(headers)
|
||||
@headers = headers
|
||||
end
|
||||
|
||||
def action
|
||||
user
|
||||
end
|
||||
|
||||
def valid?
|
||||
headers["Authorization"].present?
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def user
|
||||
@user ||= User.find(decoded_auth_token[:user_id]) if decoded_auth_token
|
||||
@user || errors.add(:token, 'Invalid token') && nil
|
||||
end
|
||||
|
||||
def decoded_auth_token
|
||||
@decoded_auth_token ||= JsonWebToken.decode(http_auth_header)
|
||||
end
|
||||
|
||||
def http_auth_header
|
||||
return headers["Authorization"].split(' ').last if valid?
|
||||
|
||||
errors.add(:token, "Missing token")
|
||||
nil
|
||||
end
|
||||
end
|
Reference in New Issue
Block a user