micro-blogger/app/commands/authorize_request.rb
2018-11-10 20:34:11 -06:00

38 lines
705 B
Ruby

# 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