Skip to content
This repository has been archived by the owner on May 20, 2021. It is now read-only.

beathyate/guachiman-rails

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

Authorization gem for Rails

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages