1

I have a rails API using Devise. When you hit the POST /login endpoint, it logs the user in and provides a JWT. This was all working fine until I recently moved to namespace my controllers with a version. This is what my sessions#create method looks like:

def create
    self.resource = warden.authenticate!(auth_options)

    set_flash_message!(:notice, :signed_in)
    sign_in(resource_name, resource)
    yield resource if block_given?

    render json: current_user
  end

When making a login request from the front end, this what my parameters look like:

{
    user: {
        email: '[email protected]',
        password: 'password'
    }
}

This was working before, but now that I've migrated to a Api::V1 namespace for my sessions controller, it requires the front end to submit credentials under :api_v1_user instead of :user.

Is there a way I can change my sessions#create function to look at the :user attribute and not :api_v1_user?

UPDATE

  namespace :api do
namespace :v1 do
    devise_for :users,
       path: '',
       path_names: {
         sign_in: 'login',
         sign_out: 'logout',
         registration: 'signup'
       },
       controllers: {
         sessions: 'api/v1/sessions',
         registrations: 'api/v1/registrations'
       }
2
  • can you share your routes ? Commented May 27, 2019 at 5:29
  • Updated the post Commented May 28, 2019 at 0:17

1 Answer 1

2

Okay I figured it out. It feels hacky, but it works. Here is what I changed my Api::V1::SessionsController create method to:

  def create
    # Changing scope from :api_v1_user to :user
    Devise.mappings[:user] = Devise.mappings[:api_v1_user]
    warden.config[:default_strategies][:user] =  warden.config[:default_strategies].delete(:api_v1_user)
    auth_opts = auth_options
    auth_opts[:scope] = :user

    self.resource = warden.authenticate!(auth_opts)

    set_flash_message!(:notice, :signed_in)
    sign_in(resource_name, resource)
    yield resource if block_given?

    render json: current_api_v1_user
  end
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I've been trying to fix this issue for two days and getting nowhere!
any ideas on how to resolve NoMethodError (undefined method `jwt_subject' for :api_v1_user:Symbol):?

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.