Implement Rails account BAN

Implement forced logout

Even on twitter and instagram, my account is banned and I can not log in ... I hope I don't have that experience, This time I would like to implement such a function.

First, prepare a user model with the attribute suspended (boolean) as user. Users with this stop flag set to true cannot log in and We will create a function that denies access to other pages and forces you to log out.

First, implement a method to see if the user model has a stop flag. It seems that you do not have to bother to prepare it as a method, but consider extensibility and create a method as a model.

app/models/user.rb


class User < ApplicationRecord


#abridgement

#Are you an active user?
private
  def active?
    !suspended?
  end
end

Now change the base controller class. If user is logged in and the stop flag is set I deleted the session and forcibly redirected to the top page.

app/controllers/user/base.rb


class User::Base < ApplicationController
  before_action :check_account
  
  private
    def current_user
      if session[:user_id]
        @current_user ||= User.find_by(id: session[:user_id])
      end
    end

  private
    def check_account
      #When user is logged in and the stop flag is set
      if current_user && !current_user.active?
        #Delete session
        session.delete(:user_id)
        flash.alert = "Account has become invalid"
        #Redirect to top page
        redirect_to :user_root
      end
    end
end

By calling the check_account method with before_action for all actions You can force a logout for a user who is flagged as stopped.

That's all for today. Thank you for reading to the end.

Recommended Posts

Implement Rails account BAN
Implement Rails pagination
[Rails] Implement search function
[Rails] Implement rake task
Implement markdown in Rails
Implement application function in Rails
[Rails] Implement User search function
Implement LTI authentication in Rails
Implement import process in Rails
[Rails] How to implement scraping
[Rails] Implement image posting function
Implement simple login function in Rails
Implement a contact form in Rails
[Rails] How to implement star rating
Implement CSV download function in Rails
How to implement search functionality in Rails
How to implement ranking functionality in Rails
[Rails] Implement star rating (input, save, display)
How to implement image posting using rails
Implement button transitions using link_to in Rails
11.2 Send Account Activation Email: Rails Tutorial Notes--Chapter 11