Skip to content

Instantly share code, notes, and snippets.

@luckyruby
Last active August 29, 2015 13:59
Show Gist options
  • Save luckyruby/10777711 to your computer and use it in GitHub Desktop.
Save luckyruby/10777711 to your computer and use it in GitHub Desktop.
Simple Role-based Authorization in Rails
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
class FooController < ApplicationController
before_action :authenticate_user!
before_action { authorize! 'Foo' }
def bar
end
end
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