1
votes

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

1
Look for "devise-token_authenticatable" gem. It's what you need - Sergio Tulentsev
@SergioTulentsev Thank you, however I'd like to stick with the way I'm currently generating authentication tokens which is completely separate from Devise. I'd simply like to use Devise for the creation of users and user sessions. I need advise on setting up Devise to handle these JSON requests. - Lee Rowbotham
In this case, you should be able to simply subclass corresponding devise controllers and add your json handling - Sergio Tulentsev

1 Answers

1
votes

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.