Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modyfying before_action

I have an admin:boolean field in my user model, and would like to be able to to check in my controller if the user is an admin before they can edit anything.

How would I modify before_action :authenticate_user!, only: [:edit] to check if the user is an admin?

like image 209
Colton Seal Avatar asked Dec 08 '25 04:12

Colton Seal


1 Answers

You can add another before action that will be called after authenticate_user! to check if current user has admin privilege.

class YourController
  # first call authenticate_user! to check if user is signed in
  before_action authenticate_user!, only: [:edit]
  # if user is signed (current_user exist), check if he is admin
  before_action authenticate_admin!, only: [:edit]

  def authenticate_admin!
    # check if current user is admin
    unless current_user.admin
      # if current_user is not admin redirect to some route
      redirect_to 'some_public_route'
    end
    # if current_user is admin he will proceed to edit action
  end
end
like image 106
Nermin Avatar answered Dec 10 '25 23:12

Nermin