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

Rails + Devise - Is there a way to BAN a user so they can't login or reset their password?


I have a lot of users thanks to devise and I want to ban a few problem makers. Does Devise have this support built in?

Thanks


Solution

  • I just implemented this in my project myself. What I did was similar to Kleber above, I defined this in my app/controllers/sessions_controller.rb (overriding Devise)...

    class SessionsController < Devise::SessionsController
    
    protected
    
      def after_sign_in_path_for(resource)
        if resource.is_a?(User) && resource.banned?
          sign_out resource
          flash[:error] = "This account has been suspended for violation of...."
          root_path
        else
          super
        end
       end
    
    end
    

    And then I added a boolean column to Users called 'banned,' so the moderators check the checkbox when editing the user in the backend, and the boolean will return true.

    But there was one flaw...if a user was already logged in and then banned, they still had access to doing stuff on the site (comments, etc) at least until their session expired or they logged out. So I did this in the app/controllers/application_controller.rb...

    class ApplicationController < ActionController::Base
      before_filter :banned?
    
      def banned?
        if current_user.present? && current_user.banned?
          sign_out current_user
          flash[:error] = "This account has been suspended...."
          root_path
        end
      end
    end
    

    That'll automatically log them out if a ban is detected. Anyway, not sure this whole thing is the "best" way to factor the whole thing as I'm newer to Rails, but the whole thing works for me and hope it will at least give you a good start.