Skip to content
Browse files

Moving param protection to -more

  • Loading branch information...
1 parent f589085 commit 957bcb667bf4a2709bb6efa2e4f562e589a5f2de @wycats committed Oct 9, 2008
View
20 merb_param_protection/LICENSE
@@ -1,20 +0,0 @@
-Copyright (c) 2008 Lance Carlson
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
View
37 merb_param_protection/README
@@ -1,37 +0,0 @@
-merb_param_protection
-=================
-
-This plugin exposes three new controller methods which allow us to simply and flexibly filter the parameters available within the controller.
-
-Setup:
-The request sets:
-
- params => { :post => { :title => "ello", :body => "Want it", :status => "green", :author_id => 3, :rank => 4 } }
-
- Example 1: params_accessable
- MyController < Application
- params_accessible :post => [:title, :body]
- end
-
- params.inspect # => { :post => { :title => "ello", :body => "Want it" } }
-
-So we see that params_accessible removes everything except what is explictly specified.
-
- Example 2: params_protected
- MyOtherController < Application
- params_protected :post => [:status, :author_id]
- end
-
- params.inspect # => { :post => { :title => "ello", :body => "Want it", :rank => 4 } }
-
-We also see that params_protected removes ONLY those parameters explicitly specified.
-
-Sometimes you have certain post parameters that are best left unlogged, we support that too. Your
-actions continue to receive the variable correctly, but the requested parameters are scrubbed
-at log time.
-
- MySuperDuperController < Application
- log_params_filtered :password
- end
-
- params.inspect # => { :username => 'atmos', :password => '[FILTERED]' }
View
78 merb_param_protection/Rakefile
@@ -1,78 +0,0 @@
-require 'rubygems'
-require 'rubygems/specification'
-require 'rake/gempackagetask'
-require "extlib"
-require 'merb-core/tasks/merb_rake_helper'
-require "spec/rake/spectask"
-
-##############################################################################
-# Package && release
-##############################################################################
-RUBY_FORGE_PROJECT = "merb"
-PROJECT_URL = "http://merbivore.com"
-PROJECT_SUMMARY = "Merb plugin that provides params_accessible and params_protected class methods"
-PROJECT_DESCRIPTION = PROJECT_SUMMARY
-
-GEM_AUTHOR = "Lance Carlson"
-GEM_EMAIL = "lancecarlson@gmail.com"
-
-GEM_NAME = "merb_param_protection"
-PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : ''
-GEM_VERSION = (Merb::MORE_VERSION rescue "0.9.8") + PKG_BUILD
-
-RELEASE_NAME = "REL #{GEM_VERSION}"
-
-require "extlib/tasks/release"
-
-spec = Gem::Specification.new do |s|
- s.rubyforge_project = RUBY_FORGE_PROJECT
- s.name = GEM_NAME
- s.version = GEM_VERSION
- s.platform = Gem::Platform::RUBY
- s.has_rdoc = true
- s.extra_rdoc_files = ["README", "LICENSE"]
- s.summary = PROJECT_SUMMARY
- s.description = PROJECT_DESCRIPTION
- s.author = GEM_AUTHOR
- s.email = GEM_EMAIL
- s.homepage = PROJECT_URL
- s.add_dependency('merb-core', '>= 0.9.8')
- s.require_path = 'lib'
- s.files = %w(LICENSE README Rakefile) + Dir.glob("{lib,specs}/**/*")
-end
-
-Rake::GemPackageTask.new(spec) do |pkg|
- pkg.gem_spec = spec
-end
-
-desc "Install the gem"
-task :install do
- Merb::RakeHelper.install(GEM_NAME, :version => GEM_VERSION)
-end
-
-desc "Uninstall the gem"
-task :uninstall do
- Merb::RakeHelper.uninstall(GEM_NAME, :version => GEM_VERSION)
-end
-
-desc "Create a gemspec file"
-task :gemspec do
- File.open("#{GEM_NAME}.gemspec", "w") do |file|
- file.puts spec.to_ruby
- end
-end
-
-desc "Run all examples (or a specific spec with TASK=xxxx)"
-Spec::Rake::SpecTask.new('spec') do |t|
- t.spec_opts = ["-cfs"]
- t.spec_files = begin
- if ENV["TASK"]
- ENV["TASK"].split(',').map { |task| "spec/**/#{task}_spec.rb" }
- else
- FileList['spec/**/*_spec.rb']
- end
- end
-end
-
-desc 'Default: run spec examples'
-task :default => 'spec'
View
4 merb_param_protection/TODO
@@ -1,4 +0,0 @@
-TODO:
-DRY up the code
-Finish spec'ing
-Allow specification of any parameter?
View
179 merb_param_protection/lib/merb_param_protection.rb
@@ -1,179 +0,0 @@
-# This plugin exposes two new controller methods which allow us to simply and flexibly filter the parameters available within the controller.
-
-# Setup:
-# The request sets:
-# params => { :post => { :title => "ello", :body => "Want it", :status => "green", :author_id => 3, :rank => 4 } }
-#
-# Example 1: params_accessable
-# MyController < Application
-# params_accessible :post => [:title, :body]
-# end
-
-# params.inspect # => { :post => { :title => "ello", :body => "Want it" } }
-
-# So we see that params_accessible removes everything except what is explictly specified.
-
-# Example 2: params_protected
-# MyOtherController < Application
-# params_protected :post => [:status, :author_id]
-# end
-
-# params.inspect # => { :post => { :title => "ello", :body => "Want it", :rank => 4 } }
-
-# We also see that params_protected removes ONLY those parameters explicitly specified.
-
-if defined?(Merb::Plugins)
-
- # Merb gives you a Merb::Plugins.config hash...feel free to put your stuff in your piece of it
- #Merb::Plugins.config[:merb_param_protection] = {
- #:chickens => false
- #}
-
- #Merb::Plugins.add_rakefiles "merb_param_protection/merbtasks"
-
- module Merb
- module ParamsFilter
- module ControllerMixin
- def self.included(base)
- base.send(:extend, ClassMethods)
- base.send(:include, InstanceMethods)
- base.send(:class_inheritable_accessor, :accessible_params_args)
- base.send(:class_inheritable_accessor, :protected_params_args)
- base.send(:class_inheritable_accessor, :log_params_args)
- # Don't expose these as public methods - otherwise they'll become controller actions
- base.send(:protected, :accessible_params_args, :protected_params_args, :log_params_args)
- base.send(:protected, :accessible_params_args=, :protected_params_args=, :log_params_args=)
-
- base.send(:before, :initialize_params_filter)
- end
-
- module ClassMethods
- # Ensures these parameters are sent for the object
- #
- # params_accessible :post => [:title, :body]
- #
- def params_accessible(args = {})
- assign_filtered_params(:accessible_params_args, args)
- end
-
- # Protects parameters of an object
- #
- # params_protected :post => [:status, :author_id]
- #
- def params_protected(args = {})
- assign_filtered_params(:protected_params_args, args)
- end
-
- # Filters parameters out from the default log string
- # Params will still be passed to the controller properly, they will
- # show up as [FILTERED] in the merb logs.
- #
- # log_params_filtered :password, 'token'
- #
- def log_params_filtered(*args)
- self.log_params_args = args.collect { |arg| arg.to_sym }
- end
-
- private
-
- def assign_filtered_params(method, args)
- validate_filtered_params(method, args)
-
- # If the method is nil, set to initial hash, otherwise merge
- self.send(method).nil? ? self.send(method.to_s + '=', args) : self.send(method).merge!(args)
- end
-
- def validate_filtered_params(method, args)
- # Reversing methods
- params_methods = [:accessible_params_args, :protected_params_args]
- params_methods.delete(method)
- params_method = params_methods.first
-
- # Make sure the opposite method is not nil
- unless self.send(params_method).nil?
- # Loop through arg's keys
- args.keys.each do |key|
- # If the key exists on the opposite method, raise exception
- if self.send(params_method).include?(key)
- case method
- when :accessible_params_args : raise "Cannot make accessible a controller (#{self}) that is already protected"
- when :protected_params_args : raise "Cannot protect controller (#{self}) that is already accessible"
- end
- end
- end
- end
- end
- end
-
- module InstanceMethods
- def initialize_params_filter
- if accessible_params_args.is_a?(Hash)
- accessible_params_args.keys.each do |obj|
- self.request.restrict_params(obj, accessible_params_args[obj])
- end
- end
-
- if protected_params_args.is_a?(Hash)
- protected_params_args.keys.each do |obj|
- self.request.remove_params_from_object(obj, protected_params_args[obj])
- end
- end
- end
- end
-
- end
-
- module RequestMixin
- attr_accessor :trashed_params
-
- # Removes specified parameters of an object
- #
- # remove_params_from_object(:post, [:status, :author_id])
- #
- def remove_params_from_object(obj, attrs = [])
- unless params[obj].nil?
- filtered = params
- attrs.each {|a| filtered[obj].delete(a)}
- @params = filtered
- end
- end
-
- # Restricts parameters of an object
- #
- # restrict_params(:post, [:title, :body])
- #
- def restrict_params(obj, attrs = [])
- # Make sure the params for the object exists
- unless params[obj].nil?
- attrs = attrs.collect {|a| a.to_s}
- trashed_params_keys = params[obj].keys - attrs
-
- # Store a hash of the key/value pairs we are going
- # to remove in case we need them later. Lighthouse Bug # 105
- @trashed_params = {}
- trashed_params_keys.each do |key|
- @trashed_params.merge!({key => params[obj][key]})
- end
-
- remove_params_from_object(obj, trashed_params_keys)
- end
- end
-
- end
- end
- end
-
- Merb::Controller.send(:include, Merb::ParamsFilter::ControllerMixin)
- Merb::Request.send(:include, Merb::ParamsFilter::RequestMixin)
-
- class Merb::Controller
- def self._filter_params(params)
- return params if self.log_params_args.nil?
- result = { }
- params.each do |k,v|
- result[k] = (self.log_params_args.include?(k.to_sym) ? '[FILTERED]' : v)
- end
- result
- end
- end
-end
View
6 merb_param_protection/lib/merb_param_protection/merbtasks.rb
@@ -1,6 +0,0 @@
-namespace :merb_param_protection do
- desc "Do something for merb_param_protection"
- task :default do
- puts "merb_param_protection doesn't do anything"
- end
-end
View
1 merb_param_protection/log/merb_test.log
@@ -1 +0,0 @@
-# Logfile created on Wed Jan 09 01:18:03 -0500 2008
View
14 merb_param_protection/script/destroy
@@ -1,14 +0,0 @@
-#!/usr/bin/env ruby
-APP_ROOT = File.join(File.dirname(__FILE__), '..')
-
-begin
- require 'rubigen'
-rescue LoadError
- require 'rubygems'
- require 'rubigen'
-end
-require 'rubigen/scripts/destroy'
-
-ARGV.shift if ['--help', '-h'].include?(ARGV[0])
-RubiGen::Base.use_component_sources! [:rubygems, :test_unit]
-RubiGen::Scripts::Destroy.new.run(ARGV)
View
14 merb_param_protection/script/generate
@@ -1,14 +0,0 @@
-#!/usr/bin/env ruby
-APP_ROOT = File.join(File.dirname(__FILE__), '..')
-
-begin
- require 'rubigen'
-rescue LoadError
- require 'rubygems'
- require 'rubigen'
-end
-require 'rubigen/scripts/generate'
-
-ARGV.shift if ['--help', '-h'].include?(ARGV[0])
-RubiGen::Base.use_component_sources! [:rubygems, :test_unit]
-RubiGen::Scripts::Generate.new.run(ARGV)
View
112 merb_param_protection/spec/merb_param_protection_spec.rb
@@ -1,112 +0,0 @@
-require File.dirname(__FILE__) + '/spec_helper'
-
-describe "merb_param_protection" do
- describe "Controller", "parameter filtering" do
- describe "accessible parameters" do
- class ParamsAccessibleController < Merb::Controller
- params_accessible :customer => [:name, :phone, :email], :address => [:street, :zip]
- params_accessible :post => [:title, :body]
- def create; end
- end
-
- class ParamsProtectedController < Merb::Controller
- params_protected :customer => [:activated?, :password], :address => [:long, :lat]
- def update; end
- end
-
-
- it "should store the accessible parameters for that controller" do
- pending
- @params_accessible_controller = ParamsAccessibleController.new( fake_request )
- @params_accessible_controller.stub!(:initialize_params_filter)
-
- # FIXME : this call to dispatch is where I break
- @params_accessible_controller.dispatch('create')
- @params_accessible_controller.accessible_params_args.should == {
- :address=> [:street, :zip], :post=> [:title, :body], :customer=> [:name, :phone, :email]
- }
- end
-
- it "should remove the parameters from the request that are not accessible" do
- pending
- @params_accessible_controller = ParamsAccessibleController.new( fake_request )
- # FIXME : this call to dispatch is where I break
- @params_accessible_controller.dispatch('create')
- end
- end
-
- describe "protected parameters" do
- before(:each) do
- pending
- @params_protected_controller = ParamsProtectedController.new( fake_request )
- # FIXME : this call to dispatch is where I break
- #@params_protected_controller.dispatch('update')
- end
-
- it "should store the protected parameters for that controller" do
- @params_protected_controller.protected_params_args.should == {
- :address=> [:long, :lat], :customer=> [:activated?, :password]
- }
- end
- end
-
- describe "param clash prevention" do
- it "should raise an error 'cannot make accessible'" do
- lambda {
- class TestAccessibleController < Merb::Controller
- params_protected :customer => [:password]
- params_accessible :customer => [:name, :phone, :email]
- def index; end
- end
- }.should raise_error("Cannot make accessible a controller (TestAccessibleController) that is already protected")
- end
-
- it "should raise an error 'cannot protect'" do
- lambda {
- class TestProtectedController < Merb::Controller
- params_accessible :customer => [:name, :phone, :email]
- params_protected :customer => [:password]
- def index; end
- end
- }.should raise_error("Cannot protect controller (TestProtectedController) that is already accessible")
- end
- end
- end
-
- describe "param filtering" do
- before(:each) do
- Merb::Router.prepare do |r|
- @test_route = r.match("/the/:place/:goes/here").to(:controller => "Test", :action => "show").name(:test)
- @default_route = r.default_routes
- end
- end
-
- it "should remove specified params" do
- post_body = "post[title]=hello%20there&post[body]=some%20text&post[status]=published&post[author_id]=1&commit=Submit"
- request = fake_request( {:request_method => 'POST'}, {:post_body => post_body})
- request.remove_params_from_object(:post, [:status, :author_id])
- request.params[:post][:title].should == "hello there"
- request.params[:post][:body].should == "some text"
- request.params[:post][:status].should_not == "published"
- request.params[:post][:author_id].should_not == 1
- request.params[:commit].should == "Submit"
- end
-
- it "should restrict parameters" do
- post_body = "post[title]=hello%20there&post[body]=some%20text&post[status]=published&post[author_id]=1&commit=Submit"
- request = fake_request( {:request_method => 'POST'}, {:post_body => post_body})
- request.restrict_params(:post, [:title, :body])
- request.params[:post][:title].should == "hello there"
- request.params[:post][:body].should == "some text"
- request.params[:post][:status].should_not == "published"
- request.params[:post][:author_id].should_not == 1
- request.params[:commit].should == "Submit"
- request.trashed_params.should == {"status"=>"published", "author_id"=>"1"}
- end
- end
-
- it "should not have any plugin methods accidently exposed as actions" do
- Merb::Controller.callable_actions.should be_empty
- end
-
-end
View
31 merb_param_protection/spec/spec_helper.rb
@@ -1,31 +0,0 @@
-require 'rubygems'
-$:.push File.join(File.dirname(__FILE__), '..', 'lib')
-require 'merb-core'
-require 'merb_param_protection'
-
-Spec::Runner.configure do |config|
- config.include(Merb::Test::ViewHelper)
- config.include(Merb::Test::RouteHelper)
- config.include(Merb::Test::ControllerHelper)
-end
-
-def new_controller(action = 'index', controller = nil, additional_params = {})
- request = OpenStruct.new
- request.params = {:action => action, :controller => (controller.to_s || "Test")}
- request.params.update(additional_params)
- request.cookies = {}
- request.accept ||= '*/*'
-
- yield request if block_given?
-
- response = OpenStruct.new
- response.read = ""
- (controller || Merb::Controller).build(request, response)
-end
-
-class Merb::Controller
- # require 'merb/session/memory_session'
- # Merb::MemorySessionContainer.setup
- # include ::Merb::SessionMixin
- # self.session_secret_key = "footo the bar to the baz"
-end

0 comments on commit 957bcb6

Please sign in to comment.
Something went wrong with that request. Please try again.