1

I currently have an API set up with token authentication. I have a parent class ApiController that my other API controllers inherit from that contains the following:

class ApiController < ApplicationController
  protect_from_forgery with: :null_session

  protected 
    def authenticate
      authenticate_token || render_unauthorized
    end

    def authenticate_token
      authenticate_with_http_token do |token, options|
        User.find_by(auth_token: token)
      end
    end

    def render_unauthorized
      self.headers['WWW-Authenticate'] = 'Token realm="Users"'
      render json: 'Bad credentials', status: 401
    end
end

In my API controllers I just set before_action :authenticate to make sure it's a valid request from a user with an auth_token.

I sometimes need the user that issued the request, for example, when following a user I need to make the user that made the request follow another user, looking at what I have how can I set it up so in my controller I can access the user that made the request?

1 Answer 1

1

You can set an instance variable that will be accessible by your Controller in your authenticate_token method. As such

 @current_user = User.find_by(auth_token: token)

Then, for example, the Controller::Action you define to "follow" a user can use @current_user.

 def follow()     
   @current_user.follow (another_user)
 end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.