Reputation: 3400
I want to allow access to a resource only when the authorization token contained in the HTTP headers matches token stored in the users table. i'm using curl as shown below to access the resource:
$ curl http://localhost:3000/api/v1/tasks.json -H 'Authorization: Token token="S8S4MPqFNdDz3G1jLsC9"'
in the tasks#index
method i would like to check whether the token above matches the current user's authentication token stored in the database.
How can i get the token value as an instance variable so that i can use it as shown below:
def index
@token = ???
if User.exists?(:authentication_token => @token)
### code to access the resource
else
authenticate_user!
end
end
Upvotes: 0
Views: 319
Reputation: 3400
From this railscast, I have found the best solution is to use rails authenticate_or_request_with_http_token
method like this:
class Api::V1::TasksController < ApplicationController
before_filter :restrict_access
respond_to :json
def index
@user = User.where("users.authentication_token IS NOT NULL").first
@tasks = @user.tasks
end
private
def restrict_access
authenticate_or_request_with_http_token do |token, options|
User.exists?(authentication_token: token)
end
end
Upvotes: 1