sábado, 20 de febrero de 2010

Easy Groups Authentication in Ruby on Rails using before_filter

first It's necessary to create two new tables: a table called groups with the fields (id, groupname, description) and other table called systables, with the fields (id, group_id, controller). Then create a file login_system.rb in the Lib folder under the main project. This file it's the library for send a filter to "before_filter" method in a rails controller. the modified code it's above:

require_dependency "user"
module LoginSystem
protected

def autorizado?(user, controller)
@usuario= User.find(user)
@grupo = @usuario.grupo.id.to_i
@systable = Systable.find(:all, :conditions => ["grupo_id = ? and controller = ?", @grupo, controller])
if @systable.empty?
return false
else
return true
end
end

#------ Group permissions ------------
def check_permissions
if not protect?(action_name)
return true
end
if @session['user'] and autorizado?(@session['user'], controller_name)
return true
end
store_location
access_denied
return false
end

# overwrite if you want to have special behavior in case the user is not authorized
# to access the current operation.
# the default action is to redirect to the login screen
# example use :
# a popup window might just close itself for instance

def access_denied
redirect_to :controller=>"/account", :action =>"login"
end

# store current uri in the session.
# we can return to this location by calling return_location
def store_location
@session['return-to'] = @request.request_uri
end

# move to the last store_location call or to the passed default one
def redirect_back_or_default(default)
if @session['return-to'].nil?
redirect_to default
else
redirect_to_url @session['return-to']
@session['return-to'] = nil
end
end



finally, in a controller write a line like this:


class CatalogosController < ApplicationController
before_filter :check_permissions
end

No hay comentarios: