Last active
August 29, 2015 13:59
-
-
Save luckyruby/10777711 to your computer and use it in GitHub Desktop.
Simple Role-based Authorization in 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
class ApplicationController < ActionController::Base | |
protect_from_forgery with: :exception | |
def authorize!(*roles) | |
unless current_user.allowed?(roles) | |
render text: 'You are not authorized to view this page' | |
end | |
end | |
end |
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
class FooController < ApplicationController | |
before_action :authenticate_user! | |
before_action { authorize! 'Foo' } | |
def bar | |
end | |
end |
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
class User < ActiveRecord::Base | |
ROLES = %w(Superadmin Admin Foo) #do not ever change order | |
def roles=(roles) | |
self.roles_mask = (roles & ROLES).map {|r| 2**ROLES.index(r)}.sum | |
end | |
def roles | |
ROLES.reject {|r| ((roles_mask || 0) & 2**ROLES.index(r)).zero?} | |
end | |
def role?(role) | |
roles.include? role.to_s | |
end | |
def admin? | |
(['Superadmin', 'Admin'] & roles).present? | |
end | |
def allowed?(allowed_roles) | |
admin? || (roles & allowed_roles).present? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment