0
votes

I have a Rails 5 app with the Devise gem installed. My project is set up in such a way, that all controllers are namespaced...Even Devise controllers.

In my routes file I have done this(This will better explain my namespacing structure):

controllers: {
    sessions: "api/v1/public/members/users/sessions",
    passwords: "api/v1/public/members/users/passwords",
    registrations: "api/v1/public/members/users/registrations",
},
path_names: { 
  sign_in: 'login', 
  password: 'forgot', 
  sign_up: 'register',
  sign_out: 'signout'
}

I have also setup the devise view files to reflect the required namespaced structure.

I have included the following in my ApplicationController.rb:

before_action :authenticate_api_v1_public_members_user!

Since my Devise controllers are namespaced, the standard 'before_action :authenticate_user!' method needed to be updated to the one above in order to work.

The issue that I'm experiencing, is that none of the Devise helper methods are available in any of my views. When calling 'current_user' or 'user_signed_in?' in a view, I am presented with an 'undefined method' error when refreshing my browser. I tried namespacing these helper methods as well, but to no avail.

UPDATE Models are not namespaced in my app. I am using a normal User model. Only controllers are namespaced and are structured as indicated by the route above.

Does anybody have experience with a similar issue?

1
:authenticate_api_v1_public_members_user! It looks very weird! This Devise helper should have nothing to do with your namespaces. The name of the method depends of the name of your user model. From your example I may gess that your user model is ApiV1PublicMemberUser - chumakoff
I got the tip for a namespaced authenticate method here: stackoverflow.com/a/29409283/1933068 . I have also updated my question to explain the Model @chumakoff - HermannHH
If it really works this way, you must use methods current_api_v1_public_members_user! and api_v1_public_members_user_signed_in? instead of current_user! and user_signed_in? - chumakoff
Wow your suggestion actually worked. I did something similar before, but my word sequence was incorrect. Can you please add this as an answer so that I can mark it as accepted. Thanks @chumakoff - HermannHH
I am very surprised that it works like this. Got something new to know. Thank you! I created an answer - chumakoff

1 Answers

1
votes

It seems to be that Devise is nested within the :api_v1_public_members namespace in your routes.rb. In this case it affects not only on authenticate_user! method, changing it into authenticate_api_v1_public_members_user!, but on the others methods too.

  • current_user turns to current_api_v1_public_members_user

  • user_signed_in? turns to api_v1_public_members_user_signed_in?

There is similar problem here undefined method `authenticate_user! Api::PostsController in Devise / Rails 4