SJU
SJU

Reputation: 3272

Add custom routes to devise returns 404 ActionNotFound

I would like to create a new routes and method inside my Sessions Controller within Devise. I am using devise_token_auth

Here is my original routes.rb for devise :

namespace :api do
    namespace :v1 do
      mount_devise_token_auth_for 'User', as: 'user', at: 'auth', controllers: {
        token_validations:  'api/v1/users/token_validations',
        confirmations:      'api/v1/users/confirmations',
        registrations:      'api/v1/users/registrations',
        passwords:          'api/v1/users/passwords',
        sessions:           'api/v1/users/sessions'
      }
    end
end

which give me these classic routes :

new_api_v1_user_session GET          /api/v1/auth/sign_in(.:format)                   api/v1/users/sessions#new
api_v1_user_session POST             /api/v1/auth/sign_in(.:format)                   api/v1/users/sessions#create
destroy_api_v1_user_session DELETE   /api/v1/auth/sign_out(.:format)                  api/v1/users/sessions#destroy
new_api_v1_user_password GET         /api/v1/auth/password/new(.:format)              api/v1/users/passwords#new
edit_api_v1_user_password GET        /api/v1/auth/password/edit(.:format)             api/v1/users/passwords#edit
....

I have also inside my directory tree :

controllers
-- api
--- v1
----users
----- confirmations_controller.rb
----- passwords_controller.rb
----- registrations_controller.rb
----- sessions_controller.rb

Now I want to create a new custom method and routes inside the sessions controller for connected people. I want this new route : /api/v1/auth/token

So here is what I add to my routes :

devise_scope :user do   
    post '/auth/tokens', to: 'users/sessions#tokens'
end

And the result when I do rails routes, which looks fine :

api_v1_auth_tokens POST   /api/v1/auth/tokens(.:format)                    api/v1/users/sessions#tokens

But in Postman when I call POST {url}/api/v1/auth/tokens I get the classic 404 error AbstractController::ActionNotFound.

[Devise] Could not find devise mapping for path "/api/v1/auth/tokens". This may happen for two reasons:

  1. You forgot to wrap your route inside the scope block. For example:

devise_scope :user do get "/some/route" => "some_devise_controller" end

  1. You are testing a Devise controller bypassing the router. If so, you can explicitly tell Devise which mapping to use:

    @request.env["devise.mapping"] = Devise.mappings[:user]

Completed 404 Not Found in 1ms (ActiveRecord: 0.0ms | Allocations: 110)

But I am doing what the hint is telling me. What am I missing ?

Upvotes: 1

Views: 126

Answers (0)

Related Questions