I want to use Devise with two namespaces: an API namespace, and the default namespace,
but the two seem to be conflicting when a user tries to sign in.
Meaning, whichever namespace that references Devise first ends up
being the final redirection place. Ex: If I try to create a new session
under the default namespace it will fail on that user session path,
and then attempt to create the session on the API/v1 sessions path.
How do I make the two act independently?
They are both referencing a User object. The user_sessions controller
for the default namespace is ‘user_sessions’. The user_sessions
controller for the API/V1 namespace is ‘/api/v1/user_sessions’
---- ROUTES.RB -------
MySite::Application.routes.draw do
namespace :api do
namespace :v1 do
devise_for :users,:controllers => { :sessions => "api/v1/
user_sessions",:registrations=>"users" }
......
end
end
devise_for :users,:controllers => { :sessions =>"user_sessions",:registrations=>"users" } do
post 'users/sign_in' => 'user_sessions#create', :as => :user_session
get 'users/sign_in' => 'user_sessions#new', :as => :new_user_session
get 'users/sign_up' => 'user_sessions#new', :as => :new_user_session
match 'users/sign_out' => 'user_sessions#destroy', :as => :destroy_user_session
<.....>
end
—– DEFAULT NAMESPACE USER_SESSIONS_CONTROLLER —–
class UserSessionsController < Devise::SessionsController
....
end
----
API NAMESPACE USER_SESSIONS_CONTROLLER —- (this goes to my custom Devise base controller marked below)
class Api::V1::UserSessionsController < Api::V1::DeviseBaseController
...
end
—- API NAMESPACE CUSTOM DEVISE BASE CONTROLLER —-
class Api::V1::DeviseBaseController < Devise::SessionsController
respond_to :json
end
I found out that this isn’t possible with Devise, you have to have one sign-in/sign out source.
Clean solution: Create routes for both your API and Web namespaces that point back to the same Devise controller code (say, /user/sessions). In there, call partials for the appropriate response (JSON, HTML). Those partials can sit in the view directories for each namespace, keeping things clean.