Skip to content

Instantly share code, notes, and snippets.

@mutablestate
Last active August 29, 2015 13:58
Show Gist options
  • Save mutablestate/9999983 to your computer and use it in GitHub Desktop.
Save mutablestate/9999983 to your computer and use it in GitHub Desktop.
Simple authorization of controller actions with Rails 4 Concern
# app/controllers/concern/authorizable.rb
module Authorizable
def authorize_admin!
unless signed_in? && current_user.admin?
flash_not_authorized
end
end
def authorize_editor!
unless signed_in? && current_user.editor?
flash_not_authorized
end
end
def unauthorized!
flash_not_authorized
end
private
def flash_not_authorized
flash.now[:error] = "You are not authorized!"
redirect_to request.headers["Referer"] || root_path
end
end
# app/controllers/posts_controller.rb
# authorize multiple roles or a singular role
class PostsController < ApplicationController
include Authorizable
# before_action :authorize_admin!, except: [:index]
before_action :authorize_roles!, except: [:index]
def index
@posts = Post.all
end
def new
@post = Post.new
end
private
def authorize_roles!
case
when current_user.admin?
authorize_admin!
when current_user.editor?
authorize_editor!
else
unauthorized!
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment