1
votes

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

1 Answers

1
votes

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