Search code examples
ruby-on-railsruby-on-rails-3devisecancan

How to access users who did not confirmed and those who confirmed (Rails/Devise/cancan/rolify)


I am building a daily deal app on Rails to train myself to Ruby on Rails.

I have installed authentication with devise/cancan/rolify.

I'd like to create in cancan two type of users

  • users who confirmed
  • users who did not confirmed yet

How can I achieve that ? how can I access on devise users who have and those who have not confirmed their account(i.e clicked on the activation link sent to them by email).


Solution

  • There is no need to add roles for confirmed and unconfirmed. You can use user.confirmed? in your ability.rb file to control authorization:

    # models/ability.rb
    
    if user.confirmed?
      can :manage, Model
    end
    
    if !user.confirmed?
      can :view, Model
    end
    

    Note: you can use an if/else construct, but I prefer to keep my rules nicely separated.

    In regards to your comments, you're reimplementing what's already been done. With cancan you can use load_and_authorize_resource (see: here).

    class ProductsController < ActionController::Base
      load_and_authorize_resource
    end
    

    That's it. The user will receive an "unauthorized" response if they try to access without the required permissions.

    I highly recommend you read through the documentation for rolify and cancan.