devise icon indicating copy to clipboard operation
devise copied to clipboard

devise_for vs devise_scope routes

Open michaelirey opened this issue 12 years ago • 19 comments

Using devise (3.2.2)
Using rails (4.0.2)

Working on developing an API which only has the need for only certain routes. I have the following in my routes.rb:

devise_for :users, path: '/users', controllers: {
  sessions: 'v1/custom_devise/sessions',
  passwords: 'v1/custom_devise/passwords'
}

Great! Now we have all these routes:

              Prefix Verb    URI Pattern                    Controller#Action
    new_user_session GET     /users/sign_in(.:format)       v1/custom_devise/sessions#new
        user_session POST    /users/sign_in(.:format)       v1/custom_devise/sessions#create
destroy_user_session DELETE  /users/sign_out(.:format)      v1/custom_devise/sessions#destroy
       user_password POST    /users/password(.:format)      v1/custom_devise/passwords#create
   new_user_password GET     /users/password/new(.:format)  v1/custom_devise/passwords#new
  edit_user_password GET     /users/password/edit(.:format) v1/custom_devise/passwords#edit
                     PATCH   /users/password(.:format)      v1/custom_devise/passwords#update
                     PUT     /users/password(.:format)      v1/custom_devise/passwords#update

But I do not want or need these routes:

    new_user_session GET     /users/sign_in(.:format)       v1/custom_devise/sessions#new
   new_user_password GET     /users/password/new(.:format)  v1/custom_devise/passwords#new
  edit_user_password GET     /users/password/edit(.:format) v1/custom_devise/passwords#edit

So I thought I will just create my own routes as per the documentation. So I changed my routes.rb:

devise_scope :user do
  post   '/users/sign_in'  => 'custom_devise/sessions#create',  as: :user_session
  delete '/users/sign_out' => 'custom_devise/sessions#destroy', as: :destroy_user_session

  post  '/users/password'  => 'custom_devise/passwords#create', as: :user_password
  put   '/users/password'  => 'custom_devise/passwords#update', as: nil
  patch '/users/password'  => 'custom_devise/passwords#update', as: nil
end

Now my routes look perfect, just the way I want them:

              Prefix Verb    URI Pattern                   Controller#Action
        user_session POST    /users/sign_in(.:format)      v1/custom_devise/sessions#create
destroy_user_session DELETE  /users/sign_out(.:format)     v1/custom_devise/sessions#destroy
       user_password POST    /users/password(.:format)     v1/custom_devise/passwords#create
                     PUT     /users/password(.:format)     v1/custom_devise/passwords#update
                     PATCH   /users/password(.:format)     v1/custom_devise/passwords#update

But now my requests fail, with:

 AbstractController::ActionNotFound:
   Could not find devise mapping for path "/users/sign_in".
   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

   2) 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]

After debugging for some reason Devise.mappings[:user] is nil when using devise_scope, but is not nil when using devise_for.

I have tried many variations, to no avail.

michaelirey avatar Jan 22 '14 19:01 michaelirey

Can you pls paste the test?

josevalim avatar Jan 22 '14 19:01 josevalim

Here is an rspec test:

require 'spec_helper'

describe 'Users' do
  it "POST /users/sign_in" do
    post '/users/sign_in', { user: { email: "[email protected]", password: "badPassword"} }
    response.status.should eql(401)
  end
 end

Please note: I get the same response when using curl with rails s

michaelirey avatar Jan 22 '14 20:01 michaelirey

Hrm this is very weird. Note that the implementation of devise_scope does set the mapping:

https://github.com/plataformatec/devise/blob/master/lib/devise/rails/routes.rb#L342

Furthermore, devise_for simply uses devise_scope:

https://github.com/plataformatec/devise/blob/master/lib/devise/rails/routes.rb#L245

Can you pls provide a sample app that reproduces the error?

josevalim avatar Jan 22 '14 20:01 josevalim

https://github.com/michaelirey/devise_weird

Here is a sample app which demonstrates the issue:

Please note: https://github.com/michaelirey/devise_weird/blob/master/config/routes.rb#L9-13

Regarding the comment for: ### This one works!

You should be able to toggle back and forth between the 2 of them.

Test with curl -X POST --data 'user[email][email protected]&user[password]=pass' http://0.0.0.0:3000/users/sign_in

michaelirey avatar Jan 22 '14 20:01 michaelirey

It is raised because of https://github.com/plataformatec/devise/blob/master/app/controllers/devise_controller.rb#L58-L72

I tried your application and notice that you have a custom Session controller there, maybe you have to skip this check.

I think it's not a bug, since it's a custom implementation issue, so I'm closing this issue.

@michaelirey thanks for reporting.

laurocaetano avatar Apr 16 '14 21:04 laurocaetano

In case anyone else Googles their way here, I had something very similar come up, but my case involved namespaces altering the known scopes. I debugged it by adding: Devise.mappings.each { |k, v| puts "scope: #{k}, mapping: #{v} } at https://github.com/plataformatec/devise/blob/master/lib/devise/rails/routes.rb#L344 This exposed that the correct scope for my model "Model" within namespace "Space" was actually :space_model, and not not just :model. However, for devise_for it seems I still need to use :models and not :space_models because that is the actual model name.

rokob avatar May 15 '14 20:05 rokob

I personally ran into the same issue while customising Devise to do json stuff for an API, hence defining only custom routes through devise_scope. It seems that the mapping is added here https://github.com/plataformatec/devise/blob/master/lib/devise/rails/routes.rb#L224 in devise_for, but never in devise_scope. A quick&dirty fix consists of adding devise_for :users, skip: [ :sessions, :registrations, :passwords ] (in my case), basically, skipping everything, just so that the mapping gets correctly added, and then define my custom routes through devise_scope. I can try to provide a clean patch in case you guys are interested.

Also, thanks for providing Devise!

beauby avatar Aug 02 '14 18:08 beauby

Is the patch available?

kithokit avatar Nov 10 '14 08:11 kithokit

@kithokit There is actually no need for a patch. Just make sure you do call devise_for before you declare any custom route (if you do not want to use any of the default routes, juste use skip: :all).

beauby avatar Nov 10 '14 17:11 beauby

@beauby could you paste an a code example of what you mean?

dilizarov avatar Dec 18 '14 00:12 dilizarov

@dilizarov Just do

devise_for :users, skip: :all
devise_scope :user do
   # custom routes here
end

Note that the resource is plural for devise_for but singular for devise_scope.

beauby avatar Dec 21 '14 20:12 beauby

@beauby I'm using rails-api to generate json apis so when I add devise_for :users skip: :all I get the following error

=> Booting WEBrick
=> Rails 4.2.1 application starting in development on http://localhost:3000 
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Exiting
/home/pamio/.rvm/gems/ruby-2.1.1/gems/devise-3.2.4/lib/devise/rails/routes.rb:455:in `ensure in   with_devise_exclusive_scope': undefined method `merge!' for #<ActionDispatch\
::Routing::Mapper::Scope:0x000000071ce380> (NoMethodError)
    from /home/pamio/.rvm/gems/ruby-2.1.1/gems/devise-3.2.4/lib/devise/rails/routes.rb:455:in  `with_devise_exclusive_scope'
    from /home/pamio/.rvm/gems/ruby-2.1.1/gems/devise-3.2.4/lib/devise/rails/routes.rb:246:in `block  (2 levels) in devise_for'
     from /home/pamio/.rvm/gems/ruby-2.1.1/gems/devise-3.2.4/lib/devise/rails/routes.rb:349:in `block in devise_scope'

Any ideas ??

pamio avatar Aug 03 '15 05:08 pamio

@pamio please update your devise version, official support for Rails 4.2 was released on v3.4.

carlosantoniodasilva avatar Aug 03 '15 10:08 carlosantoniodasilva

@carlosantoniodasilva thanks for the update. It solved my problem.

pamio avatar Aug 05 '15 05:08 pamio

This should help anyone in 2016 http://stackoverflow.com/questions/22063026/how-do-i-override-devise-controller-and-devise-routes-at-the-same-time

theterminalguy avatar Apr 28 '16 19:04 theterminalguy

anyone still facing this issue even after doing

devise_for :users, skip: :all devise_scope :user do end

please refer to this issue https://github.com/plataformatec/devise/issues/2496#issuecomment-20645182 if you're calling devise_scope inside a namespace.

zhoplocal avatar Apr 19 '17 19:04 zhoplocal

yes I am also facing the same issue, I am having devise-4.3.0 and rails-5.1.0

kartikupadhyay90 avatar May 29 '17 08:05 kartikupadhyay90

For reference, this is how I solved the issue about Could not find devise mapping for path..., which is a bit different to the solution referenced in https://github.com/plataformatec/devise/issues/2840#issuecomment-295402383 by @zhoplocal.

In my case I'm exposing Devise within an API and everything is namescoped into /api/v1. The problem was that I called devise_for :users also within the namescope, which didn't work:

namespace :api do
  namespace :v1 do
    devise_for :users, skip: :all
    devise_scope :user do
      post 'users', to: 'registrations#create', as: nil
    end
  end
end

Moving the devise_for :users call outside of the namespacing, allowed my custom controllers to work:

# DOC: https://github.com/plataformatec/devise/blob/v4.3.0/lib/devise/rails/routes.rb#L33
devise_for :users, skip: :all

namespace :api do
  namespace :v1 do
    devise_scope :user do
      post 'users', to: 'registrations#create', as: nil
    end
  end
end

# Used in the signup email by devise to confirm the signup.
get '/signup/confirm', to: 'custom_controller#some_action', as: :user_confirmation

Note that the corresponding controller registrations will be expected under the according namespace, i.e. class Api::V1::RegistrationsController < Devise::RegistrationsController in the file /app/controllers/api/v1/registrations_controller.rb. Also, I had to manually provide a route prefixed user_confirmation, so that the default confirmation email can be generated.

For what is worth, this was working for me as in the first example, i.e. with the devise_for :users call inside of the namespacing and with the confirm path prefixed as as: :api_v1_user_confirmation. Sadly I'm not sure what I did change that broke this setup and I had to move the devise_for :users call outside of the namespacing. Maybe it's related to the fact that I'm using Doorkeeper as well within the same namescope, but I was unable to isolate the cause.

Thanks to all the commenters above! 👍

rbf avatar Nov 06 '17 10:11 rbf

@rbf Thanks for your solution! Moving the devise_for :users call outside of the namespacing worked for me. I also have a Rails API project. This configuration should be documented by Devise!

My routes.rb file looks like this now:

Rails.application.routes.draw do
  devise_for :admin_users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
  
  # API Endpoints
  api_version(module: 'api/v1', path: { value: 'api/v1' }, defaults: { format: :json }) do
    ...
    namespace :users do
      resource :profile, only: [:show, :update]
      ...
    end
    resources :users, only: [:create] do
      collection do
        resources :notifications, only: [:index, :update]
        resources :sessions, only: [:create]
        ... 
        get :show
        put :update
      end
    end

    devise_scope :user do
      post 'users/password', to: 'users/passwords#create'
      put 'users/password', to: 'users/passwords#update'
      post 'users/confirmation', to: 'users/confirmations#create'
      get 'users/client_auth/google', to: 'users/omniauth_client#google'
      get 'users/client_auth/facebook', to: 'users/omniauth_client#facebook'
      get 'users/client_auth/microsoft', to: 'users/omniauth_client#microsoft'
      get 'users/client_auth/twitter_callback', to: 'users/omniauth_client#twitter_callback'
      post 'users/client_auth/twitter_callback', to: 'users/omniauth_client#twitter_callback'
      get 'users/client_auth/twitter_request_token', to: 'users/omniauth_client#twitter_request_token'
      post 'users/client_auth/twitter_request_token', to: 'users/omniauth_client#twitter_request_token'
    end
  end

  devise_for :users, skip: :all, path_prefix: 'api/v1', controllers: {
    omniauth_callbacks: 'api/v1/users/omniauth_callbacks'
  }
end

ghost avatar Jul 11 '18 02:07 ghost