Skip to content

Instantly share code, notes, and snippets.

@bcalloway
Created March 2, 2010 19:40
Show Gist options
  • Save bcalloway/319833 to your computer and use it in GitHub Desktop.
Save bcalloway/319833 to your computer and use it in GitHub Desktop.
Super Simple Role-Based Authorization
class ApplicationController < ActionController::Base
helper :all
protect_from_forgery
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user, :role_call
before_filter :start_session
def check_authorization(vars)
unless "#{vars}".include?(role_call)
flash[:error] = "You are not authorized to access this!"
redirect_to("/account/#{current_user.id}")
end
end
# Determine the role of the current user based on the current user's role_id
def role_call
@role = Role.find(current_user.role_id)
return "#{@role.name}"
end
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
# Helper method to determine the current logged-in user based on the user session
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
def require_user
unless current_user
store_location
flash[:error] = "You must be logged in to access this page"
redirect_to new_user_session_url
return false
end
end
end
class CreateRoles < ActiveRecord::Migration
def self.up
add_column :users, :role_id, :integer
create_table :roles do |t|
t.string :name
t.timestamps
end
end
def self.down
remove_column :users, :role_id
drop_table :roles
end
end
class PagesController < ApplicationController
before_filter :require_user, :except => :show
before_filter :except => [:new, :create] do |controller|
controller.check_authorization(["admin"])
end
## all your normal controller actions
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment