Created
July 22, 2020 17:16
-
-
Save bearded-avenger/cd4a3acc5affcfbb85008c46adc812da to your computer and use it in GitHub Desktop.
Simple Role based Authorization for Ruby on Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Roles Table | |
Role.create([{name:'admin'},{name:'staff'}]) | |
# Users Roles Table | |
UserRole.create(user: User.find_by_username('corndog'), role: Role.find_by_name('admin')) | |
# User Model | |
class User < ApplicationRecord | |
def role?(role) | |
role.kind_of?(Array) ? role.map { |role| has_role?(role) }.any? : has_role?(role) | |
end | |
def has_role?(role) | |
roles.any? { |r| r.name.underscore.to_sym == role } | |
end | |
end | |
# Helper Method - Check One Role | |
current_user.role?(:admin) | |
# Helper Method - Check Two Roles | |
current_user.role?([:admin, :staff]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment