Reputation: 165
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: 'john@gmail.com',
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'
}
Upvotes: 1
Views: 742
Reputation: 165
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
Upvotes: 2