Users & Auth

This commit is contained in:
2018-11-10 18:46:47 -06:00
parent 904a071fc0
commit 8a7b3d8ae0
26 changed files with 663 additions and 14 deletions

View 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

View 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