Search code examples
ruby-on-railsrubysessiondevisecancan

Rails, Devise multiple models login and their sessions


I have two models that are generated by devise: Partner and Admin. Each of them has their own sessions currents and etc. Some controllers require only Admin that logged in, some controllers require either Partner or Admin to be logged in.

There is :authenticate_admin! and :authenticate_partner! methods that will be called in my controllers before_action.

I also use CanCanCan to define both of them roles.

That gives multiple questions:

  1. If I logged in as Partner then I opened page where Admin must be logged in and I logged in, that means that I will have two sessions at once?
  2. I logged in as Partner when I am also Admin, that mens I need to destroy session of Admin. How to make Devise to destroy other model sessions when current model is logged in?
  3. Do I need to add something like this in controller where or Admin or Partner is needed?

    before_action :authenticate_partner!
    before_action :authenticate_admin!
    
  4. And the last question is: how I can make Partners open pages (that means access controllers) only that is allowed by CanCanCan ?

I wanted to use authorize_resource, it asks only one model per controller.


Solution

    1. Yes. There are two independent devise scopes for each model, using different session variables.
    2. Devise does not destroy a scope session when you sign in the other scope, but you can do it manually. There is devise method sign_out(scope). In your case, you can call sign_out(:partner) and sign_out(:admin) when you need it. There also must be methods like this sign_out_partner, sign_out_admin, automatically provided for your scopes by Devise. Also, pay attention to config.sign_out_all_scopes devise option.
    3. Yes, those filters restrict access to the controller's actions.
    4. I hope this will help How to integrate CanCan with multiple devise models?