Search code examples
ruby-on-railsdevisepundit

Multiple users authenticating and authorizing


I am a bit confused with Authorizing and Authenticating at the moment.

First I need to tell you about my project. It will have two main models: Users and Pros. Users are people requesting a service. Pros are people offering services. Pros can have very different jobs and thus very different type of data stored in my project. I plan to have different models for different types of jobs held by the Pros (photographers, wedding planners..). Those models will have relationships and "own" different other models (images added with paperclip, links to websites...).

I guess I need to use gems for both Authentication and Authorizing (I have Devise and Pundit in mind)

now my questions:

  • I would like to have all Users and Pros login through the same form. I guess this is very a Devise thing. Though after having read a bit about Devise, it seems there is a login for each of the Models. but this thread mentions Devise "groups"
    https://gorails.com/forum/devise-with-multiple-user-models-with-single-login-form Will it definitely solve my problem of a single form login ?

  • I would like to have each of the Pros submodels show a preview of their records to any type of users or even guests. But when a Pro is logged in they can access to an extended profile view with more information (all personnal data that can be changed, price requests from users, etc...). Can you confirm this is Pundit job here ?


Solution

  • Pundit is the perfect choice for achieving your second point. You can limit certain actions (such as edit/update) to be achievable only by the Pro who owns the account. The code for those actions in the ProPolicy would look something like:

    def edit?
      update?
    end
    
    def update?
      record.pro == user
    end
    

    In terms of your question about multiple user model authentication using Devise, can you explain why you are set on having just one login form for both users? You could have a dropdown on the login button where the user can select if he is a normal User or a Pro. Or you could even have a checkbox/select on the form where they select which type of login they want to use.

    If not, then you will somehow have to check your database to see if the login exists in either the Pro or User tables. However, I suppose that would mean that you cannot have both a Pro and a User account using the same email.