Skip to content

Manage User Roles

Jan Westphal edited this page Dec 17, 2018 · 4 revisions

This page describes how to manage the user roles: user, employee, admin

Check for user role everywhere in code

  • <user>.user?
  • <user>.employee?
  • <user>.admin?

Note: the checks are exclusive

Restrict user access for role in controller

  • define before_action
  • currently available are: authenticate_user! (checks if any user is logged in), authenticate_employee, authenticate_admin

Example:

class Controller < Application
   before_action :authenticate_admin

   def authenticate_admin
      redirect_to root_path, alert: I18n.t('authorization.unauthorized') unless current_user&.admin?
   end
end

Note: If you want to skip an action defined by a parent controller use: skip_before_action :<action>

Restrict user access for role for specific path of controller

  • e.g. show and edit should be only accessable by admins
class Controller < Application
   before_action :authenticate_admin only: [:show, :edit]

   # controller methods

   def authenticate_admin
      redirect_to root_path, alert: I18n.t('authorization.unauthorized') unless current_user&.admin?
   end
end

Check if logged in user is requested user

  • <user> == current_user

A controller method could look like this:

  def authenticate_current_user
    @user = User.find(params[:id])
    redirect_to @user unless current_user == @user
  end