0.0
Repository is archived
No commit activity in last 3 years
No release in over 3 years
Rails specific implementation of the Guachiman gem for authorization in ActionController
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 1.9.0, ~> 1.9
>= 5.7.0, ~> 5.7
>= 10.4.0, ~> 10.4

Runtime

>= 2.0.0, ~> 2.0
>= 4.2.0, ~> 4.2
 Project Readme

guachiman-rails

Basic Authorization gem for rails based on RailsCast #385 Authorization from Scratch by Ryan Bates. Built on top of guachiman.

Codeship Status for goddamnhippie/guachiman-rails

Installation

Add this line to your application's Gemfile:

gem 'guachiman-rails'

And then execute:

$ bundle

Or install it directly:

$ gem install guachiman-rails

Usage

Run rails g guachiman:install

This will generate a authorization.rb file in app/models.

Include Guachiman::Authorizable in ApplicationController and optionally implement a current_user method there (it defaults to nil).

# app/controllers/application_controller.rb

include Guachiman::Authorizable

def current_user
  @current_user ||= User.find_by_auth_token(cookies[:auth_token]) if cookies[:auth_token]
end

Skip authorization

class UsersController < ApplicationController
  skip_before_action :authorize, if: :admin?
  # ...
  private

  def admin?
    current_user && current_user.admin?
  end
end

Handle authorization failure

The default implementation is to raise Guachiman::UnauthorizedError. You can rescue the error with a regular Rails rescue_from call or override the #unauthorized method directly:

def unauthorized
  if request.get? && !request.xhr?
    session[:next] = request.url
    redirect_to root_path, alert: t(:unauthorized)
  else
    render nothing: true, status: :unauthorized
  end
end

Now you can describe your authorization object in this way:

class Authorization
  include Guachiman

  def initialize(current_user)
    allow :sessions, :new, :create
    allow :users,    :new, :create

    allow :users, :show, :edit, :update do |user|
      current_user && current_user.id == user.id
    end
  end
end

The method #current_resource will default to nil but you can override in the controllers:

class UsersController < ApplicationController
  # ...
  private

  def current_resource
    @user ||= User.find(params[:id]) if params[:id].present?
  end
end

License

MIT