From f4222bc29e4224887d6416bb3c58db7b5164c320 Mon Sep 17 00:00:00 2001 From: Daniel Lobato Date: Tue, 15 Sep 2015 11:51:40 +0200 Subject: [PATCH] Update gems to a Rails 4 compatible version Counter cache columns fix Remove conditions,order,limit from has_many relations Remove test runner On minitest 5, the runner API was deprecated, so our custom test runner is no longer working. Remove useless add_index on lookup_values match An index is added previously on lookup_values :priority, and on Rails 4 rename_column changes 'priority' to 'match' already changes the name of the index. Alias assert_include to assert_includes Expire topbar cache Subclass ApplicationMailer in test to avoid 'missing template' error Fixes #12021 - Use .to_param to find parent object in LookupKeys controller On Rails 4, .find will not default to .friendly.find so find_hostgroup, find_environment and find_host will fail for non numeric IDs. However, we can use from_param to find these objects. This is something we can do both on Rails 3 and Rails 4, whereas using .friendly isn't an option until friendly_id 5.0, which depends on Rails 4. Use explicit friendly ID search Remove RecordNotFound errors from parameterizable in rails 4 find_common finder uses from_param -> friendly -> find The finder needed to be refactored because with the new Friendly ID we have to use .friendly explicitely. It currently follows the strategy of searching like this: - from_param -> .friendly -> regular find Protected attributes automatically added through AccessibleAttributes AccessibleAttributes pulls in all possible associations and models and sets them as attr_accessible for the model. Where needed, additional attr_accessible attributes have been added. refs #3157 - adding protected_attributes gem Conflicts: app/models/auth_source.rb app/models/domain.rb app/models/image.rb app/models/lookup_value.rb config/routes/test.rb Conflicts: app/models/domain.rb app/models/lookup_value.rb url_for doesn't append port when protocol is specified Some of our tests are checking if port 80 or 443 is included in the URL generated by lib/foreman/renderer.rb. However url_for has changed in Rails 4 and now it does not append the port even if explicitly added. If the protocol is specified, as it is in this case, then the url generated will just have the protocol (http or https) but not the port (80 or 443) Validate object instead of _id column in join tables On Rails 4 such validations will fail when we try to create objects without explicitely assigning the id. Puppetclass.new(:config_group => config_group) would fail even for a valid config group, :config_group_id => config_group.id should be used instead. To avoid that, we validate the object, not the ID column Rails 4 non backwards compatible syntax changes Changes that have to deal with how some of the internal Rails objects need a new syntax, like generating routes, exceptions, form builders. None of these are Rails 3 compatible. Fixes #12199 - rails 4 migration errors There are actually two parts to the issue of not being able to migrate with this branch. The first is https://gist.github.com/eLobato/0f5db50b5c93cc6c277c and can be temporarily fixed with rails/sass-rails#136 (comment) I am not sure of a long term fix for that atm. Once that is patched, this error https://gist.github.com/johnpmitsch/96e5ba3629890931193a happens on a migration. This will fix that error by changing the Migrator class initializer arguments which have changed from rails 3 to rails 4 Refactor fact value test to not modify user_roles directly Return external usergroupsas an array Use eager_load instead of references Other rails 4 particularities --- Gemfile | 15 +++-- app/controllers/api/v1/reports_controller.rb | 2 +- .../api/v2/host_classes_controller.rb | 2 +- app/controllers/api/v2/models_controller.rb | 6 ++ .../api/v2/parameters_controller.rb | 5 +- app/controllers/api/v2/reports_controller.rb | 2 +- .../api/v2/smart_variables_controller.rb | 2 +- .../api/v2/lookup_keys_common_controller.rb | 57 ++++++----------- app/controllers/concerns/find_common.rb | 16 +++-- app/controllers/hosts_controller.rb | 6 +- app/controllers/reports_controller.rb | 2 +- app/controllers/settings_controller.rb | 4 +- app/controllers/unattended_controller.rb | 6 +- app/controllers/usergroups_controller.rb | 2 +- app/helpers/application_helper.rb | 7 ++ app/models/architecture.rb | 3 + app/models/auth_source.rb | 6 ++ app/models/bookmark.rb | 4 +- app/models/cached_user_role.rb | 2 - app/models/cached_usergroup_member.rb | 2 - app/models/compute_attribute.rb | 1 + app/models/compute_profile.rb | 3 +- app/models/compute_resource.rb | 5 ++ .../compute_resources/foreman/model/ec2.rb | 1 + .../compute_resources/foreman/model/gce.rb | 1 + .../foreman/model/openstack.rb | 1 + .../compute_resources/foreman/model/ovirt.rb | 1 + .../compute_resources/foreman/model/vmware.rb | 1 + app/models/concerns/has_many_common.rb | 5 +- app/models/concerns/nested_ancestry_common.rb | 1 + app/models/concerns/parameterizable.rb | 4 +- app/models/concerns/taxonomix.rb | 14 ++-- app/models/config_group.rb | 3 +- app/models/config_group_class.rb | 7 +- app/models/domain.rb | 4 +- app/models/environment.rb | 8 ++- app/models/environment_class.rb | 1 + app/models/external_usergroup.rb | 2 + app/models/fact_name.rb | 1 + app/models/fact_value.rb | 1 - app/models/feature.rb | 1 + app/models/filter.rb | 4 +- app/models/filtering.rb | 2 - app/models/host/base.rb | 19 ++++-- app/models/host/managed.rb | 13 ++-- app/models/host_class.rb | 2 +- app/models/host_config_group.rb | 2 +- app/models/hostgroup.rb | 10 +++ app/models/hostgroup_class.rb | 2 - app/models/image.rb | 4 +- app/models/key_pair.rb | 1 + app/models/log.rb | 2 + app/models/lookup_keys/lookup_key.rb | 4 ++ .../lookup_keys/puppetclass_lookup_key.rb | 2 +- app/models/lookup_keys/variable_lookup_key.rb | 1 + app/models/lookup_value.rb | 6 +- app/models/mail_notification.rb | 2 - app/models/medium.rb | 2 + app/models/message.rb | 1 + app/models/model.rb | 3 + app/models/operatingsystem.rb | 6 ++ app/models/os_default_template.rb | 3 + app/models/parameter.rb | 2 + app/models/parameters/domain_parameter.rb | 1 + app/models/parameters/group_parameter.rb | 1 + app/models/parameters/host_parameter.rb | 1 + app/models/parameters/location_parameter.rb | 1 + .../parameters/organization_parameter.rb | 1 + app/models/parameters/os_parameter.rb | 1 + app/models/permission.rb | 2 - app/models/provisioning_template.rb | 4 +- app/models/ptable.rb | 6 +- app/models/puppetclass.rb | 10 ++- app/models/realm.rb | 1 + app/models/report.rb | 3 +- app/models/setting.rb | 3 +- app/models/smart_proxy.rb | 2 + app/models/source.rb | 1 + app/models/subnet.rb | 5 +- app/models/taxonomy.rb | 18 ++++++ app/models/template.rb | 2 +- app/models/template_combination.rb | 3 + app/models/template_kind.rb | 1 + app/models/token.rb | 1 - app/models/trend_counter.rb | 1 + app/models/user.rb | 12 +++- app/models/user_mail_notification.rb | 4 +- app/models/user_role.rb | 2 +- app/models/usergroup.rb | 13 ++-- app/models/usergroup_member.rb | 2 +- app/services/foreman/plugin.rb | 2 +- app/services/tax_host.rb | 5 +- app/views/api/v2/interfaces/base.json.rabl | 1 + bundler.d/assets.rb | 10 +-- bundler.d/console.rb | 3 - bundler.d/test.rb | 6 +- config/application.rb | 4 +- config/environments/development.rb | 7 -- config/environments/test.rb | 4 +- .../initializers/active_record_extensions.rb | 35 ++++++++++ config/initializers/routing_hash_for.rb | 29 +++++++++ ...0444_add_look_up_key_id_to_puppet_class.rb | 1 - .../20140219183343_migrate_permissions.rb | 24 +++---- lib/middleware/catch_json_parse_errors.rb | 2 +- lib/tasks/jenkins.rake | 8 +-- lib/tasks/test.rake | 7 -- .../api/base_controller_subclass_test.rb | 64 +++++++++---------- .../smart_class_parameters_controller_test.rb | 2 +- .../api/v2/smart_proxies_controller_test.rb | 2 +- .../provisioning_templates_controller_test.rb | 2 +- test/functional/unattended_controller_test.rb | 4 +- test/lib/tasks/seeds_test.rb | 1 + test/test_helper.rb | 5 +- test/test_runner.rb | 35 ---------- test/unit/application_mailer_test.rb | 12 +++- test/unit/fact_value_test.rb | 22 +++---- test/unit/helpers/layout_helper_test.rb | 4 +- test/unit/host_test.rb | 10 ++- 118 files changed, 430 insertions(+), 293 deletions(-) create mode 100644 config/initializers/routing_hash_for.rb delete mode 100644 test/test_runner.rb diff --git a/Gemfile b/Gemfile index abbfd7d188cc..85471b6a7e2d 100644 --- a/Gemfile +++ b/Gemfile @@ -4,31 +4,34 @@ require File.expand_path('../lib/regexp_extensions', FOREMAN_GEMFILE) source 'https://rubygems.org' -gem 'rails', '3.2.22' +gem 'rails', '4.1.5' gem 'rack-cache', '< 1.3.0' gem 'json', '~> 1.5' gem 'rest-client', '~> 1.6.0', :require => 'rest_client' -gem 'audited-activerecord', '3.0.0' +gem 'audited-activerecord', '~> 4.0' gem 'will_paginate', '~> 3.0' gem 'ancestry', '~> 2.0' -gem 'scoped_search', '~> 3.0' +gem 'scoped_search', '>= 3.2.2' gem 'ldap_fluff', '>= 0.3.5', '< 1.0' gem 'net-ldap', '>= 0.8.0' -gem 'apipie-rails', '~> 0.2.5' +gem 'apipie-rails', '~> 0.3.4' gem 'rabl', '~> 0.11' gem 'oauth', '~> 0.4' gem 'deep_cloneable', '~> 2.0' gem 'foreigner', '~> 1.4' gem 'validates_lengths_from_database', '~> 0.2' -gem 'friendly_id', '~> 4.0' +gem 'friendly_id', '~> 5.0' gem 'secure_headers', '~> 1.3' gem 'safemode', '~> 1.2' gem 'fast_gettext', '~> 0.8' gem 'gettext_i18n_rails', '~> 1.0' gem 'i18n', '~> 0.6.4' -gem 'rails-i18n', '~> 3.0.0' +gem 'rails-i18n', '~> 4.0.0' gem 'turbolinks', '~> 2.5' gem 'logging', '>= 1.8.0', '< 3.0.0' +gem 'activerecord-session_store' +gem 'rails-observers' +gem 'protected_attributes' Dir["#{File.dirname(FOREMAN_GEMFILE)}/bundler.d/*.rb"].each do |bundle| self.instance_eval(Bundler.read_file(bundle)) diff --git a/app/controllers/api/v1/reports_controller.rb b/app/controllers/api/v1/reports_controller.rb index a5374c7d7ad0..42dd88c291ec 100644 --- a/app/controllers/api/v1/reports_controller.rb +++ b/app/controllers/api/v1/reports_controller.rb @@ -35,7 +35,7 @@ def destroy param :id, :identifier, :required => true def last - conditions = { :host_id => Host.authorized(:view_hosts).find(params[:host_id]).try(:id) } if params[:host_id].present? + conditions = { :host_id => Host.authorized(:view_hosts).friendly.find(params[:host_id]).try(:id) } if params[:host_id].present? max_id = resource_scope.where(conditions).maximum(:id) @report = resource_scope.includes(:logs => [:message, :source]).find(max_id) render :show diff --git a/app/controllers/api/v2/host_classes_controller.rb b/app/controllers/api/v2/host_classes_controller.rb index 28c4b82bcad8..c60051483aea 100644 --- a/app/controllers/api/v2/host_classes_controller.rb +++ b/app/controllers/api/v2/host_classes_controller.rb @@ -35,7 +35,7 @@ def destroy # overwrite resource_name so it's host and and not host_class, since we want to return @host def find_host not_found and return false if params[:host_id].blank? - @host = Host.find(params[:host_id]) if Host::Managed.respond_to?(:authorized) && + @host = Host.friendly.find(params[:host_id]) if Host::Managed.respond_to?(:authorized) && Host::Managed.authorized("view_host", Host::Managed) end end diff --git a/app/controllers/api/v2/models_controller.rb b/app/controllers/api/v2/models_controller.rb index 9554fe389592..1a288ab6e3b4 100644 --- a/app/controllers/api/v2/models_controller.rb +++ b/app/controllers/api/v2/models_controller.rb @@ -47,6 +47,12 @@ def update def destroy process_response @model.destroy end + + private + + def find_resource + @model = Model.friendly.find(params[:id]) || super + end end end end diff --git a/app/controllers/api/v2/parameters_controller.rb b/app/controllers/api/v2/parameters_controller.rb index 0d3f536396b1..fd0ebae7b489 100644 --- a/app/controllers/api/v2/parameters_controller.rb +++ b/app/controllers/api/v2/parameters_controller.rb @@ -165,8 +165,9 @@ def allowed_nested_id def find_parameter # nested_obj is required, so no need to check here @parameters = nested_obj.send(parameters_method) - @parameter = @parameters.find(params[:id]) - return @parameter if @parameter + @parameter = @parameters.from_param(params[:id]) + @parameter ||= @parameters.friendly.find(params[:id]) + return @parameter if @parameter.present? not_found end end diff --git a/app/controllers/api/v2/reports_controller.rb b/app/controllers/api/v2/reports_controller.rb index 0990a2f69e4e..47953ebbc529 100644 --- a/app/controllers/api/v2/reports_controller.rb +++ b/app/controllers/api/v2/reports_controller.rb @@ -54,7 +54,7 @@ def destroy param :id, :identifier, :required => true def last - conditions = { :host_id => Host.authorized(:view_hosts).find(params[:host_id]).try(:id) } if params[:host_id].present? + conditions = { :host_id => Host.authorized(:view_hosts).friendly.find(params[:host_id]).try(:id) } if params[:host_id].present? max_id = resource_scope.where(conditions).maximum(:id) @report = resource_scope.includes(:logs => [:message, :source]).find(max_id) render :show diff --git a/app/controllers/api/v2/smart_variables_controller.rb b/app/controllers/api/v2/smart_variables_controller.rb index 4ea79e8fb62c..2e34ab301b8e 100644 --- a/app/controllers/api/v2/smart_variables_controller.rb +++ b/app/controllers/api/v2/smart_variables_controller.rb @@ -43,7 +43,7 @@ def show param_group :smart_variable, :as => :create def create - @smart_variable = LookupKey.new(params[:smart_variable]) unless @puppetclass + @smart_variable = VariableLookupKey.new(params[:smart_variable]) unless @puppetclass @smart_variable ||= @puppetclass.lookup_keys.build(params[:smart_variable]) process_response @smart_variable.save end diff --git a/app/controllers/concerns/api/v2/lookup_keys_common_controller.rb b/app/controllers/concerns/api/v2/lookup_keys_common_controller.rb index 009eef9d15ff..a9a310c84a8a 100644 --- a/app/controllers/concerns/api/v2/lookup_keys_common_controller.rb +++ b/app/controllers/concerns/api/v2/lookup_keys_common_controller.rb @@ -19,22 +19,6 @@ module Api::V2::LookupKeysCommonController before_filter :return_if_smart_mismatch, :only => [:show, :update, :destroy] end - def puppetclass_id? - params.keys.include?('puppetclass_id') - end - - def environment_id? - params.keys.include?('environment_id') - end - - def host_id? - params.keys.include?('host_id') - end - - def hostgroup_id? - params.keys.include?('hostgroup_id') - end - def smart_variable_id? params.keys.include?('smart_variable_id') || controller_name.match(/smart_variables/) end @@ -43,28 +27,22 @@ def smart_class_parameter_id? params.keys.include?('smart_class_parameter_id') || controller_name.match(/smart_class_parameters/) end - def find_puppetclass - @puppetclass = Puppetclass.authorized(:view_puppetclasses).find(params['puppetclass_id']) - rescue ActiveRecord::RecordNotFound - not_found({ :error => { :message => (_("Puppet class with id '%{id}' was not found") % { :id => params['puppetclass_id'] }) } }) - end + [Puppetclass, Environment, Host::Base, Hostgroup].each do |model| + model_string = model.to_s.split('::').first.downcase - def find_environment - @environment = Environment.authorized(:view_environments).find(params['environment_id']) - rescue ActiveRecord::RecordNotFound - not_found({ :error => { :message => (_("Environment with id '%{id}' was not found") % { :id => params['environment_id'] }) } }) - end - - def find_host - @host = Host::Base.authorized(:view_hosts).find(params['host_id']) - rescue ActiveRecord::RecordNotFound - not_found({ :error => { :message => (_("Host with id '%{id}' was not found") % { :id => params['host_id'] }) } }) - end + define_method("#{model_string}_id?") do + params.keys.include?("#{model_string}_id") + end - def find_hostgroup - @hostgroup = Hostgroup.authorized(:view_hostgroups).find(params['hostgroup_id']) - rescue ActiveRecord::RecordNotFound - not_found({ :error => { :message => (_("Hostgroup with id '%{id}' was not found") % { :id => params['hostgroup_id'] }) } }) + define_method("find_#{model_string}") do + scope = model.authorized(:"view_#{model_string.pluralize}") + begin + instance_variable_set("@#{model_string}", + resource_finder(scope, params["#{model_string}_id"])) + rescue ActiveRecord::RecordNotFound + model_not_found(model_string) + end + end end def find_smart_variable @@ -144,4 +122,11 @@ def return_if_smart_mismatch not_found "#{obj} not found by id '#{id}'" end end + + private + + def model_not_found(model_name) + not_found(:error => { :message => (_("#{model_name.capitalize} with id '%{id}' was not found") % + { :id => params["#{model_name}_id"] } ) } ) + end end diff --git a/app/controllers/concerns/find_common.rb b/app/controllers/concerns/find_common.rb index 5d8a5a30edd9..9018d8cef25a 100644 --- a/app/controllers/concerns/find_common.rb +++ b/app/controllers/concerns/find_common.rb @@ -1,12 +1,18 @@ -# this mixin is used by both ApplicationController and Api::BaseController -# searches for an object based on its id, name, label, etc and assign it to an instance variable +# This mixin is used by both ApplicationController and Api::BaseController +# Searches for an object based on its id, name, label, etc and assign it to an instance variable # friendly_id performs the logic if params[:id] is 'id' or 'id-name' or 'name' module FindCommon - # example: @host = Host.find(params[:id]) def find_resource - not_found and return if params[:id].blank? - instance_variable_set("@#{resource_name}", resource_scope.find(params[:id])) + instance_variable_set("@#{resource_name}", + resource_finder(resource_scope, params[:id])) + end + + def resource_finder(scope, id) + raise ActiveRecord::RecordNotFound if scope.empty? + result = scope.from_param(id) if scope.respond_to?(:from_param) + result ||= scope.friendly.find(id) if scope.respond_to?(:friendly) + result ||= scope.find(id) end def resource_name(resource = controller_name) diff --git a/app/controllers/hosts_controller.rb b/app/controllers/hosts_controller.rb index ddc5b4d98773..4ef1fbdb64f6 100644 --- a/app/controllers/hosts_controller.rb +++ b/app/controllers/hosts_controller.rb @@ -169,7 +169,7 @@ def puppetclass_parameters def externalNodes certname = params[:name] @host ||= resource_base.find_by_certname certname - @host ||= resource_base.find certname + @host ||= resource_base.friendly.find certname not_found and return unless @host begin @@ -352,7 +352,7 @@ def update_multiple_parameters skipped = [] params[:name].each do |name, value| next if value.empty? - if (host_param = host.host_parameters.find(name)) + if (host_param = host.host_parameters.friendly.find(name)) counter += 1 if host_param.update_attribute(:value, value) else skipped << name @@ -676,7 +676,7 @@ def taxonomy_scope # overwrite application_controller def find_resource not_found and return false if (id = params[:id]).blank? - @host = resource_base.find(id) + @host = resource_base.friendly.find(id) @host ||= resource_base.find_by_mac params[:host][:mac] if params[:host] && params[:host][:mac] not_found and return(false) unless @host diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb index d175c3a10df2..ab486aa94387 100644 --- a/app/controllers/reports_controller.rb +++ b/app/controllers/reports_controller.rb @@ -10,7 +10,7 @@ def index def show # are we searching for the last report? if params[:id] == "last" - conditions = { :host_id => Host.authorized(:view_hosts).find(params[:host_id]).try(:id) } if params[:host_id].present? + conditions = { :host_id => Host.authorized(:view_hosts).friendly.find(params[:host_id]).try(:id) } if params[:host_id].present? params[:id] = resource_base.where(conditions).maximum(:id) end @report = resource_base.includes(:logs => [:message, :source]).find(params[:id]) diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index ef4133685ef5..646f258eda4c 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -9,11 +9,11 @@ class SettingsController < ApplicationController end def index - @settings = Setting.live_descendants.search_for(params[:search]) + @settings = Setting.live_descendants.search_for(params[:search]).where(nil) end def update - @setting = Setting.find(params[:id]) + @setting = Setting.friendly.find(params[:id]) if @setting.parse_string_value(params[:setting][:value]) && @setting.save render :json => @setting else diff --git a/app/controllers/unattended_controller.rb b/app/controllers/unattended_controller.rb index ecf25b3cf137..c74d86ff3e30 100644 --- a/app/controllers/unattended_controller.rb +++ b/app/controllers/unattended_controller.rb @@ -45,8 +45,8 @@ def built def template return head(:not_found) unless (params.has_key?("id") and params.has_key?(:hostgroup)) - template = ProvisioningTemplate.find(params['id']) - @host = Hostgroup.find(params['hostgroup']) + template = ProvisioningTemplate.friendly.find(params['id']) + @host = Hostgroup.friendly.find(params['hostgroup']) return head(:not_found) unless template and @host @@ -108,7 +108,7 @@ def get_host_details def find_host_by_spoof host = Nic::Base.primary.find_by_ip(params.delete('spoof')).try(:host) if params['spoof'].present? - host ||= Host.find(params.delete('hostname')) if params['hostname'].present? + host ||= Host.friendly.find(params.delete('hostname')) if params['hostname'].present? @spoof = host.present? host end diff --git a/app/controllers/usergroups_controller.rb b/app/controllers/usergroups_controller.rb index ee66a1652f99..dbbfecdc864b 100644 --- a/app/controllers/usergroups_controller.rb +++ b/app/controllers/usergroups_controller.rb @@ -51,7 +51,7 @@ def find_by_id(permission = :view_usergroups) def get_external_usergroups_to_refresh # we need to load current status, so we call all explicitly - @external_usergroups = @usergroup.external_usergroups.all + @external_usergroups = @usergroup.external_usergroups.to_a end def external_usergroups diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index af20f443b600..ca2043299269 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -32,6 +32,13 @@ def link_to(*args, &block) end end + def link_to_function(name, function, html_options = {}) + onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;" + href = html_options[:href] || '#' + + content_tag(:a, name, html_options.merge(:href => href, :onclick => onclick)) + end + protected def contract(model) diff --git a/app/models/architecture.rb b/app/models/architecture.rb index c69038bb3803..c14c16f95c85 100644 --- a/app/models/architecture.rb +++ b/app/models/architecture.rb @@ -4,6 +4,8 @@ class Architecture < ActiveRecord::Base friendly_id :name include Parameterizable::ByIdName + attr_accessible :name, :operatingsystem_ids + before_destroy EnsureNotUsedBy.new(:hosts, :hostgroups) validates_lengths_from_database @@ -11,6 +13,7 @@ class Architecture < ActiveRecord::Base has_many :hostgroups has_many :images, :dependent => :destroy has_and_belongs_to_many :operatingsystems + validates :name, :presence => true, :uniqueness => true, :no_whitespace => true audited :allow_mass_assignment => true, :except => [:hosts_count, :hostgroups_count] diff --git a/app/models/auth_source.rb b/app/models/auth_source.rb index 7949d09eca54..0d5bff980eb4 100644 --- a/app/models/auth_source.rb +++ b/app/models/auth_source.rb @@ -17,12 +17,18 @@ class AuthSource < ActiveRecord::Base include Authorizable + + attr_accessible :name, :host, :tls, :port, :server_type, :account, + :base_dn, :groups_base, :ldap_filter, :onthefly_register, + :attr_login, :attr_firstname, :attr_lastname, :attr_mail, :attr_photo + audited :allow_mass_assignment => true validates_lengths_from_database :except => [:name, :account_password, :host, :attr_login, :attr_firstname, :attr_lastname, :attr_mail] before_destroy EnsureNotUsedBy.new(:users) has_many :users has_many :external_usergroups, :dependent => :destroy + attr_protected :type validates :name, :presence => true, :uniqueness => true, :length => { :maximum => 60 } diff --git a/app/models/bookmark.rb b/app/models/bookmark.rb index 26c34ea12206..b6902179061c 100644 --- a/app/models/bookmark.rb +++ b/app/models/bookmark.rb @@ -4,10 +4,11 @@ class Bookmark < ActiveRecord::Base friendly_id :name include Parameterizable::ByIdName + attr_accessible :name, :query, :public, :controller + validates_lengths_from_database belongs_to :owner, :polymorphic => true - attr_accessible :name, :controller, :query, :public audited :allow_mass_assignment => true validates :name, :uniqueness => {:scope => :controller}, :unless => Proc.new{|b| Bookmark.my_bookmarks.where(:name => b.name).empty?} @@ -16,6 +17,7 @@ class Bookmark < ActiveRecord::Base :inclusion => { :in => ["dashboard"] + ActiveRecord::Base.connection.tables.map(&:to_s), :message => _("%{value} is not a valid controller") } + default_scope -> { order(:name) } before_validation :set_default_user diff --git a/app/models/cached_user_role.rb b/app/models/cached_user_role.rb index d8a3de0388f2..858124deaa9f 100644 --- a/app/models/cached_user_role.rb +++ b/app/models/cached_user_role.rb @@ -1,6 +1,4 @@ class CachedUserRole < ActiveRecord::Base - attr_accessible :role_id, :user_id, :user_role_id, :role, :user, :user_role - belongs_to :user belongs_to :role diff --git a/app/models/cached_usergroup_member.rb b/app/models/cached_usergroup_member.rb index b523e0619935..6d160db8429a 100644 --- a/app/models/cached_usergroup_member.rb +++ b/app/models/cached_usergroup_member.rb @@ -1,6 +1,4 @@ class CachedUsergroupMember < ActiveRecord::Base - attr_accessible :user_id, :usergroup_id, :user, :usergroup - belongs_to :user belongs_to :usergroup end diff --git a/app/models/compute_attribute.rb b/app/models/compute_attribute.rb index d29e50091632..53a7b5d1304d 100644 --- a/app/models/compute_attribute.rb +++ b/app/models/compute_attribute.rb @@ -1,5 +1,6 @@ class ComputeAttribute < ActiveRecord::Base attr_accessible :compute_profile_id, :compute_resource_id, :vm_attrs + audited :associated_with => :compute_profile belongs_to :compute_resource diff --git a/app/models/compute_profile.rb b/app/models/compute_profile.rb index d30cc211f1ee..f2a2a7ae0705 100644 --- a/app/models/compute_profile.rb +++ b/app/models/compute_profile.rb @@ -4,8 +4,9 @@ class ComputeProfile < ActiveRecord::Base friendly_id :name include Parameterizable::ByIdName - validates_lengths_from_database attr_accessible :name + + validates_lengths_from_database audited has_associated_audits diff --git a/app/models/compute_resource.rb b/app/models/compute_resource.rb index e7b9318d3480..d15b54c343be 100644 --- a/app/models/compute_resource.rb +++ b/app/models/compute_resource.rb @@ -6,6 +6,11 @@ class ComputeResource < ActiveRecord::Base include Parameterizable::ByIdName encrypts :password + attr_accessible :name, :provider, :description, :url, :display_type, + :set_console_password, :user, :password, :public_key, + :server, :tenant, :project, :email, :key_path, + :location_ids, :organization_ids + class_attribute :supported_providers self.supported_providers = { 'Libvirt' => 'Foreman::Model::Libvirt', diff --git a/app/models/compute_resources/foreman/model/ec2.rb b/app/models/compute_resources/foreman/model/ec2.rb index 412893379d2c..4ee69906a461 100644 --- a/app/models/compute_resources/foreman/model/ec2.rb +++ b/app/models/compute_resources/foreman/model/ec2.rb @@ -11,6 +11,7 @@ class EC2 < ComputeResource alias_attribute :access_key, :user alias_attribute :region, :url + attr_accessible :access_key, :region def to_label "#{name} (#{region}-#{provider_friendly_name})" diff --git a/app/models/compute_resources/foreman/model/gce.rb b/app/models/compute_resources/foreman/model/gce.rb index d2c794096a81..288cbb104518 100644 --- a/app/models/compute_resources/foreman/model/gce.rb +++ b/app/models/compute_resources/foreman/model/gce.rb @@ -4,6 +4,7 @@ class GCE < ComputeResource before_create :setup_key_pair validate :check_google_key_path validates :key_path, :project, :email, :presence => true + attr_accessible :key_pair, :key_path delegate :flavors, :to => :client diff --git a/app/models/compute_resources/foreman/model/openstack.rb b/app/models/compute_resources/foreman/model/openstack.rb index d273cfb8f6b1..3b5201a98823 100644 --- a/app/models/compute_resources/foreman/model/openstack.rb +++ b/app/models/compute_resources/foreman/model/openstack.rb @@ -7,6 +7,7 @@ class Openstack < ComputeResource delegate :flavors, :to => :client delegate :tenants, :to => :client delegate :security_groups, :to => :client + attr_accessible :key_pair, :tenant validates :user, :password, :presence => true diff --git a/app/models/compute_resources/foreman/model/ovirt.rb b/app/models/compute_resources/foreman/model/ovirt.rb index cc29ab335ecd..4e8568f0dc4c 100644 --- a/app/models/compute_resources/foreman/model/ovirt.rb +++ b/app/models/compute_resources/foreman/model/ovirt.rb @@ -8,6 +8,7 @@ class Ovirt < ComputeResource before_create :update_public_key alias_attribute :datacenter, :uuid + attr_accessible :datacenter, :ovirt_quota, :public_key delegate :clusters, :quotas, :templates, :to => :client diff --git a/app/models/compute_resources/foreman/model/vmware.rb b/app/models/compute_resources/foreman/model/vmware.rb index b59274f8c833..1db82cfc7a07 100644 --- a/app/models/compute_resources/foreman/model/vmware.rb +++ b/app/models/compute_resources/foreman/model/vmware.rb @@ -7,6 +7,7 @@ class Vmware < ComputeResource validates :user, :password, :server, :datacenter, :presence => true before_create :update_public_key + attr_accessible :pubkey_hash def self.model_name ComputeResource.model_name diff --git a/app/models/concerns/has_many_common.rb b/app/models/concerns/has_many_common.rb index 9b013d829cb3..684148722bfd 100644 --- a/app/models/concerns/has_many_common.rb +++ b/app/models/concerns/has_many_common.rb @@ -41,8 +41,9 @@ class << self; self end end #### has_many #### - def has_many(association, options = {}) - has_many_names_for(association, options) + def has_many(*args) + options = args.last.is_a?(Hash) ? args.last : {} + has_many_names_for(args.first, options) super end diff --git a/app/models/concerns/nested_ancestry_common.rb b/app/models/concerns/nested_ancestry_common.rb index f0ada1bb81b9..824e232ac5f0 100644 --- a/app/models/concerns/nested_ancestry_common.rb +++ b/app/models/concerns/nested_ancestry_common.rb @@ -17,6 +17,7 @@ module NestedAncestryCommon # attribute used by *_names and *_name methods. default is :name attr_name :title + attr_accessible :parent, :parent_id end # override title getter diff --git a/app/models/concerns/parameterizable.rb b/app/models/concerns/parameterizable.rb index 4a0c63e36487..0fb27066e476 100644 --- a/app/models/concerns/parameterizable.rb +++ b/app/models/concerns/parameterizable.rb @@ -12,7 +12,7 @@ def to_param end def self.from_param(id) - self.find(id.to_i) + self.find_by_id(id.to_i) end end end @@ -27,7 +27,7 @@ def to_param end def self.from_param(id_name) - self.find(id_name.to_i) + self.find_by_id(id_name.to_i) end end end diff --git a/app/models/concerns/taxonomix.rb b/app/models/concerns/taxonomix.rb index f2d8a476b48f..6308dfd419ac 100644 --- a/app/models/concerns/taxonomix.rb +++ b/app/models/concerns/taxonomix.rb @@ -3,12 +3,14 @@ module Taxonomix include DirtyAssociations included do - taxonomy_join_table = "taxable_taxonomies" - has_many taxonomy_join_table, :dependent => :destroy, :as => :taxable - has_many :locations, :through => taxonomy_join_table, :source => :taxonomy, - :conditions => "taxonomies.type='Location'", :validate => false - has_many :organizations, :through => taxonomy_join_table, :source => :taxonomy, - :conditions => "taxonomies.type='Organization'", :validate => false + taxonomy_join_table = :taxable_taxonomies + has_many taxonomy_join_table.to_sym, :dependent => :destroy, :as => :taxable + has_many :locations, -> {where("taxonomies.type='Location'")}, + :through => taxonomy_join_table, :source => :taxonomy, + :validate => false + has_many :organizations, -> {where "taxonomies.type='Organization'"}, + :through => taxonomy_join_table, :source => :taxonomy, + :validate => false after_initialize :set_current_taxonomy scoped_search :in => :locations, :on => :name, :rename => :location, :complete_value => true diff --git a/app/models/config_group.rb b/app/models/config_group.rb index 12b31993e0ef..5eecd5e1ab9a 100644 --- a/app/models/config_group.rb +++ b/app/models/config_group.rb @@ -6,13 +6,12 @@ class ConfigGroup < ActiveRecord::Base validates_lengths_from_database - attr_accessible :name, :puppetclass_ids - has_many :config_group_classes has_many :puppetclasses, :through => :config_group_classes, :dependent => :destroy has_many :host_config_groups has_many_hosts :through => :host_config_groups, :source => :host, :source_type => 'Host::Managed' has_many :hostgroups, :through => :host_config_groups, :source => :host, :source_type => 'Hostgroup' + attr_accessible :class_environments, :name validates :name, :presence => true, :uniqueness => true diff --git a/app/models/config_group_class.rb b/app/models/config_group_class.rb index 904d58fd4a4f..512143ba021f 100644 --- a/app/models/config_group_class.rb +++ b/app/models/config_group_class.rb @@ -4,12 +4,11 @@ class ConfigGroupClass < ActiveRecord::Base include PuppetclassTotalHosts::JoinTable audited :associated_with => :config_group, :allow_mass_assignment => true - attr_accessible :config_group_id, :puppetclass_id belongs_to :puppetclass belongs_to :config_group, :counter_cache => true - validates :puppetclass_id, :presence => true - validates :config_group_id, :presence => true, - :uniqueness => {:scope => :puppetclass_id} + validates :puppetclass, :presence => true + validates :config_group, :presence => true, + :uniqueness => {:scope => :puppetclass} end diff --git a/app/models/domain.rb b/app/models/domain.rb index cf6e2798b033..e6992ff9509f 100644 --- a/app/models/domain.rb +++ b/app/models/domain.rb @@ -8,6 +8,8 @@ class Domain < ActiveRecord::Base include StripLeadingAndTrailingDot include Parameterizable::ByIdName + attr_accessible :name, :fullname, :dns_id, :location_ids, :organization_ids, :domain_parameters_attributes + audited :allow_mass_assignment => true, :except => [:hosts_count, :hostgroups_count] validates_lengths_from_database @@ -20,7 +22,7 @@ class Domain < ActiveRecord::Base has_many :domain_parameters, :dependent => :destroy, :foreign_key => :reference_id, :inverse_of => :domain has_many :parameters, :dependent => :destroy, :foreign_key => :reference_id, :class_name => "DomainParameter" has_many :interfaces, :class_name => 'Nic::Base' - has_many :primary_interfaces, :class_name => 'Nic::Base', :conditions => { :primary => true } + has_many :primary_interfaces, -> { where(:primary => true) }, :class_name => 'Nic::Base' has_many :hosts, :through => :interfaces has_many :primary_hosts, :through => :primary_interfaces, :source => :host diff --git a/app/models/environment.rb b/app/models/environment.rb index 64e4be5356ee..b0ba8f3f8c1c 100644 --- a/app/models/environment.rb +++ b/app/models/environment.rb @@ -5,19 +5,21 @@ class Environment < ActiveRecord::Base include Authorizable include Parameterizable::ByName + attr_accessible :name, :location_ids, :organization_ids + validates_lengths_from_database before_destroy EnsureNotUsedBy.new(:hosts, :hostgroups) has_many :environment_classes, :dependent => :destroy - has_many :puppetclasses, :through => :environment_classes, :uniq => true + has_many :puppetclasses, -> { uniq }, :through => :environment_classes has_many_hosts has_many :hostgroups has_many :trends, :as => :trendable, :class_name => "ForemanTrend" - - validates :name, :uniqueness => true, :presence => true, :alphanumeric => true has_many :template_combinations, :dependent => :destroy has_many :provisioning_templates, :through => :template_combinations + validates :name, :uniqueness => true, :presence => true, :alphanumeric => true + # with proc support, default_scope can no longer be chained # include all default scoping here default_scope lambda { diff --git a/app/models/environment_class.rb b/app/models/environment_class.rb index cac10c5c1bcf..c3c413468de1 100644 --- a/app/models/environment_class.rb +++ b/app/models/environment_class.rb @@ -2,6 +2,7 @@ class EnvironmentClass < ActiveRecord::Base belongs_to :environment belongs_to :puppetclass belongs_to :puppetclass_lookup_key + validates :puppetclass_lookup_key_id, :uniqueness => {:scope => [:environment_id, :puppetclass_id]} validates :puppetclass_id, :environment_id, :presence => true diff --git a/app/models/external_usergroup.rb b/app/models/external_usergroup.rb index fc4dbaf065c9..3cfb3f71ac32 100644 --- a/app/models/external_usergroup.rb +++ b/app/models/external_usergroup.rb @@ -2,6 +2,8 @@ class ExternalUsergroup < ActiveRecord::Base extend FriendlyId friendly_id :name + attr_accessible :usergroup_id, :name, :auth_source_id, :usergroup + belongs_to :usergroup, :inverse_of => :external_usergroups belongs_to :auth_source diff --git a/app/models/fact_name.rb b/app/models/fact_name.rb index d4f12e507f5c..021c571a9549 100644 --- a/app/models/fact_name.rb +++ b/app/models/fact_name.rb @@ -6,6 +6,7 @@ class FactName < ActiveRecord::Base validates_lengths_from_database has_many :fact_values, :dependent => :destroy has_many_hosts :through => :fact_values + attr_accessible :parent, :name scope :no_timestamp_fact, -> { where("fact_names.name <> ?",:_timestamp) } scope :timestamp_facts, -> { where(:name => :_timestamp) } diff --git a/app/models/fact_value.rb b/app/models/fact_value.rb index d600a3975330..6077ddef8674 100644 --- a/app/models/fact_value.rb +++ b/app/models/fact_value.rb @@ -6,7 +6,6 @@ class FactValue < ActiveRecord::Base belongs_to :fact_name delegate :name, :short_name, :compose, :to => :fact_name has_many :hostgroup, :through => :host - has_one :parent_fact_name, :through => :fact_name, :source => :parent scoped_search :on => :value, :in_key=> :fact_name, :on_key=> :name, :rename => :facts, :complete_value => true, :only_explicit => true, :ext_method => :search_cast_facts diff --git a/app/models/feature.rb b/app/models/feature.rb index d4385ecd8ef7..4f264c9e605d 100644 --- a/app/models/feature.rb +++ b/app/models/feature.rb @@ -2,6 +2,7 @@ class Feature < ActiveRecord::Base extend FriendlyId friendly_id :name has_and_belongs_to_many :smart_proxies + validates_lengths_from_database validates :name, :presence => true diff --git a/app/models/filter.rb b/app/models/filter.rb index 5b7f0c12459c..1495064284fc 100644 --- a/app/models/filter.rb +++ b/app/models/filter.rb @@ -2,6 +2,8 @@ class Filter < ActiveRecord::Base include Taxonomix include Authorizable + attr_accessible :role_id, :resource_type, :ermissions, :search, :location_ids, :organization_ids, :permission_ids + class ScopedSearchValidator < ActiveModel::Validator def validate(record) resource_class = record.resource_class @@ -20,8 +22,6 @@ def add_current_location? false end - attr_accessible :search, :resource_type, :permission_ids, :role_id, :unlimited, - :organization_ids, :location_ids attr_writer :resource_type attr_accessor :unlimited diff --git a/app/models/filtering.rb b/app/models/filtering.rb index 59df77f2a936..ec3bced5df9a 100644 --- a/app/models/filtering.rb +++ b/app/models/filtering.rb @@ -1,6 +1,4 @@ class Filtering < ActiveRecord::Base - attr_accessible :filter_id, :permission_id - belongs_to :filter belongs_to :permission end diff --git a/app/models/host/base.rb b/app/models/host/base.rb index 314d6cce4749..9e655b7abbce 100644 --- a/app/models/host/base.rb +++ b/app/models/host/base.rb @@ -11,22 +11,29 @@ class Base < ActiveRecord::Base friendly_id :name OWNER_TYPES = %w(User Usergroup) + attr_accessible :name, :organization_id, :location_id, :hostgroup_id, + :compute_resource_id, :compute_profile_id, :environment_id, + :puppet_ca_proxy_id, :puppet_proxy_id, :managed, :progress_report_id, + :type, :domain_id, :realm_id, :start, :mac, :subnet_id, :ip, :architecture_id, + :operatingsystem_id, :provision_method, :build, :medium_id, :ptable_id, :disk, + :root_pass, :is_owned_by, :enabled, :model_id, :comment, :overwrite, :capabilities, + :rpovider, :config_group_ids, :puppetclass_ids, :location_ids, :organization_ids + validates_lengths_from_database belongs_to :model, :counter_cache => :hosts_count has_many :fact_values, :dependent => :destroy, :foreign_key => :host_id has_many :fact_names, :through => :fact_values - has_many :interfaces, :dependent => :destroy, :inverse_of => :host, :class_name => 'Nic::Base', - :foreign_key => :host_id, :order => 'identifier' - has_one :primary_interface, :class_name => 'Nic::Base', :foreign_key => 'host_id', - :conditions => { :primary => true } - has_one :provision_interface, :class_name => 'Nic::Base', :foreign_key => 'host_id', - :conditions => { :provision => true } + has_many :interfaces, -> { order(:identifier) }, :dependent => :destroy, :inverse_of => :host, :class_name => 'Nic::Base', + :foreign_key => :host_id + has_one :primary_interface, -> { where(:primary => true) }, :class_name => 'Nic::Base', :foreign_key => 'host_id' + has_one :provision_interface, -> { where(:provision => true) }, :class_name => 'Nic::Base', :foreign_key => 'host_id' has_one :domain, :through => :primary_interface has_one :subnet, :through => :primary_interface accepts_nested_attributes_for :interfaces, :allow_destroy => true belongs_to :location belongs_to :organization + attr_accessible :hostgroup_name, :id, :created_at, :updated_at alias_attribute :hostname, :name validates :name, :presence => true, :uniqueness => true, :format => {:with => Net::Validations::HOST_REGEXP} diff --git a/app/models/host/managed.rb b/app/models/host/managed.rb index b45addcc9c96..2a951af25e63 100644 --- a/app/models/host/managed.rb +++ b/app/models/host/managed.rb @@ -63,6 +63,11 @@ def build_hooks end include HostCommon + attr_accessible :interfaces_attributes, :ip, :mac, :lookup_values_attributes, :hostgroup, + :progress_report_id, :is_owned_by, :overwrite, :id, :created_at, :updated_at, :domain_id, + :last_compile, :last_report, :installed_at, :owner_id, :owner_type, :use_image, :image_file, + :uuid, :certname, :image_id, :otp, :grub_pass, :lookup_value_matcher, :global_status, :owner, + :location, :organization, :ptable, :medium, :operatingsystem, :puppet_proxy, :architecture, :environment class Jail < ::Safemode::Jail allow :name, :diskLayout, :puppetmaster, :puppet_ca_server, :operatingsystem, :os, :environment, :ptable, :hostgroup, @@ -482,7 +487,7 @@ def host_inherited_params_objects def host_params_objects # Host parameters should always be first for the uniq order - (host_parameters + host_inherited_params_objects.reverse!).uniq {|param| param.name} + (host_parameters + host_inherited_params_objects.to_a.reverse!).uniq {|param| param.name} end # JSON is auto-parsed by the API, so these should be in the right format @@ -631,7 +636,7 @@ def apply_inherited_attributes(attributes, initialized = true) new_hostgroup = self.hostgroup if initialized unless [new_hostgroup.try(:id), new_hostgroup.try(:friendly_id)].include? new_hostgroup_id - new_hostgroup = Hostgroup.find(new_hostgroup_id) + new_hostgroup = Hostgroup.friendly.find(new_hostgroup_id) end return attributes unless new_hostgroup @@ -849,11 +854,11 @@ def available_template_kinds(provisioning = nil) cr = ComputeResource.find_by_id(self.compute_resource_id) images = cr.try(:images) if images.blank? - [TemplateKind.find('finish')] + [TemplateKind.friendly.find('finish')] else uuid = self.compute_attributes[cr.image_param_name] image_kind = images.find_by_uuid(uuid).try(:user_data) ? 'user_data' : 'finish' - [TemplateKind.find(image_kind)] + [TemplateKind.friendly.find(image_kind)] end else TemplateKind.all diff --git a/app/models/host_class.rb b/app/models/host_class.rb index e1d078b94c25..774450047978 100644 --- a/app/models/host_class.rb +++ b/app/models/host_class.rb @@ -7,7 +7,7 @@ class HostClass < ActiveRecord::Base belongs_to_host belongs_to :puppetclass - validates :host, :presence => true +# validates :host, :presence => true validates :puppetclass_id, :presence => true, :uniqueness => {:scope => :host_id} def name diff --git a/app/models/host_config_group.rb b/app/models/host_config_group.rb index 5250dc090ae0..1808a815e86a 100644 --- a/app/models/host_config_group.rb +++ b/app/models/host_config_group.rb @@ -1,8 +1,8 @@ class HostConfigGroup < ActiveRecord::Base include Authorizable + audited :associated_with => :host, :allow_mass_assignment => true audited :associated_with => :hostgroup, :allow_mass_assignment => true - attr_accessible :host_id, :config_group_id belongs_to :host, :polymorphic => true belongs_to :config_group diff --git a/app/models/hostgroup.rb b/app/models/hostgroup.rb index 61c492b8b774..9323112b29ee 100644 --- a/app/models/hostgroup.rb +++ b/app/models/hostgroup.rb @@ -6,6 +6,14 @@ class Hostgroup < ActiveRecord::Base include HostCommon include NestedAncestryCommon + + attr_accessible :parent_id, :name, :environment_id, :compute_profile_id, + :puppet_ca_proxy_id, :puppet_proxy_id, :domain_id, :subnet_id, + :realm_id, :architecture_id, :operatingsystem_id, :medium_id, + :ptable_id, :root_pass, :config_group_ids, :puppetclass_ids, + :group_parameters_attributes, :location_ids, :organization_ids, + :use_image, :image_file, :ancestry, :vm_defaults, :title, :grub_pass, :lookup_value_matcher + validates :name, :presence => true, :uniqueness => {:scope => :ancestry, :case_sensitive => false} validates :title, :presence => true, :uniqueness => true @@ -40,6 +48,8 @@ class Hostgroup < ActiveRecord::Base nested_attribute_for :compute_profile_id, :environment_id, :domain_id, :puppet_proxy_id, :puppet_ca_proxy_id, :operatingsystem_id, :architecture_id, :medium_id, :ptable_id, :subnet_id, :realm_id + attr_accessible :parent, :parent_id, :os, :os_id, :arch, :arch_id, :group_parameters_attributes, + :lookup_values_attributes, :id, :created_at, :updated_at, :organizations, :locations # with proc support, default_scope can no longer be chained # include all default scoping here diff --git a/app/models/hostgroup_class.rb b/app/models/hostgroup_class.rb index 26efa1074b53..713a633538e3 100644 --- a/app/models/hostgroup_class.rb +++ b/app/models/hostgroup_class.rb @@ -7,8 +7,6 @@ class HostgroupClass < ActiveRecord::Base belongs_to :hostgroup belongs_to :puppetclass, :counter_cache => :hostgroups_count - attr_accessible :hostgroup_id, :hostgroup, :puppetclass_id, :puppetclass - validates :hostgroup, :presence => true validates :puppetclass_id, :presence => true, :uniqueness => {:scope => :hostgroup_id} diff --git a/app/models/image.rb b/app/models/image.rb index 5538d5834c8b..5ff011b4e2ea 100644 --- a/app/models/image.rb +++ b/app/models/image.rb @@ -1,12 +1,14 @@ class Image < ActiveRecord::Base include Authorizable + attr_accessible :name, :compute_resource_id, :operatingsystem_id, :architecture_id, + :username, :password, :uuid, :user_data, :iam_role + audited :allow_mass_assignment => true belongs_to :operatingsystem belongs_to :compute_resource belongs_to :architecture - has_many_hosts :dependent => :nullify validates_lengths_from_database diff --git a/app/models/key_pair.rb b/app/models/key_pair.rb index 5c128377ad04..94effa64252b 100644 --- a/app/models/key_pair.rb +++ b/app/models/key_pair.rb @@ -1,5 +1,6 @@ class KeyPair < ActiveRecord::Base belongs_to :compute_resource + validates_lengths_from_database validates :name, :secret, :presence => true validates :compute_resource_id, :presence => true, :uniqueness => true diff --git a/app/models/log.rb b/app/models/log.rb index 3a09e0a4bdf3..05c719f9b285 100644 --- a/app/models/log.rb +++ b/app/models/log.rb @@ -2,6 +2,8 @@ class Log < ActiveRecord::Base belongs_to :message belongs_to :source belongs_to :report + + attr_accessible :level, :message_id, :source_id, :report validates :message_id, :source_id, :report_id, :level_id, :presence => true default_scope -> { order('logs.id') } diff --git a/app/models/lookup_keys/lookup_key.rb b/app/models/lookup_keys/lookup_key.rb index bb47e220aa43..91cf83d38b51 100644 --- a/app/models/lookup_keys/lookup_key.rb +++ b/app/models/lookup_keys/lookup_key.rb @@ -9,6 +9,9 @@ class LookupKey < ActiveRecord::Base EQ_DELM = "=" VALUE_REGEX =/\A[^#{KEY_DELM}]+#{EQ_DELM}[^#{KEY_DELM}]+(#{KEY_DELM}[^#{KEY_DELM}]+#{EQ_DELM}[^#{KEY_DELM}]+)*\Z/ + attr_accessible :key, :description, :override, :key_type, :default_value, :required, :validator_type, :use_puppet_default, + :validator_rule, :path, :variable, :id, :is_param, :puppetclass_id, :lookup_values_attributes, :lookup_values + audited :associated_with => :audit_class, :allow_mass_assignment => true, :except => :lookup_values_count validates_lengths_from_database @@ -57,6 +60,7 @@ def self.inherited(child) alias_attribute :override_values_count, :lookup_values_count alias_attribute :override_values, :lookup_values alias_attribute :override_value_ids, :lookup_value_ids + attr_accessible :lookup_values_attributes, :is_param, :id, :variable, :key # to prevent errors caused by find_resource from override_values controller def self.find_by_name(str) diff --git a/app/models/lookup_keys/puppetclass_lookup_key.rb b/app/models/lookup_keys/puppetclass_lookup_key.rb index 1c5f6f312f06..ec097e5408d8 100644 --- a/app/models/lookup_keys/puppetclass_lookup_key.rb +++ b/app/models/lookup_keys/puppetclass_lookup_key.rb @@ -1,6 +1,6 @@ class PuppetclassLookupKey < LookupKey has_many :environment_classes, :dependent => :destroy - has_many :environments, :through => :environment_classes, :uniq => true + has_many :environments, -> { uniq }, :through => :environment_classes has_many :param_classes, :through => :environment_classes, :source => :puppetclass scoped_search :in => :param_classes, :on => :name, :rename => :puppetclass, :complete_value => true diff --git a/app/models/lookup_keys/variable_lookup_key.rb b/app/models/lookup_keys/variable_lookup_key.rb index 9ce25e9835e9..89fc82cd7785 100644 --- a/app/models/lookup_keys/variable_lookup_key.rb +++ b/app/models/lookup_keys/variable_lookup_key.rb @@ -1,5 +1,6 @@ class VariableLookupKey < LookupKey belongs_to :puppetclass, :inverse_of => :lookup_keys, :counter_cache => :variable_lookup_keys_count + attr_accessible :puppetclass_id, :puppetclass validates :puppetclass, :presence => true validates :key, :uniqueness => true diff --git a/app/models/lookup_value.rb b/app/models/lookup_value.rb index 24642db239b6..6710bc0a3867 100644 --- a/app/models/lookup_value.rb +++ b/app/models/lookup_value.rb @@ -2,10 +2,14 @@ class LookupValue < ActiveRecord::Base include Authorizable include CounterCacheFix + attr_accessible :match, :value, :lookup_key_id, :id, :_destroy, :host_or_hostgroup, :use_puppet_default, :lookup_key + validates_lengths_from_database audited :associated_with => :lookup_key, :allow_mass_assignment => true belongs_to :lookup_key, :counter_cache => true + attr_accessor :host_or_hostgroup + validates :match, :presence => true, :uniqueness => {:scope => :lookup_key_id}, :format => LookupKey::VALUE_REGEX validate :value_present? delegate :key, :to => :lookup_key @@ -14,8 +18,6 @@ class LookupValue < ActiveRecord::Base before_validation :validate_and_cast_value, :unless => Proc.new{|p| p.use_puppet_default } validate :validate_value, :ensure_fqdn_exists, :ensure_hostgroup_exists - attr_accessor :host_or_hostgroup - serialize :value attr_name :match diff --git a/app/models/mail_notification.rb b/app/models/mail_notification.rb index be11ec335e4b..3cfbd3aa88ad 100644 --- a/app/models/mail_notification.rb +++ b/app/models/mail_notification.rb @@ -4,8 +4,6 @@ class MailNotification < ActiveRecord::Base INTERVALS = [N_("Daily"), N_("Weekly"), N_("Monthly")] SUBSCRIPTION_TYPES = %w(alert report) - attr_accessible :description, :mailer, :method, :name, :subscriptable, :subscription_type, :category, :queryable - has_many :user_mail_notifications, :dependent => :destroy has_many :users, :through => :user_mail_notifications diff --git a/app/models/medium.rb b/app/models/medium.rb index d2e9dff91359..ef5bbbb553e2 100644 --- a/app/models/medium.rb +++ b/app/models/medium.rb @@ -7,6 +7,8 @@ class Medium < ActiveRecord::Base include Parameterizable::ByIdName audited :allow_mass_assignment => true + attr_accessible :name, :path, :media_path, :config_path, :image_path, :os_family, :location_ids, :organization_ids, :operatingsystems + validates_lengths_from_database before_destroy :ensure_hosts_not_in_build diff --git a/app/models/message.rb b/app/models/message.rb index 54bb93ac2e41..24c4ae611efe 100644 --- a/app/models/message.rb +++ b/app/models/message.rb @@ -1,6 +1,7 @@ class Message < ActiveRecord::Base has_many :reports, :through => :logs has_many :logs + validates_lengths_from_database validates :value, :digest, :presence => true diff --git a/app/models/model.rb b/app/models/model.rb index bdb9700a46bb..43e7cb0c86be 100644 --- a/app/models/model.rb +++ b/app/models/model.rb @@ -3,9 +3,12 @@ class Model < ActiveRecord::Base extend FriendlyId friendly_id :name + attr_accessible :name, :hardware_model, :vendor_class, :info + before_destroy EnsureNotUsedBy.new(:hosts) has_many_hosts has_many :trends, :as => :trendable, :class_name => "ForemanTrend" + validates_lengths_from_database validates :name, :uniqueness => true, :presence => true diff --git a/app/models/operatingsystem.rb b/app/models/operatingsystem.rb index a7243cbbccb6..72ac3ec562d3 100644 --- a/app/models/operatingsystem.rb +++ b/app/models/operatingsystem.rb @@ -7,6 +7,10 @@ class Operatingsystem < ActiveRecord::Base extend FriendlyId friendly_id :title + attr_accessible :name, :major, :minor, :description, :family, + :release_name, :password_hash, :architectures, :architecture_ids, :architecture_names, + :ptable_ids, :medium_ids, :os_default_templates_attributes + validates_lengths_from_database before_destroy EnsureNotUsedBy.new(:hosts, :hostgroups) has_many_hosts @@ -27,6 +31,8 @@ class Operatingsystem < ActiveRecord::Base accepts_nested_attributes_for :os_parameters, :allow_destroy => true include ParameterValidators has_many :trends, :as => :trendable, :class_name => "ForemanTrend" + + attr_accessible :architecture_names, :os_default_templates_attributes, :to_label, :family attr_name :to_label validates :minor, :numericality => {:greater_than_or_equal_to => 0}, :allow_nil => true, :allow_blank => true validates :name, :presence => true, :no_whitespace => true, diff --git a/app/models/os_default_template.rb b/app/models/os_default_template.rb index 9aa805ec750c..8b8e0800d8ee 100644 --- a/app/models/os_default_template.rb +++ b/app/models/os_default_template.rb @@ -1,7 +1,10 @@ class OsDefaultTemplate < ActiveRecord::Base + attr_accessible :provisioning_template_id, :template_kind_id, :operatingsystem, :operatingsystem_id + belongs_to :provisioning_template belongs_to :template_kind belongs_to :operatingsystem + validates :provisioning_template_id, :presence => true validates :template_kind_id, :presence => true, :uniqueness => {:scope => :operatingsystem_id} diff --git a/app/models/parameter.rb b/app/models/parameter.rb index d4aa53395f62..ea35aca3a5ae 100644 --- a/app/models/parameter.rb +++ b/app/models/parameter.rb @@ -3,6 +3,8 @@ class Parameter < ActiveRecord::Base friendly_id :name include Parameterizable::ByIdName + attr_accessible :name, :value, :hidden_value, :_destroy, :id, :nested, :reference_id + validates_lengths_from_database include Authorizable diff --git a/app/models/parameters/domain_parameter.rb b/app/models/parameters/domain_parameter.rb index 555d66d2f795..eb5f8ee401d4 100644 --- a/app/models/parameters/domain_parameter.rb +++ b/app/models/parameters/domain_parameter.rb @@ -1,5 +1,6 @@ class DomainParameter < Parameter belongs_to :domain, :foreign_key => :reference_id, :inverse_of => :domain_parameters + audited :except => [:priority], :associated_with => :domain, :allow_mass_assignment => true validates :name, :uniqueness => {:scope => :reference_id} validates :domain, :presence => true diff --git a/app/models/parameters/group_parameter.rb b/app/models/parameters/group_parameter.rb index d1b1c0d5d07a..3d17d99285be 100644 --- a/app/models/parameters/group_parameter.rb +++ b/app/models/parameters/group_parameter.rb @@ -1,5 +1,6 @@ class GroupParameter < Parameter belongs_to :hostgroup, :foreign_key => :reference_id, :inverse_of => :group_parameters + audited :except => [:priority], :associated_with => :hostgroup, :allow_mass_assignment => true validates :name, :uniqueness => {:scope => :reference_id} validates :hostgroup, :presence => true diff --git a/app/models/parameters/host_parameter.rb b/app/models/parameters/host_parameter.rb index 92528d2d1d16..f58800e7c9be 100644 --- a/app/models/parameters/host_parameter.rb +++ b/app/models/parameters/host_parameter.rb @@ -1,5 +1,6 @@ class HostParameter < Parameter belongs_to_host :foreign_key => :reference_id, :inverse_of => :host_parameters + audited :except => [:priority], :associated_with => :host, :allow_mass_assignment => true validates :name, :uniqueness => {:scope => :reference_id} validates :host, :presence => true diff --git a/app/models/parameters/location_parameter.rb b/app/models/parameters/location_parameter.rb index 1bbb9f3c6605..b997fd8a8a8f 100644 --- a/app/models/parameters/location_parameter.rb +++ b/app/models/parameters/location_parameter.rb @@ -1,5 +1,6 @@ class LocationParameter < Parameter belongs_to :location, :foreign_key => :reference_id, :inverse_of => :location_parameters + audited :except => [:priority], :associated_with => :location, :allow_mass_assignment => true validates :name, :uniqueness => {:scope => :reference_id} validates :location, :presence => true diff --git a/app/models/parameters/organization_parameter.rb b/app/models/parameters/organization_parameter.rb index 6daa6c80ee2c..8d53b33673b8 100644 --- a/app/models/parameters/organization_parameter.rb +++ b/app/models/parameters/organization_parameter.rb @@ -1,5 +1,6 @@ class OrganizationParameter < Parameter belongs_to :organization, :foreign_key => :reference_id, :inverse_of => :organization_parameters + audited :except => [:priority], :associated_with => :organization, :allow_mass_assignment => true validates :name, :uniqueness => {:scope => :reference_id} validates :organization, :presence => true diff --git a/app/models/parameters/os_parameter.rb b/app/models/parameters/os_parameter.rb index 24c5d6109e2b..7a17377ed121 100644 --- a/app/models/parameters/os_parameter.rb +++ b/app/models/parameters/os_parameter.rb @@ -1,5 +1,6 @@ class OsParameter < Parameter belongs_to :operatingsystem, :foreign_key => :reference_id, :inverse_of => :os_parameters + audited :except => [:priority], :associated_with => :operatingsystem, :allow_mass_assignment => true validates :name, :uniqueness => {:scope => :reference_id} validates :operatingsystem, :presence => true diff --git a/app/models/permission.rb b/app/models/permission.rb index fd2fe6abb3c8..7b02d99dbafb 100644 --- a/app/models/permission.rb +++ b/app/models/permission.rb @@ -1,6 +1,4 @@ class Permission < ActiveRecord::Base - attr_accessible :name, :resource_type - validates_lengths_from_database validates :name, :presence => true, :uniqueness => true diff --git a/app/models/provisioning_template.rb b/app/models/provisioning_template.rb index 6998216da8aa..36213fafbe35 100644 --- a/app/models/provisioning_template.rb +++ b/app/models/provisioning_template.rb @@ -2,12 +2,10 @@ class ProvisioningTemplate < Template include Authorizable extend FriendlyId friendly_id :name - include Parameterizable::ByIdName + include Parameterizable::ByIdName audited :allow_mass_assignment => true - attr_accessible :template_kind, :template_kind_id, :template_combinations_attributes, - :operatingsystems, :operatingsystem_ids, :vendor validates :name, :uniqueness => true validates :template_kind_id, :presence => true, :unless => Proc.new {|t| t.snippet } diff --git a/app/models/ptable.rb b/app/models/ptable.rb index ca7073828081..f4a5c584870f 100644 --- a/app/models/ptable.rb +++ b/app/models/ptable.rb @@ -8,6 +8,7 @@ class Ptable < Template friendly_id :name include Parameterizable::ByIdName include ValidateOsFamily + include Taxonomix audited :allow_mass_assignment => true has_many :audits, :as => :auditable, :class_name => Audited.audit_class.name @@ -22,7 +23,6 @@ class Ptable < Template # these can't be shared in parent class, scoped search can't handle STI properly # tested with scoped_search 3.2.0 - include Taxonomix scoped_search :on => :name, :complete_value => true, :default_order => true scoped_search :on => :locked, :complete_value => {:true => true, :false => false} scoped_search :on => :snippet, :complete_value => {:true => true, :false => false} @@ -31,10 +31,8 @@ class Ptable < Template scoped_search :on => :template, :complete_value => false, :rename => 'layout' scoped_search :on => :os_family, :rename => 'family', :complete_value => :true - attr_accessible :layout, :os_family, :operatingsystem_ids, :operatingsystem_names, - :hostgroup_ids, :hostgroup_names, :host_ids, :host_names - alias_attribute :layout, :template + attr_accessible :layout, :location_ids, :organization_ids, :name, :default, :snippet, :os_family, :audit_comment, :operatingsystem_ids # with proc support, default_scope can no longer be chained # include all default scoping here diff --git a/app/models/puppetclass.rb b/app/models/puppetclass.rb index c4b15f6772a9..e15e2619ff91 100644 --- a/app/models/puppetclass.rb +++ b/app/models/puppetclass.rb @@ -5,10 +5,11 @@ class Puppetclass < ActiveRecord::Base friendly_id :name include Parameterizable::ByIdName + attr_accessible :name, :hostgroup_ids validates_lengths_from_database before_destroy EnsureNotUsedBy.new(:hosts, :hostgroups) has_many :environment_classes, :dependent => :destroy - has_many :environments, :through => :environment_classes, :uniq => true + has_many :environments, -> { uniq }, :through => :environment_classes has_and_belongs_to_many :operatingsystems has_many :hostgroup_classes has_many :hostgroups, :through => :hostgroup_classes, :dependent => :destroy @@ -19,8 +20,8 @@ class Puppetclass < ActiveRecord::Base has_many :lookup_keys, :inverse_of => :puppetclass, :dependent => :destroy, :class_name => 'VariableLookupKey' accepts_nested_attributes_for :lookup_keys, :reject_if => ->(a) { a[:key].blank? }, :allow_destroy => true # param classes - has_many :class_params, :through => :environment_classes, :uniq => true, - :source => :puppetclass_lookup_key, :conditions => 'environment_classes.puppetclass_lookup_key_id is NOT NULL' + has_many :class_params, -> { where('environment_classes.puppetclass_lookup_key_id is NOT NULL').uniq }, + :through => :environment_classes, :source => :puppetclass_lookup_key accepts_nested_attributes_for :class_params, :reject_if => ->(a) { a[:key].blank? }, :allow_destroy => true validates :name, :uniqueness => true, :presence => true, :no_whitespace => true @@ -31,6 +32,9 @@ class Puppetclass < ActiveRecord::Base alias_attribute :smart_class_parameters, :class_params alias_attribute :smart_class_parameter_ids, :class_param_ids + attr_accessible :smart_variables, :smart_variable_ids, :smart_class_parameters, + :smart_class_parameter_ids, :lookup_keys_attributes + default_scope -> { order('puppetclasses.name') } scoped_search :on => :name, :complete_value => :true diff --git a/app/models/realm.rb b/app/models/realm.rb index 670196b9c531..a8bcc08c502b 100644 --- a/app/models/realm.rb +++ b/app/models/realm.rb @@ -7,6 +7,7 @@ class Realm < ActiveRecord::Base TYPES = ["FreeIPA", "Active Directory"] validates_lengths_from_database + attr_accessible :name, :realm_type, :realm_proxy_id, :realm_proxy, :location_ids, :organization_ids audited :allow_mass_assignment => true, :except => [:hosts_count, :hostgroups_count] before_destroy EnsureNotUsedBy.new(:hosts, :hostgroups) diff --git a/app/models/report.rb b/app/models/report.rb index c1ac5d497a31..8a2130827cdc 100644 --- a/app/models/report.rb +++ b/app/models/report.rb @@ -6,7 +6,6 @@ class Report < ActiveRecord::Base include Authorizable include ConfigurationStatusScopedSearch - validates_lengths_from_database belongs_to_host has_many :messages, :through => :logs @@ -46,7 +45,7 @@ class Report < ActiveRecord::Base # returns reports for hosts in the User's filter set scope :my_reports, lambda { if !User.current.admin? || Organization.expand(Organization.current).present? || Location.expand(Location.current).present? - joins_authorized(Host, :view_hosts, :where => Host.taxonomy_conditions) + joins_authorized(Host, :view_hosts) end } diff --git a/app/models/setting.rb b/app/models/setting.rb index 43f521d53ce8..f801ea1c0002 100644 --- a/app/models/setting.rb +++ b/app/models/setting.rb @@ -3,6 +3,7 @@ class Setting < ActiveRecord::Base friendly_id :name include ActiveModel::Validations self.inheritance_column = 'category' + attr_accessible :category, :description, :settings_type, :default, :full_name, :name, :value TYPES= %w{ integer boolean hash array string } FROZEN_ATTRS = %w{ name category full_name } @@ -24,8 +25,6 @@ def validate(record) end end - attr_accessible :name, :value, :description, :category, :settings_type, :default, :full_name - validates_lengths_from_database # audit the changes to this model audited :only => [:value], :on => [:update], :allow_mass_assignment => true diff --git a/app/models/smart_proxy.rb b/app/models/smart_proxy.rb index d5a5372895e0..b4a7debe76cb 100644 --- a/app/models/smart_proxy.rb +++ b/app/models/smart_proxy.rb @@ -7,6 +7,7 @@ class SmartProxy < ActiveRecord::Base audited :allow_mass_assignment => true attr_accessible :name, :url, :location_ids, :organization_ids + validates_lengths_from_database before_destroy EnsureNotUsedBy.new(:hosts, :hostgroups, :subnets, :domains, [:puppet_ca_hosts, :hosts], [:puppet_ca_hostgroups, :hostgroups], :realms) #TODO check if there is a way to look into the tftp_id too @@ -19,6 +20,7 @@ class SmartProxy < ActiveRecord::Base has_many :puppet_ca_hosts, :class_name => 'Host::Managed', :foreign_key => 'puppet_ca_proxy_id' has_many :puppet_ca_hostgroups, :class_name => 'Hostgroup', :foreign_key => 'puppet_ca_proxy_id' has_many :realms, :foreign_key => 'realm_proxy_id' + URL_HOSTNAME_MATCH = %r{\A(?:http|https):\/\/([^:\/]+)} validates :name, :uniqueness => true, :presence => true validates :url, :presence => true, :format => { :with => URL_HOSTNAME_MATCH, :message => N_('is invalid - only http://, https:// are allowed') }, diff --git a/app/models/source.rb b/app/models/source.rb index 1ba597914242..732af8dc8de1 100644 --- a/app/models/source.rb +++ b/app/models/source.rb @@ -2,6 +2,7 @@ class Source < ActiveRecord::Base validates_lengths_from_database has_many :reports, :through => :logs has_many :logs + validates :value, :digest, :presence => true def to_s diff --git a/app/models/subnet.rb b/app/models/subnet.rb index f69e517d8c98..00f9f70864c1 100644 --- a/app/models/subnet.rb +++ b/app/models/subnet.rb @@ -9,6 +9,8 @@ class Subnet < ActiveRecord::Base include Taxonomix include Parameterizable::ByIdName include EncOutput + attr_accessible :name, :network, :mask, :gateway, :dns_primary, :dns_secondary, :ipam, :from, :to, + :vlanid, :boot_mode, :dhcp_id, :tftp_id, :dns_id, :domain_ids, :location_ids, :organization_ids audited :allow_mass_assignment => true validates_lengths_from_database :except => [:gateway] @@ -20,9 +22,10 @@ class Subnet < ActiveRecord::Base has_many :subnet_domains, :dependent => :destroy has_many :domains, :through => :subnet_domains has_many :interfaces, :class_name => 'Nic::Base' - has_many :primary_interfaces, :class_name => 'Nic::Base', :conditions => { :primary => true } + has_many :primary_interfaces, -> { where(:primary => true) }, :class_name => 'Nic::Base' has_many :hosts, :through => :interfaces has_many :primary_hosts, :through => :primary_interfaces, :source => :host + validates :network, :mask, :name, :presence => true validates_associated :subnet_domains validates :network, :format => {:with => Net::Validations::IP_REGEXP} diff --git a/app/models/taxonomy.rb b/app/models/taxonomy.rb index eed82aac6403..4c0ad2e97a32 100644 --- a/app/models/taxonomy.rb +++ b/app/models/taxonomy.rb @@ -5,6 +5,24 @@ class Taxonomy < ActiveRecord::Base serialize :ignore_types, Array + attr_accessible :name, + :title, + :environment_ids, + :hostgroup_ids, + :subnet_ids, + :domain_ids, + :medium_ids, + :user_ids, + :users, + :smart_proxy_ids, + :config_template_ids, + :provisioning_template_ids, + :compute_resource_ids, + :location_ids, + :organization_ids, + :description, + :ignore_types + validates_lengths_from_database belongs_to :user before_destroy EnsureNotUsedBy.new(:hosts) diff --git a/app/models/template.rb b/app/models/template.rb index f3c783b529e5..941ff9e46930 100644 --- a/app/models/template.rb +++ b/app/models/template.rb @@ -1,7 +1,7 @@ class Template < ActiveRecord::Base validates_lengths_from_database - attr_accessible :name, :template, :snippet, :audit_comment, :location_ids, :organization_ids, :locked, :default + attr_accessible :name, :default, :template, :audit_comment, :location_ids, :organization_ids, :operatingsystem_ids, :snippet, :template_kind, :template_kind_id, :vendor, :operatingsystems validates :name, :presence => true validates :template, :presence => true diff --git a/app/models/template_combination.rb b/app/models/template_combination.rb index 104f6ed6d86d..01bd0a989a7e 100644 --- a/app/models/template_combination.rb +++ b/app/models/template_combination.rb @@ -1,7 +1,10 @@ class TemplateCombination < ActiveRecord::Base + attr_accessible :environment_id, :hostgroup_id, :hostgroup, :environment + belongs_to :provisioning_template belongs_to :environment belongs_to :hostgroup + validates :environment_id, :uniqueness => {:scope => [:hostgroup_id, :provisioning_template_id]} validates :hostgroup_id, :uniqueness => {:scope => [:environment_id, :provisioning_template_id]} end diff --git a/app/models/template_kind.rb b/app/models/template_kind.rb index 7c1e5a91413d..4013b0d4c155 100644 --- a/app/models/template_kind.rb +++ b/app/models/template_kind.rb @@ -4,6 +4,7 @@ class TemplateKind < ActiveRecord::Base validates_lengths_from_database has_many :provisioning_templates, :inverse_of => :template_kind has_many :os_default_templates + validates :name, :presence => true, :uniqueness => true scoped_search :on => :name end diff --git a/app/models/token.rb b/app/models/token.rb index 4cc7521518d2..f41538e32e76 100644 --- a/app/models/token.rb +++ b/app/models/token.rb @@ -1,5 +1,4 @@ class Token < ActiveRecord::Base - attr_accessible :value, :expires validates_lengths_from_database belongs_to_host :foreign_key => :host_id diff --git a/app/models/trend_counter.rb b/app/models/trend_counter.rb index 50ef51b7e058..df95635e5fde 100644 --- a/app/models/trend_counter.rb +++ b/app/models/trend_counter.rb @@ -1,5 +1,6 @@ class TrendCounter < ActiveRecord::Base belongs_to :trend + validates :count, :numericality => {:greater_than_or_equal_to => 0} validates :created_at, :uniqueness => {:scope => :trend_id} default_scope -> { order(:created_at) } diff --git a/app/models/user.rb b/app/models/user.rb index c13ef1f73b4e..b4b5bade99d0 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -26,10 +26,10 @@ class User < ActiveRecord::Base has_many :auditable_changes, :class_name => '::Audit', :as => :user has_many :direct_hosts, :class_name => 'Host', :as => :owner has_many :usergroup_member, :dependent => :destroy, :as => :member - has_many :user_roles, :dependent => :destroy, :foreign_key => 'owner_id', :conditions => {:owner_type => self.to_s} + has_many :user_roles, -> { where(:owner_type => 'User') }, :dependent => :destroy, :foreign_key => 'owner_id' has_many :cached_user_roles, :dependent => :destroy has_many :cached_usergroups, :through => :cached_usergroup_members, :source => :usergroup - has_many :cached_roles, :through => :cached_user_roles, :source => :role, :uniq => true + has_many :cached_roles, -> { uniq }, :through => :cached_user_roles, :source => :role has_many :usergroups, :through => :usergroup_member, :dependent => :destroy has_many :roles, :through => :user_roles, :dependent => :destroy has_many :filters, :through => :cached_roles @@ -41,6 +41,12 @@ class User < ActiveRecord::Base has_many :mail_notifications, :through => :user_mail_notifications accepts_nested_attributes_for :user_mail_notifications, :allow_destroy => true, :reject_if => :reject_empty_intervals + attr_accessible :password, :password_confirmation, :login, :firstname, + :lastname, :mail, :locale, :timezone, :auth_source_id, + :mail_enabled, :location_ids, :default_location_id, + :organization_ids, :default_organization_id, :auth_source, + :default_location_id, :default_organization_id, :role_ids, + :mail_notification_ids, :locations, :organizations attr_name :login @@ -386,7 +392,7 @@ def self.random_password(size = 16) end def expire_topbar_cache(sweeper) - sweeper.expire_fragment(TopbarSweeper.fragment_name(id)) + ActionController::Base.new.expire_fragment(TopbarSweeper.fragment_name(id)) end def external_usergroups diff --git a/app/models/user_mail_notification.rb b/app/models/user_mail_notification.rb index b3869fb43d19..4c1afbc6a630 100644 --- a/app/models/user_mail_notification.rb +++ b/app/models/user_mail_notification.rb @@ -1,10 +1,8 @@ class UserMailNotification < ActiveRecord::Base - attr_accessible :last_sent, :mail_notification_id, :user_id, :interval, :mail_query - belongs_to :user belongs_to :mail_notification - validates :user_id, :presence => true + validates :user, :presence => true validates :mail_notification, :presence => true scope :daily, -> { where(:interval => 'Daily') } diff --git a/app/models/user_role.rb b/app/models/user_role.rb index 5478a528c40d..b49180c46ebd 100644 --- a/app/models/user_role.rb +++ b/app/models/user_role.rb @@ -59,7 +59,7 @@ def cache_user_roles! end def build_user_role_cache - [ self.cached_user_roles.build(:user => owner, :role => role) ] + [ self.cached_user_roles.build(:user_id => owner.id, :role_id => role.id) ] end def build_user_group_role_cache(owner) diff --git a/app/models/usergroup.rb b/app/models/usergroup.rb index ad724f0cf19e..f7eed1fbd154 100644 --- a/app/models/usergroup.rb +++ b/app/models/usergroup.rb @@ -5,10 +5,12 @@ class Usergroup < ActiveRecord::Base friendly_id :name include Parameterizable::ByIdName + attr_accessible :name, :admin, :user_ids, :role_ids, :usergroup_ids + validates_lengths_from_database before_destroy EnsureNotUsedBy.new(:hosts), :ensure_last_admin_group_is_not_deleted - has_many :user_roles, :dependent => :destroy, :foreign_key => 'owner_id', :conditions => {:owner_type => self.to_s} + has_many :user_roles, -> { where(:owner_type => 'Usergroup') }, :dependent => :destroy, :foreign_key => 'owner_id' has_many :roles, :through => :user_roles, :dependent => :destroy has_many :usergroup_members, :dependent => :destroy @@ -16,12 +18,15 @@ class Usergroup < ActiveRecord::Base has_many :usergroups, :through => :usergroup_members, :source => :member, :source_type => 'Usergroup', :dependent => :destroy has_many :external_usergroups, :dependent => :destroy, :inverse_of => :usergroup - has_many :cached_usergroup_members - has_many :usergroup_parents, :dependent => :destroy, :foreign_key => 'member_id', - :conditions => "member_type = 'Usergroup'", :class_name => 'UsergroupMember' + has_many :cached_usergroups, :through => :cached_usergroup_members, :source => :usergroup + has_many :cached_usergroup_members, :foreign_key => 'usergroup_id' + has_many :usergroup_parents, -> { where("member_type = 'Usergroup'") }, :dependent => :destroy, + :foreign_key => 'member_id', :class_name => 'UsergroupMember' has_many :parents, :through => :usergroup_parents, :source => :usergroup, :dependent => :destroy has_many_hosts :as => :owner + attr_accessible :external_usergroups_attributes + validates :name, :uniqueness => true, :presence => true # The text item to see in a select dropdown menu diff --git a/app/models/usergroup_member.rb b/app/models/usergroup_member.rb index e27c25c99dd5..781bf438f35d 100644 --- a/app/models/usergroup_member.rb +++ b/app/models/usergroup_member.rb @@ -100,7 +100,7 @@ def find_all_user_roles end def find_all_user_roles_for(usergroup) - usergroup.user_roles + usergroup.parents.map { |g| find_all_user_roles_for(g) } + (UserRole.where(:owner => usergroup )+ usergroup.parents.map { |g| find_all_user_roles_for(g) }).flatten end def find_all_usergroups diff --git a/app/services/foreman/plugin.rb b/app/services/foreman/plugin.rb index d7bbae294a8f..4950b9e12bc3 100644 --- a/app/services/foreman/plugin.rb +++ b/app/services/foreman/plugin.rb @@ -218,7 +218,7 @@ def role(name, permissions) end def pending_migrations - migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations + migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations(ActiveRecord::Migrator.migrations_paths)).pending_migrations migrations.size > 0 end diff --git a/app/services/tax_host.rb b/app/services/tax_host.rb index 010b40d03726..11c8a1ec17f7 100644 --- a/app/services/tax_host.rb +++ b/app/services/tax_host.rb @@ -154,8 +154,9 @@ def non_inherited_ids(v1 = self.selected_ids, v2 = self.inherited_ids) # populate used_ids for 3 non-standard_id's def user_ids(hosts = self.hosts) - #TODO: when migrating to rails 3.1+ switch to inner select on users. - User.unscoped.joins(:direct_hosts).where({ :hosts => { :id => hosts }, :users => { :admin => false } }).pluck('DISTINCT users.id') + User.unscoped.except_admin. + eager_load(:direct_hosts).where(:hosts => { :id => hosts.map(&:id) }). + pluck('DISTINCT users.id') end def provisioning_template_ids(hosts = self.hosts) diff --git a/app/views/api/v2/interfaces/base.json.rabl b/app/views/api/v2/interfaces/base.json.rabl index 43dcaf324f2c..2181267775cf 100644 --- a/app/views/api/v2/interfaces/base.json.rabl +++ b/app/views/api/v2/interfaces/base.json.rabl @@ -2,5 +2,6 @@ object @interface attributes :id, :name, :ip, :mac, :identifier, :primary, :provision node :type do |i| + next if i.is_a? Symbol i.class.humanized_name.downcase end diff --git a/bundler.d/assets.rb b/bundler.d/assets.rb index 12b81fc482e0..f1fa7e7985be 100644 --- a/bundler.d/assets.rb +++ b/bundler.d/assets.rb @@ -1,21 +1,21 @@ group :assets do gem 'ace-rails-ap', '~> 4.0.0' - gem 'sass-rails', '~> 3.2' + gem 'sass-rails' gem 'uglifier', '>= 1.0.3' gem 'execjs', '>= 1.4.0', '<2.5.0' gem 'jquery-rails', '2.0.3' gem 'jquery-ui-rails', '< 5.0.0' gem 'bootstrap-sass', '3.0.3.0' - gem 'spice-html5-rails', '~> 0.1.4' + gem 'spice-html5-rails', '~> 0.1.5' gem 'flot-rails', '0.0.3' gem 'quiet_assets', '~> 1.0' - gem 'gettext_i18n_rails_js', '~> 0.0', '>= 0.0.8' + gem 'gettext_i18n_rails_js', '~> 1.0.0' # unspecified dep of gettext_i18n_rails_js # https://github.com/nubis/gettext_i18n_rails_js/pull/23 gem 'gettext', '~> 3.1', :require => false gem 'multi-select-rails', '~> 0.9' - gem 'gridster-rails', '~> 0.1' - gem 'jquery_pwstrength_bootstrap', '~> 1.2' + gem 'gridster-rails', github: "hampei/gridster-rails", branch: "rails4" # TODO + gem 'jquery_pwstrength_bootstrap', github: "unorthodoxgeek/jquery_pwstrength_bootstrap-gem" #TODO gem 'jquery-turbolinks', '~> 2.1' gem 'select2-rails', '~> 3.5' gem 'underscore-rails', '~> 1.8' diff --git a/bundler.d/console.rb b/bundler.d/console.rb index 40d40e295c27..1affb5c30be3 100644 --- a/bundler.d/console.rb +++ b/bundler.d/console.rb @@ -2,7 +2,4 @@ gem 'wirb', '~> 1.0' gem 'hirb-unicode', '~> 0.0.5' gem 'awesome_print', '~> 1.0', :require => 'ap' - - # minitest - workaround until Rails 4.0 (#2650) - gem 'minitest', '~> 4.7', :require => 'minitest/unit' end diff --git a/bundler.d/test.rb b/bundler.d/test.rb index 81c6664b94bb..fb828aca4d82 100644 --- a/bundler.d/test.rb +++ b/bundler.d/test.rb @@ -3,9 +3,9 @@ gem 'simplecov', '~> 0.9' gem 'spork-minitest', '0.0.3' gem 'single_test', '~> 0.6' - gem 'minitest', '~> 4.7' - gem 'minitest-spec-rails', '~> 4.7' - gem 'ci_reporter', '>= 1.6.3', '< 2.0.0', :require => false + gem 'minitest', '~> 5.1.0' + gem 'minitest-spec-rails' + gem 'ci_reporter_minitest', :require => false gem 'capybara', '~> 2.0' gem 'database_cleaner', '~> 1.3' gem 'launchy', '~> 2.4' diff --git a/config/application.rb b/config/application.rb index 8734ca1a7cec..45fde6abd143 100644 --- a/config/application.rb +++ b/config/application.rb @@ -85,7 +85,9 @@ module Foreman class Application < Rails::Application # Setup additional routes by loading all routes file from routes directory - config.paths["config/routes"] += Dir[Rails.root.join("config/routes/**/*.rb")] + Dir["#{Rails.root}/config/routes/**/*.rb"].each do |route_file| + config.paths['config/routes.rb'] << route_file + end # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers diff --git a/config/environments/development.rb b/config/environments/development.rb index dee9b93b32e4..f4267c0a8869 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -30,13 +30,6 @@ # Expands the lines which load the assets config.assets.debug = true - # Raise exception on mass assignment protection for Active Record models - config.active_record.mass_assignment_sanitizer = :strict - - # Log the query plan for queries taking more than this (works - # with SQLite, MySQL, and PostgreSQL) - config.active_record.auto_explain_threshold_in_seconds = 0.5 - config.after_initialize do Bullet.enable = true Bullet.bullet_logger = true diff --git a/config/environments/test.rb b/config/environments/test.rb index 8f97d032ef29..901e75c3c362 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -41,12 +41,10 @@ config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" - # Raise exception on mass assignment protection for Active Record models - config.active_record.mass_assignment_sanitizer = :strict - #enables a few aliases - context, should, and should_eventually methods config.minitest_spec_rails.mini_shoulda = true # Use separate cache stores for parallel_tests config.cache_store = :file_store, Rails.root.join("tmp", "cache", "paralleltests#{ENV['TEST_ENV_NUMBER']}") + config.active_record.mass_assignment_sanitizer = :strict end diff --git a/config/initializers/active_record_extensions.rb b/config/initializers/active_record_extensions.rb index 7881a3f5f194..e280fbde2c98 100644 --- a/config/initializers/active_record_extensions.rb +++ b/config/initializers/active_record_extensions.rb @@ -4,3 +4,38 @@ class ActiveRecord::Base include StripWhitespace include Parameterizable::ById end + +# Fixes the issue with custom counter cache column names +module ActiveRecord::Associations::Builder + class BelongsTo < SingularAssociation + def self.add_counter_cache_callbacks(model, reflection) + cache_column = reflection.counter_cache_column + + model.after_create lambda { |record| + record.belongs_to_counter_cache_after_create(reflection) + } + + model.before_destroy lambda { |record| + record.belongs_to_counter_cache_before_destroy(reflection) + } + + #model.after_update lambda { |record| + # record.belongs_to_counter_cache_after_update(reflection) + #} + + klass = reflection.class_name.safe_constantize + klass.attr_readonly cache_column if klass && klass.respond_to?(:attr_readonly) + end + end +end + +module ActiveRecord + module Delegation # :nodoc: + module DelegateCache + def relation_delegate_class(klass) # :nodoc: + initialize_relation_delegate_cache if @relation_delegate_cache.nil? + @relation_delegate_cache[klass] + end + end + end +end diff --git a/config/initializers/routing_hash_for.rb b/config/initializers/routing_hash_for.rb new file mode 100644 index 000000000000..9c163e265bf4 --- /dev/null +++ b/config/initializers/routing_hash_for.rb @@ -0,0 +1,29 @@ +module ActionDispatch + module Routing + class RouteSet + class NamedRouteCollection + def define_url_helper(route, name, options) + helper = UrlHelper.create(route, options.dup) + + @module.remove_possible_method name + @module.module_eval do + define_method(name) do |*args| + helper.call self, args + end + + #because we heavily rely on the removed hash_for method in routes, we must add this monkey patch. + define_method("hash_for_#{name}") do |*args| + unless args.first.is_a? Hash + id = args.first.try(:to_param) + options[:id] = id if id.present? + end + helper.send(:handle_positional_args, self, args, options, []) + end + end + + helpers << name + end + end + end + end +end diff --git a/db/migrate/20110616080444_add_look_up_key_id_to_puppet_class.rb b/db/migrate/20110616080444_add_look_up_key_id_to_puppet_class.rb index e38216b4bb5b..0aa75dad8b88 100644 --- a/db/migrate/20110616080444_add_look_up_key_id_to_puppet_class.rb +++ b/db/migrate/20110616080444_add_look_up_key_id_to_puppet_class.rb @@ -11,7 +11,6 @@ def up add_column :lookup_keys, :validator_type, :string add_column :lookup_keys, :validator_rule, :string rename_column :lookup_values, :priority, :match - add_index :lookup_values, :match end def down diff --git a/db/migrate/20140219183343_migrate_permissions.rb b/db/migrate/20140219183343_migrate_permissions.rb index 08efe504367f..a7909ef10534 100644 --- a/db/migrate/20140219183343_migrate_permissions.rb +++ b/db/migrate/20140219183343_migrate_permissions.rb @@ -22,12 +22,12 @@ def resource_type @resource_type ||= permissions.first.try(:resource_type) end - taxonomy_join_table = "taxable_taxonomies" + taxonomy_join_table = :taxable_taxonomies has_many taxonomy_join_table, :dependent => :destroy, :as => :taxable, :foreign_key => 'taxable_id' - has_many :locations, :through => taxonomy_join_table, :source => :taxonomy, - :conditions => "taxonomies.type='Location'", :validate => false - has_many :organizations, :through => taxonomy_join_table, :source => :taxonomy, - :conditions => "taxonomies.type='Organization'", :validate => false + has_many :locations, -> { where("taxonomies.type='Location'") }, :through => taxonomy_join_table, :source => :taxonomy, + :validate => false + has_many :organizations, -> { where("taxonomies.type='Organization'") }, :through => taxonomy_join_table, :source => :taxonomy, + :validate => false end class FakeUserRole < ActiveRecord::Base @@ -61,15 +61,15 @@ def self.name has_many :hostgroups, :through => :user_hostgroups has_many :user_facts, :dependent => :destroy, :foreign_key => 'user_id' has_many :facts, :through => :user_facts, :source => :fact_name - has_many :user_roles, :dependent => :destroy, :foreign_key => 'owner_id', - :conditions => {:owner_type => 'User'}, :class_name => 'FakeUserRole' + has_many :user_roles, -> { where(:owner_type => 'User') }, :dependent => :destroy, :foreign_key => 'owner_id', + :class_name => 'FakeUserRole' has_many :roles, :through => :user_roles, :dependent => :destroy, :class_name => 'FakeRole' - taxonomy_join_table = "taxable_taxonomies" + taxonomy_join_table = :taxable_taxonomies has_many taxonomy_join_table, :dependent => :destroy, :as => :taxable, :foreign_key => 'taxable_id' - has_many :locations, :through => taxonomy_join_table, :source => :taxonomy, - :conditions => "taxonomies.type='Location'", :validate => false - has_many :organizations, :through => taxonomy_join_table, :source => :taxonomy, - :conditions => "taxonomies.type='Organization'", :validate => false + has_many :locations, -> { where("taxonomies.type='Location'") }, :through => taxonomy_join_table, :source => :taxonomy, + :validate => false + has_many :organizations, -> { where("taxonomies.type='Organization'") }, :through => taxonomy_join_table, :source => :taxonomy, + :validate => false has_many :cached_usergroup_members, :foreign_key => 'user_id' has_many :cached_usergroups, :through => :cached_usergroup_members, :source => :usergroup end diff --git a/lib/middleware/catch_json_parse_errors.rb b/lib/middleware/catch_json_parse_errors.rb index 1fbab51cad62..9a5bdf591f6d 100644 --- a/lib/middleware/catch_json_parse_errors.rb +++ b/lib/middleware/catch_json_parse_errors.rb @@ -7,7 +7,7 @@ def initialize(app) def call(env) begin @app.call(env) - rescue MultiJson::LoadError, MultiJson::ParseError => error + rescue ActionDispatch::ParamsParser::ParseError => error if env['HTTP_ACCEPT'] =~ /application\/json/ || env['CONTENT_TYPE'] =~ /application\/json/ error_output = "There was a problem in the JSON you submitted: #{error}" Rails.logger.debug(error_output) diff --git a/lib/tasks/jenkins.rake b/lib/tasks/jenkins.rake index a653b592be9f..7371d6ed28f8 100644 --- a/lib/tasks/jenkins.rake +++ b/lib/tasks/jenkins.rake @@ -1,12 +1,6 @@ begin require "ci/reporter/rake/minitest" - namespace :foreman do - task :set_test_runner do - ENV['TESTOPTS'] = "#{ENV['TESTOPTS']} #{Rails.root}/test/test_runner.rb" - end - end - namespace :jenkins do task :unit => ["jenkins:setup:minitest", 'rake:test:units', 'rake:test:lib', 'rake:test:functionals'] task :integration => ["jenkins:setup:minitest", 'rake:test:integration'] @@ -19,7 +13,7 @@ begin ENV["CI_REPORTS"] = 'jenkins/reports/unit/' gem 'ci_reporter' end - task :minitest => [:pre_ci, "ci:setup:minitest", "foreman:set_test_runner"] + task :minitest => [:pre_ci, "ci:setup:minitest"] end task :rubocop do diff --git a/lib/tasks/test.rake b/lib/tasks/test.rake index 03ae8123f07f..b9ec3fb4f289 100644 --- a/lib/tasks/test.rake +++ b/lib/tasks/test.rake @@ -19,10 +19,3 @@ end Rake::Task[:test].enhance do Rake::Task['test:lib'].invoke end - -Rake::Task[:test].enhance ['foreman:set_test_runner'] -Rake::Task['test:units'].enhance ['foreman:set_test_runner'] -Rake::Task['test:functionals'].enhance ['foreman:set_test_runner'] -Rake::Task['test:integration'].enhance ['foreman:set_test_runner'] -Rake::Task['test:lib'].enhance ['foreman:set_test_runner'] -Rake::Task['test:api'].enhance ['foreman:set_test_runner'] diff --git a/test/functional/api/base_controller_subclass_test.rb b/test/functional/api/base_controller_subclass_test.rb index 989b6ba8ac86..ed5a3b3e8059 100644 --- a/test/functional/api/base_controller_subclass_test.rb +++ b/test/functional/api/base_controller_subclass_test.rb @@ -211,48 +211,42 @@ class Api::TestableControllerTest < ActionController::TestCase assert_equal @response.status, 200 end - it 'should return nested resource for unauthorized resource' do - child_associacion = mock('child_associacion') - testable_scope1 = mock('testable_scope1') - testable_scope2 = mock('testable_scope2') - testable_obj = mock('testable1') - - Testable.stubs(:joins).returns(child_associacion) - Testable.stubs(:where).returns(testable_scope2) - Testable.stubs(:scoped).returns(testable_scope2) - testable_scope2.stubs(:merge).returns(testable_scope1) - child_associacion.stubs(:merge).returns(testable_scope1) - testable_scope1.stubs(:readonly).returns(testable_scope1) + context 'nested resource permissions' do + setup do + @child_associacion = mock('child_associacion') + @testable_scope1 = mock('testable_scope1') + @testable_scope2 = mock('testable_scope2') + @testable_obj = mock('testable1') + @testable_scope2.stubs(:merge).returns(@testable_scope1) + @child_associacion.stubs(:merge).returns(@testable_scope1) + @testable_scope1.stubs(:readonly).returns(@testable_scope1) + @testable_scope1.expects(:find).with('1').returns(@testable_obj) + @testable_scope1.expects(:empty?).returns(false) + Testable.stubs(:joins).returns(@child_associacion) + end - testable_scope1.expects(:find).with('1').returns(testable_obj) + it 'should return nested resource for unauthorized resource' do + Testable.stubs(:where).returns(@testable_scope2) + Testable.stubs(:scoped).returns(@testable_scope2) - get :nested_values, :domain_id => 1, :id => 1 + get :nested_values, :domain_id => 1, :id => 1 - assert_equal testable_obj, @controller.instance_variable_get('@testable') - assert_equal @nested_obj, @controller.instance_variable_get('@nested_obj') - end - - it 'should return nested resource scope for authorized resource' do - child_auth_scope = mock('child_auth_scope') - child_associacion = mock('child_associacion') - testable_scope1 = mock('testable_scope1') - testable_scope2 = mock('testable_scope2') - testable_obj = mock('testable1') + assert_equal @testable_obj, @controller.instance_variable_get('@testable') + assert_equal @nested_obj, @controller.instance_variable_get('@nested_obj') + end - Testable.stubs(:authorized).returns(child_auth_scope) - Testable.stubs(:joins).returns(child_associacion) - testable_scope2.stubs(:merge).returns(testable_scope1) - child_associacion.stubs(:merge).returns(testable_scope1) - child_auth_scope.stubs(:where).returns(testable_scope2) - child_auth_scope.stubs(:scoped).returns(testable_scope2) - testable_scope1.stubs(:readonly).returns(testable_scope1) + it 'should return nested resource scope for authorized resource' do + child_auth_scope = mock('child_auth_scope') - testable_scope1.expects(:find).with('1').returns(testable_obj) + Testable.stubs(:authorized).returns(child_auth_scope) + child_auth_scope.stubs(:where).returns(@testable_scope2) + child_auth_scope.stubs(:scoped).returns(@testable_scope2) - get :nested_values, :domain_id => 1, :id => 1 + get :nested_values, :domain_id => 1, :id => 1 - assert_equal testable_obj, @controller.instance_variable_get('@testable') - assert_equal @nested_obj, @controller.instance_variable_get('@nested_obj') + assert_equal @testable_obj, @controller.instance_variable_get('@testable') + assert_equal @nested_obj, @controller.instance_variable_get('@nested_obj') + end end end diff --git a/test/functional/api/v2/smart_class_parameters_controller_test.rb b/test/functional/api/v2/smart_class_parameters_controller_test.rb index c757be0acadc..a153155648ca 100644 --- a/test/functional/api/v2/smart_class_parameters_controller_test.rb +++ b/test/functional/api/v2/smart_class_parameters_controller_test.rb @@ -64,7 +64,7 @@ class Api::V2::SmartClassParametersControllerTest < ActionController::TestCase get :index, {:puppetclass_id => non_existing_id} assert_response :not_found results = ActiveSupport::JSON.decode(@response.body) - assert_equal "Puppet class with id '#{non_existing_id}' was not found", results["error"]["message"] + assert_equal "Puppetclass with id '#{non_existing_id}' was not found", results["error"]["message"] end test "should get smart class parameters for a specific environment" do diff --git a/test/functional/api/v2/smart_proxies_controller_test.rb b/test/functional/api/v2/smart_proxies_controller_test.rb index 0a48d169328a..1902ece8ace9 100644 --- a/test/functional/api/v2/smart_proxies_controller_test.rb +++ b/test/functional/api/v2/smart_proxies_controller_test.rb @@ -181,7 +181,7 @@ def setup_import_classes test "should obsolete puppetclasses" do setup_import_classes as_admin do - assert_difference('Environment.find("env1").puppetclasses.count', -2) do + assert_difference('Environment.friendly.find("env1").puppetclasses.count', -2) do post :import_puppetclasses, {:id => smart_proxies(:puppetmaster).id}, set_session_user end end diff --git a/test/functional/provisioning_templates_controller_test.rb b/test/functional/provisioning_templates_controller_test.rb index 517d93a37f10..a1146eb8bec2 100644 --- a/test/functional/provisioning_templates_controller_test.rb +++ b/test/functional/provisioning_templates_controller_test.rb @@ -103,7 +103,7 @@ class ProvisioningTemplatesControllerTest < ActionController::TestCase Setting[:unattended_url] = "http://foreman.unattended.url" @request.env['HTTP_REFERER'] = provisioning_templates_path - ProxyAPI::TFTP.any_instance.expects(:create_default).with(has_entry(:menu, regexp_matches(/ks=http:\/\/foreman.unattended.url:80\/unattended\/template/))).returns(true) + ProxyAPI::TFTP.any_instance.expects(:create_default).with(has_entry(:menu, regexp_matches(/ks=http:\/\/foreman.unattended.url\/unattended\/template/))).returns(true) get :build_pxe_default, {}, set_session_user assert_redirected_to provisioning_templates_path diff --git a/test/functional/unattended_controller_test.rb b/test/functional/unattended_controller_test.rb index e8580f2528b7..171f19f7759e 100644 --- a/test/functional/unattended_controller_test.rb +++ b/test/functional/unattended_controller_test.rb @@ -243,7 +243,7 @@ class UnattendedControllerTest < ActionController::TestCase @request.env["REMOTE_ADDR"] = @ub_host.ip @ub_host.create_token(:value => token, :expires => Time.now + 5.minutes) get :provision, {'token' => @ub_host.token.value } - assert @response.body.include?("#{Setting[:unattended_url]}:443/unattended/finish?token=#{token}") + assert @response.body.include?("#{Setting[:unattended_url]}/unattended/finish?token=#{token}") end test "hosts with unknown ip and valid token should render a template" do @@ -314,7 +314,7 @@ class UnattendedControllerTest < ActionController::TestCase @request.env["REMOTE_ADDR"] = @ub_host.ip @ub_host.create_token(:value => "aaaaaa", :expires => Time.now + 5.minutes) get :provision - assert @response.body.include?("http://test.host:80/unattended/finish?token=aaaaaa") + assert @response.body.include?("http://test.host/unattended/finish?token=aaaaaa") end end # end of context "location or organizations are not enabled" diff --git a/test/lib/tasks/seeds_test.rb b/test/lib/tasks/seeds_test.rb index a1881308db96..1fc8e0a33e0f 100644 --- a/test/lib/tasks/seeds_test.rb +++ b/test/lib/tasks/seeds_test.rb @@ -9,6 +9,7 @@ class SeedsTest < ActiveSupport::TestCase DatabaseCleaner.clean_with :truncation Setting.stubs(:[]).with(:administrator).returns("root@localhost") Setting.stubs(:[]).with(:send_welcome_email).returns(false) + Setting.stubs(:[]).with('entries_per_page').returns(20) end def seed diff --git a/test/test_helper.rb b/test/test_helper.rb index e80a643b9244..e3fc3ffdc64f 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,5 +1,6 @@ require 'rubygems' require 'spork' + # $LOAD_PATH required for testdrb party of spork-minitest $LOAD_PATH << "test" @@ -28,7 +29,7 @@ Capybara.register_driver :poltergeist do |app| Capybara::Poltergeist::Driver.new(app, {:js_errors => true, :timeout => 60}) end - Capybara.default_wait_time = 30 + Capybara.default_max_wait_time = 30 Capybara.javascript_driver = :poltergeist @@ -85,6 +86,8 @@ def clear_current_user alias_method :assert_not_nil, :refute_nil alias_method :assert_not_equal, :refute_equal alias_method :assert_raise, :assert_raises + alias_method :assert_include, :assert_includes + alias_method :assert_not_include, :assert_not_includes class < "test_0010_foo" and string => "foo" - if test[string] - puts "skipping #{self}##{test}" - string - end - end - end - end - end - end - end - - super(suites, type) - end - end -end - -MiniTest::Unit.runner = ForemanMiniTestRunner::Unit.new diff --git a/test/unit/application_mailer_test.rb b/test/unit/application_mailer_test.rb index ffc37f4e2e5f..98e1669295f9 100644 --- a/test/unit/application_mailer_test.rb +++ b/test/unit/application_mailer_test.rb @@ -3,10 +3,16 @@ class ApplicationMailerTest < ActiveSupport::TestCase setup { ActionMailer::Base.deliveries = [] } + class TestMailer < ::ApplicationMailer + def test + mail(:to => 'nobody@example.com', :subject => 'Danger, Will Robinson!') do |format| + format.text { render plain: "This is a test mail." } + end + end + end + def mail - ApplicationMailer.mail(:to => 'nobody@example.com', :subject => 'Danger, Will Robinson!') do |mail| - format.text "This is a test mail." - end.deliver + TestMailer.test.deliver ActionMailer::Base.deliveries.last end diff --git a/test/unit/fact_value_test.rb b/test/unit/fact_value_test.rb index fb6f74d6f6c3..942857d0b6e8 100644 --- a/test/unit/fact_value_test.rb +++ b/test/unit/fact_value_test.rb @@ -112,22 +112,22 @@ def setup end test "only return facts from host in user's taxonomies" do - user_role = FactoryGirl.create(:user_user_role) - FactoryGirl.create(:filter, :role => user_role.role, :permissions => Permission.where(:name => 'view_hosts'), :search => "hostgroup_id = #{target_host.hostgroup_id}") + setup_user('view', 'hosts', "hostgroup_id = #{target_host.hostgroup_id}") orgs = FactoryGirl.create_pair(:organization) locs = FactoryGirl.create_pair(:location) - target_host.update_attributes(:location => locs.last, :organization => orgs.last) - - user_role.owner.update_attributes(:locations => [locs.first], :organizations => [orgs.first]) - as_user user_role.owner do - assert_equal [], FactValue.my_facts.map(&:id).sort + as_admin do + [orgs, locs].map { |taxonomy| taxonomy.map { |t| t.update_attributes(:users => []) } } + users(:one).update_attributes(:locations => [], :organizations => []) + target_host.update_attributes(:location => locs.last, :organization => orgs.last) + Hostgroup.find(target_host.hostgroup_id).update_attributes(:organizations => [orgs.last], :locations => [locs.last]) end - user_role.owner.update_attributes(:locations => [locs.last], :organizations => [orgs.last]) - as_user user_role.owner do - assert_equal target_host.fact_values.map(&:id).sort, FactValue.my_facts.map(&:id).sort - end + users(:one).update_attributes(:locations => [locs.first], :organizations => [orgs.first]) + assert_equal [], FactValue.my_facts.map(&:id).sort + + users(:one).update_attributes(:locations => [locs.last], :organizations => [orgs.last]) + assert_equal target_host.fact_values.map(&:id).sort, FactValue.my_facts.map(&:id).sort end test "only return facts from host in admin's currently selected taxonomy" do diff --git a/test/unit/helpers/layout_helper_test.rb b/test/unit/helpers/layout_helper_test.rb index cf0658accbe9..e54ab03182c5 100644 --- a/test/unit/helpers/layout_helper_test.rb +++ b/test/unit/helpers/layout_helper_test.rb @@ -15,12 +15,12 @@ class LayoutHelperTest < ActionView::TestCase end test "is_required?(f, attr) method returns true if attribute is required and false if not required" do - f = ActionView::Helpers::FormBuilder.new(:hostgroup, Hostgroup.new, @hostgroup, {}, {}) + f = ActionView::Helpers::FormBuilder.new(:hostgroup, Hostgroup.new, @hostgroup, {}) assert is_required?(f, :name) assert is_required?(f, :title) refute is_required?(f, :environment_id) refute is_required?(f, :parent_id) - f = ActionView::Helpers::FormBuilder.new(:host, Host::Managed.new, @host, {}, {}) + f = ActionView::Helpers::FormBuilder.new(:host, Host::Managed.new, @host, {}) refute is_required?(f, :architecture_id) # not required because of :if refute is_required?(f, :mac) # not required because of :unless end diff --git a/test/unit/host_test.rb b/test/unit/host_test.rb index 78d254551e66..79bf847dc2d4 100644 --- a/test/unit/host_test.rb +++ b/test/unit/host_test.rb @@ -771,7 +771,7 @@ def teardown test "available_template_kinds finds templates for a PXE host" do os_dt = FactoryGirl.create(:os_default_template, - :template_kind=> TemplateKind.find('finish')) + :template_kind=> TemplateKind.friendly.find('finish')) host = FactoryGirl.create(:host, :operatingsystem => os_dt.operatingsystem) assert_equal [os_dt.provisioning_template], host.available_template_kinds('build') @@ -779,7 +779,7 @@ def teardown test "available_template_kinds finds templates for an image host" do os_dt = FactoryGirl.create(:os_default_template, - :template_kind=> TemplateKind.find('finish')) + :template_kind=> TemplateKind.friendly.find('finish')) host = FactoryGirl.create(:host, :on_compute_resource, :operatingsystem => os_dt.operatingsystem) FactoryGirl.create(:image, :uuid => 'abcde', @@ -1749,6 +1749,8 @@ def teardown test "test tokens are not created until host is saved" do class Host::Test < Host::Base + attr_accessible :interfaces + def lookup_value_match 'no_match' end @@ -2450,7 +2452,9 @@ def to_managed! test 'should accept non-existing hostgroup' do host = FactoryGirl.build(:host, :managed, :with_hostgroup) - Hostgroup.expects(:find).with(1111).returns(nil) + hostgroup_friendly_scope = stub + hostgroup_friendly_scope.stubs(:find).with(1111).returns(nil) + Hostgroup.stubs(:friendly).returns(hostgroup_friendly_scope) attributes = { 'hostgroup_id' => 1111 } actual_attr = host.apply_inherited_attributes(attributes)