Skip to content

Integration with Sorcery

the-teacher edited this page Jul 19, 2012 · 4 revisions

Sorcery on TheRole

rails 3.2.6

sorcery 0.7.12

the_role 1.6.0

git clone
bundle

Sorcery + TheRole integration

rake db:create

Create Sorcery Migration

rails generate sorcery:install

=> db\migrate\XXXXXX_sorcery_core.rb

Add role_id:integer to Sorcery migration

class SorceryCore < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :username,         :null => false
      t.string :email,            :default => nil
      t.string :crypted_password, :default => nil
      t.string :salt,             :default => nil

      # TheRole field
      t.integer :role_id,         :default => nil

      t.timestamps
    end
  end
end

Create the_role migration

rake the_role_engine:install:migrations

=> Copied migration 20120719064432_create_roles.the_role_engine.rb

Invoke migrate

rake db:migrate

Create Role Model without migration

rails g model role --migration=false

Try to create Fake Roles for test (if you wish)

rake db:roles:test

Try to create User with any Role

u = User.new
u.username = 'Jon Dow'
u.email = '[email protected]'
u.password = 'qwerty'
u.save

Try to play with Role

user_role = Role.where(:name => :user).first

user_role.has?(:pages, :edit)          => true
user_role.has?(:pages, :index)         => false
user_role.has?(:users, :avatar_upload) => true

Set Role to User

u = User.new
u.role = user_role
u.save

Try to play with User's Role

u.has_role?(:pages, :edit)          => true
u.has_role?(:pages, :index)         => false
u.has_role?(:users, :avatar_upload) => true

Setup TheRole and Sorcery for Auth

class ApplicationController < ActionController::Base
  include TheRole::Requires

  protect_from_forgery

  def access_denied
    render :text => 'access_denied: requires an role' and return
  end

  alias_method :login_required,     :require_login
  alias_method :role_access_denied, :access_denied
end

Use with any Controller

class WelcomeController < ApplicationController
  before_filter :login_required, :except => [:index]

  def index; end

  def only_for_users
    render :text => 'only_for_users' and return
  end
end

Use full Authenticate cycle

class PagesController < ApplicationController
  # Sorcery and TheRole before_filters
  before_filter :login_required, :except => [:index, :show]
  before_filter :role_required,  :except => [:index, :show]

  before_filter :find_page,      :only   => [:edit, :update, :destroy]
  before_filter :owner_required, :only   => [:edit, :update, :destroy]

  private

  def find_page
    @page = Page.find params[:id]
    @ownership_checking_object = @page
  end
end

Owner Required

define @ownership_checking_object with checked object, before invoke of owner_required