Reputation: 95
I've created a Rails 4 app using the rails-api gem. I have my application controller which inherits from ActionController::API.
My routes file:
namespace :api do
namespace :v1 do
devise_for :users
resources :friends
end
end
I have a user model which I have ran a migration to add devise attributes. The user model also has attributes which are not specific to devise, such as first_name and last_name.
I then have a token_authentication model which stores the users token.
I'd like to use the current version of Deivse for the registration / sessions / authentication of users in my app.
My question is how can I use Devise registration controllers / session controllers to accept JSON format, create a user / session and send a JSON response. I want to enforce user authentication on every request to the API, except for a User create action. I'd need to be able to add in my token code in to Devise so that on the creation of users it also created a token, and on the sessions / authentication it checked for the token.
Any help or suggestions would be greatly appreciated.
If there's any additional info I can provide to help understand my issue, please let me know.
Many thanks
Lee
Upvotes: 2
Views: 4051
Reputation: 156
I used to do like this.
First you need override the devise controller.
# Override the devise session and registration controller to do like this.
resource.generate_auth_token!
Then write your own authenticate method.
# Authenticate user.
def current_user
@current_user ||= User.where(private_token: token).first
end
def authenticate!
render json:{error:'401 Unauthorized!'},status: 401 unless current_user
end
But then i found the devise_token_auth. I think they do better.
Upvotes: 1