Reputation: 2018
I have the following namespaces ApiController
class Api::ApiController < ApplicationController
skip_before_action :verify_authenticity_token,
if: Proc.new { |c| c.request.content_type == 'application/json' }
before_action :authenticate
attr_reader :current_user
private
def authenticate
@current_user = AuthorizeApiRequest.call(request.headers).result
render json: { error: 'Not Authorized' }, status: 401 unless @current_user
end
end
On AuthorizeApiRequest.call
, Rails complains that:
uninitialized constant Api::ApiController::AuthorizeApiRequest
My AuthorizeApiRequest class is defined under app/commands:
class AuthorizeApiRequest
prepend SimpleCommand
def initialize(headers = {})
@headers = headers
end
def call
user
end
private
attr_reader :headers
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
if headers['Authorization'].present?
return headers['Authorization'].split(' ').last
else
errors.add(:token, 'Missing token')
end
nil
end
end
So it seems to not allow me to call AuthorizeApiRequest.call
without added namespace to front. How to fix?
Upvotes: 1
Views: 1180
Reputation: 368
Your app/commands
folder doesn't seem to be loaded into Rails at boot.
You need to include your app/commands
in your autoload paths for this to work or require the file manually in your controller.
See: https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoload-paths
Upvotes: 0