diff --git a/Gemfile b/Gemfile index 3be707cdd..8575d13ca 100644 --- a/Gemfile +++ b/Gemfile @@ -1,4 +1,6 @@ -source "https://rubygems.org" +# frozen_string_literal: true + +source 'https://rubygems.org' gem 'rspec-its' # Specify gem dependencies in hydra-head.gemspec @@ -30,9 +32,9 @@ else case ENV['RAILS_VERSION'] when /^4.2/ + gem 'coffee-rails', '~> 4.1.0' gem 'responders', '~> 2.0' gem 'sass-rails', '>= 5.0' - gem 'coffee-rails', '~> 4.1.0' when /^4.[01]/ gem 'sass-rails', '< 5.0' end diff --git a/Rakefile b/Rakefile index df6ca3b84..43c7f40a6 100644 --- a/Rakefile +++ b/Rakefile @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'rake/testtask' begin require 'bundler/setup' @@ -6,31 +8,31 @@ rescue LoadError end Bundler::GemHelper.install_tasks -APP_ROOT= File.dirname(__FILE__) +APP_ROOT = File.dirname(__FILE__) require 'solr_wrapper' require 'fcrepo_wrapper' require 'active_fedora/rake_support' require 'engine_cart/rake_task' -desc "Run Continuous Integration" -task :ci => ['engine_cart:generate'] do - ENV['environment'] = "test" +desc 'Run Continuous Integration' +task ci: ['engine_cart:generate'] do + ENV['environment'] = 'test' with_test_server do Rake::Task['spec'].invoke end end -task :default => [:ci] +task default: [:ci] directory 'pkg' -FRAMEWORKS = ['hydra-access-controls', 'hydra-core'] +FRAMEWORKS = ['hydra-access-controls', 'hydra-core'].freeze -root = File.expand_path('../', __FILE__) +root = File.expand_path(__dir__) version = File.read("#{root}/HYDRA_VERSION").strip tag = "v#{version}" -(FRAMEWORKS + ['hydra-head']).each do |framework| +(FRAMEWORKS + ['hydra-head']).each do |framework| namespace framework do gem = "pkg/#{framework}-#{version}.gem" gemspec = "#{framework}.gemspec" @@ -41,54 +43,55 @@ tag = "v#{version}" task :update_version_rb do glob = root.dup - glob << "/#{framework}/lib/*" unless framework == "hydra-head" - glob << "/version.rb" + glob << "/#{framework}/lib/*" unless framework == 'hydra-head' + glob << '/version.rb' file = Dir[glob].first if file ruby = File.read(file) major, minor, tiny, pre = version.split('.') - pre = pre ? pre.inspect : "nil" + pre = pre ? pre.inspect : 'nil' ruby.gsub!(/^(\s*)VERSION = ".*?"$/, "\\1VERSION = \"#{version}\"") - raise "Could not insert VERSION in #{file}" unless $1 + raise "Could not insert VERSION in #{file}" unless Regexp.last_match(1) + File.open(file, 'w') { |f| f.write ruby } end end - task gem => %w(update_version_rb pkg) do - cmd = "" - cmd << "cd #{framework} && " unless framework == "hydra-head" + task gem => %w[update_version_rb pkg] do + cmd = '' + cmd << "cd #{framework} && " unless framework == 'hydra-head' cmd << "gem build #{gemspec} && mv #{framework}-#{version}.gem #{root}/pkg/" sh cmd end - task :build => [:clean, gem] - task :install => :build do + task build: [:clean, gem] + task install: :build do sh "gem install #{gem}" end - task :prep_release => [:ensure_clean_state, :build] + task prep_release: %i[ensure_clean_state build] - task :push => :build do + task push: :build do sh "gem push #{gem}" end end end namespace :all do - task :build => FRAMEWORKS.map { |f| "#{f}:build" } + ['hydra-head:build'] - task :install => FRAMEWORKS.map { |f| "#{f}:install" } + ['hydra-head:install'] - task :push => FRAMEWORKS.map { |f| "#{f}:push" } + ['hydra-head:push'] + task build: FRAMEWORKS.map { |f| "#{f}:build" } + ['hydra-head:build'] + task install: FRAMEWORKS.map { |f| "#{f}:install" } + ['hydra-head:install'] + task push: FRAMEWORKS.map { |f| "#{f}:push" } + ['hydra-head:push'] task :ensure_clean_state do unless `git status -s | grep -v HYDRA_VERSION | grep -v HISTORY.textile`.strip.empty? - abort "[ABORTING] `git status` reports a dirty tree. Make sure all changes are committed" + abort '[ABORTING] `git status` reports a dirty tree. Make sure all changes are committed' end unless ENV['SKIP_TAG'] || `git tag | grep "#{tag}$"`.strip.empty? abort "[ABORTING] `git tag` shows that #{tag} already exists. Has this version already\n"\ - " been released? Git tagging can be skipped by setting SKIP_TAG=1" + ' been released? Git tagging can be skipped by setting SKIP_TAG=1' end end @@ -96,29 +99,29 @@ namespace :all do File.open('pkg/commit_message.txt', 'w') do |f| f.puts "# Preparing for #{version} release\n" f.puts - f.puts "# UNCOMMENT THE LINE ABOVE TO APPROVE THIS COMMIT" + f.puts '# UNCOMMENT THE LINE ABOVE TO APPROVE THIS COMMIT' end - sh "git add . && git commit --verbose --template=pkg/commit_message.txt" - rm_f "pkg/commit_message.txt" + sh 'git add . && git commit --verbose --template=pkg/commit_message.txt' + rm_f 'pkg/commit_message.txt' end task :tag do sh "git tag #{tag}" - sh "git push --tags" + sh 'git push --tags' end - task :release => %w(ensure_clean_state build commit tag push) + task release: %w[ensure_clean_state build commit tag push] end -desc "run all specs" +desc 'run all specs' task :spec do - raise "test failures" unless all_modules("FCREPO_TEST_PORT=#{ENV['FCREPO_TEST_PORT']} SOLR_TEST_PORT=#{ENV['SOLR_TEST_PORT']} bundle exec rake spec") + raise 'test failures' unless all_modules("FCREPO_TEST_PORT=#{ENV['FCREPO_TEST_PORT']} SOLR_TEST_PORT=#{ENV['SOLR_TEST_PORT']} bundle exec rake spec") end -desc "Remove any existing test deploys" +desc 'Remove any existing test deploys' task :clean do - raise "test failures" unless all_modules('rake clean') + raise 'test failures' unless all_modules('rake clean') end def all_modules(cmd) @@ -133,25 +136,23 @@ end begin require 'yard' require 'yard/rake/yardoc_task' - project_root = File.expand_path(".") + project_root = File.expand_path('.') doc_destination = File.join(project_root, 'doc') - if !File.exists?(doc_destination) - FileUtils.mkdir_p(doc_destination) - end + FileUtils.mkdir_p(doc_destination) unless File.exist?(doc_destination) YARD::Rake::YardocTask.new(:doc) do |yt| - yt.files = ['*/lib/**/*.rb', project_root+"*", '*/app/**/*.rb'] - - yt.options << "-m" << "textile" - yt.options << "--protected" - yt.options << "--no-private" - yt.options << "-r" << "README.textile" - yt.options << "-o" << "doc" - yt.options << "--files" << "*.textile" + yt.files = ['*/lib/**/*.rb', project_root + '*', '*/app/**/*.rb'] + + yt.options << '-m' << 'textile' + yt.options << '--protected' + yt.options << '--no-private' + yt.options << '-r' << 'README.textile' + yt.options << '-o' << 'doc' + yt.options << '--files' << '*.textile' end rescue LoadError - desc "Generate YARD Documentation" + desc 'Generate YARD Documentation' task :doc do - abort "Please install the YARD gem to generate rdoc." + abort 'Please install the YARD gem to generate rdoc.' end end diff --git a/hydra-access-controls/Rakefile b/hydra-access-controls/Rakefile old mode 100644 new mode 100755 index 3ce17f054..070b5d9c2 --- a/hydra-access-controls/Rakefile +++ b/hydra-access-controls/Rakefile @@ -1,22 +1,24 @@ #!/usr/bin/env rake -require "bundler/gem_tasks" +# frozen_string_literal: true + +require 'bundler/gem_tasks' require 'rspec/core/rake_task' -APP_ROOT= File.expand_path(File.join(File.dirname(__FILE__),"..")) -import "tasks/hydra-access-controls.rake" +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) +import 'tasks/hydra-access-controls.rake' desc 'Default: run specs.' -task :default => :spec +task default: :spec -desc "Run specs" +desc 'Run specs' RSpec::Core::RakeTask.new do |t| - if ENV['COVERAGE'] and RUBY_VERSION =~ /^1.8/ + if ENV['COVERAGE'] && RUBY_VERSION =~ /^1.8/ t.rcov = true - t.rcov_opts = %w{--exclude spec\/*,gems\/*,ruby\/* --aggregate coverage.data} + t.rcov_opts = %w[--exclude spec\/*,gems\/*,ruby\/* --aggregate coverage.data] end end -desc "clean" +desc 'clean' task :clean do - #nop, required by hydra-head ci + # nop, required by hydra-head ci end diff --git a/hydra-access-controls/app/indexers/hydra/access_controls/embargo_indexer.rb b/hydra-access-controls/app/indexers/hydra/access_controls/embargo_indexer.rb index 52af73212..d2c76d901 100644 --- a/hydra-access-controls/app/indexers/hydra/access_controls/embargo_indexer.rb +++ b/hydra-access-controls/app/indexers/hydra/access_controls/embargo_indexer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::AccessControls class EmbargoIndexer def initialize(object) diff --git a/hydra-access-controls/app/indexers/hydra/access_controls/lease_indexer.rb b/hydra-access-controls/app/indexers/hydra/access_controls/lease_indexer.rb index e8cabf271..358f39e1e 100644 --- a/hydra-access-controls/app/indexers/hydra/access_controls/lease_indexer.rb +++ b/hydra-access-controls/app/indexers/hydra/access_controls/lease_indexer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::AccessControls class LeaseIndexer def initialize(object) @@ -9,4 +11,3 @@ def generate_solr_document end end end - diff --git a/hydra-access-controls/app/models/ability.rb b/hydra-access-controls/app/models/ability.rb index c5711a392..68d473854 100644 --- a/hydra-access-controls/app/models/ability.rb +++ b/hydra-access-controls/app/models/ability.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Allows you to use CanCan to control access to Models class Ability include Hydra::Ability diff --git a/hydra-access-controls/app/models/concerns/hydra/access_controls.rb b/hydra-access-controls/app/models/concerns/hydra/access_controls.rb index c19d3820b..170b984f2 100644 --- a/hydra-access-controls/app/models/concerns/hydra/access_controls.rb +++ b/hydra-access-controls/app/models/concerns/hydra/access_controls.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module AccessControls extend ActiveSupport::Autoload diff --git a/hydra-access-controls/app/models/concerns/hydra/access_controls/access_right.rb b/hydra-access-controls/app/models/concerns/hydra/access_controls/access_right.rb index 3d9922fc0..1fd23c8d4 100644 --- a/hydra-access-controls/app/models/concerns/hydra/access_controls/access_right.rb +++ b/hydra-access-controls/app/models/concerns/hydra/access_controls/access_right.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + module Hydra module AccessControls class AccessRight # What these groups are called in the Hydra rights assertions: - PERMISSION_TEXT_VALUE_PUBLIC = 'public'.freeze - PERMISSION_TEXT_VALUE_AUTHENTICATED = 'registered'.freeze + PERMISSION_TEXT_VALUE_PUBLIC = 'public' + PERMISSION_TEXT_VALUE_AUTHENTICATED = 'registered' # The values that get drawn to the page - VISIBILITY_TEXT_VALUE_PUBLIC = 'open'.freeze - VISIBILITY_TEXT_VALUE_EMBARGO = 'embargo'.freeze - VISIBILITY_TEXT_VALUE_LEASE = 'lease'.freeze - VISIBILITY_TEXT_VALUE_AUTHENTICATED = 'authenticated'.freeze - VISIBILITY_TEXT_VALUE_PRIVATE = 'restricted'.freeze + VISIBILITY_TEXT_VALUE_PUBLIC = 'open' + VISIBILITY_TEXT_VALUE_EMBARGO = 'embargo' + VISIBILITY_TEXT_VALUE_LEASE = 'lease' + VISIBILITY_TEXT_VALUE_AUTHENTICATED = 'authenticated' + VISIBILITY_TEXT_VALUE_PRIVATE = 'restricted' # @param permissionable [#visibility, #permissions] # @example @@ -24,9 +26,9 @@ def initialize(permissionable) delegate :persisted?, :permissions, :visibility, to: :permissionable protected :persisted?, :permissions, :visibility - def open_access? return true if has_visibility_text_for?(VISIBILITY_TEXT_VALUE_PUBLIC) + # We don't want to know if its under embargo, simply does it have a date. # In this way, we can properly inform the label input persisted_open_access_permission? && !permissionable.embargo_release_date.present? @@ -35,6 +37,7 @@ def open_access? def open_access_with_embargo_release_date? return false unless permissionable_is_embargoable? return true if has_visibility_text_for?(VISIBILITY_TEXT_VALUE_EMBARGO) + # We don't want to know if its under embargo, simply does it have a date. # In this way, we can properly inform the label input persisted_open_access_permission? && permissionable.embargo_release_date.present? @@ -42,47 +45,50 @@ def open_access_with_embargo_release_date? def authenticated_only? return false if open_access? + has_permission_text_for?(PERMISSION_TEXT_VALUE_AUTHENTICATED) || has_visibility_text_for?(VISIBILITY_TEXT_VALUE_AUTHENTICATED) end - alias :authenticated_only_access? :authenticated_only? + alias authenticated_only_access? authenticated_only? def private? return false if open_access? return false if authenticated_only? return false if open_access_with_embargo_release_date? + true end - alias :private_access? :private? + alias private_access? private? private - def persisted_open_access_permission? - if persisted? - has_permission_text_for?(PERMISSION_TEXT_VALUE_PUBLIC) - else - visibility.to_s == '' - end + def persisted_open_access_permission? + if persisted? + has_permission_text_for?(PERMISSION_TEXT_VALUE_PUBLIC) + else + visibility.to_s == '' end + end - def on_or_after_any_embargo_release_date? - return true unless permissionable.embargo_release_date - permissionable.embargo_release_date.to_date < Date.today - end + def on_or_after_any_embargo_release_date? + return true unless permissionable.embargo_release_date - def permissionable_is_embargoable? - permissionable.respond_to?(:embargo_release_date) - end + permissionable.embargo_release_date.to_date < Date.today + end - def has_visibility_text_for?(text) - visibility == text - end + def permissionable_is_embargoable? + permissionable.respond_to?(:embargo_release_date) + end - def has_permission_text_for?(text) - !!permissions.detect { |perm| perm.agent_name == text } - end + def has_visibility_text_for?(text) + visibility == text + end + + def has_permission_text_for?(text) + !!permissions.detect { |perm| perm.agent_name == text } + end end end end diff --git a/hydra-access-controls/app/models/concerns/hydra/access_controls/embargoable.rb b/hydra-access-controls/app/models/concerns/hydra/access_controls/embargoable.rb index c176223f3..9f95526cd 100644 --- a/hydra-access-controls/app/models/concerns/hydra/access_controls/embargoable.rb +++ b/hydra-access-controls/app/models/concerns/hydra/access_controls/embargoable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module AccessControls module Embargoable @@ -5,8 +7,8 @@ module Embargoable include Hydra::AccessControls::WithAccessRight included do - validates :lease_expiration_date, :'hydra/future_date' => true, if: :enforce_future_date_for_lease? - validates :embargo_release_date, :'hydra/future_date' => true, if: :enforce_future_date_for_embargo? + validates :lease_expiration_date, 'hydra/future_date': true, if: :enforce_future_date_for_lease? + validates :embargo_release_date, 'hydra/future_date': true, if: :enforce_future_date_for_embargo? belongs_to :embargo, predicate: Hydra::ACL.hasEmbargo, class_name: 'Hydra::AccessControls::Embargo' belongs_to :lease, predicate: Hydra::ACL.hasLease, class_name: 'Hydra::AccessControls::Lease' @@ -49,14 +51,13 @@ def lease_indexer_class end def under_embargo? - embargo && embargo.active? + embargo&.active? end def active_lease? - lease && lease.active? + lease&.active? end - # If changing away from embargo or lease, this will deactivate the lease/embargo before proceeding. # The lease_visibility! and embargo_visibility! methods rely on this to deactivate the lease when applicable. def visibility=(value) @@ -66,7 +67,7 @@ def visibility=(value) super end - def apply_embargo(release_date, visibility_during=nil, visibility_after=nil) + def apply_embargo(release_date, visibility_during = nil, visibility_after = nil) self.embargo_release_date = release_date self.visibility_during_embargo = visibility_during unless visibility_during.nil? self.visibility_after_embargo = visibility_after unless visibility_after.nil? @@ -77,13 +78,14 @@ def apply_embargo(release_date, visibility_during=nil, visibility_after=nil) # Deactivates the embargo and logs a message to the embargo object. # Marks this record as dirty so that it will get reindexed. def deactivate_embargo! - embargo && embargo.deactivate! + embargo&.deactivate! visibility_will_change! end # Validate that the current visibility is what is specified in the embargo def validate_visibility_complies_with_embargo return true unless embargo_release_date + if under_embargo? expected_visibility = visibility_during_embargo failure_message = "An embargo is in effect for this object until #{embargo_release_date}. Until that time the " @@ -92,8 +94,8 @@ def validate_visibility_complies_with_embargo failure_message = "The embargo expired on #{embargo_release_date}. The " end if visibility != expected_visibility - failure_message << "visibility should be #{expected_visibility} but it is currently #{visibility}. Call embargo_visibility! on this object to repair." - self.errors[:embargo] << failure_message + failure_message += "visibility should be #{expected_visibility} but it is currently #{visibility}. Call embargo_visibility! on this object to repair." + errors[:embargo] << failure_message return false end true @@ -102,17 +104,19 @@ def validate_visibility_complies_with_embargo # Set the current visibility to match what is described in the embargo. def embargo_visibility! return unless embargo_release_date + if under_embargo? - self.visibility_during_embargo = visibility_during_embargo ? visibility_during_embargo : Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE - self.visibility_after_embargo = visibility_after_embargo ? visibility_after_embargo : Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED + self.visibility_during_embargo = visibility_during_embargo || Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE + self.visibility_after_embargo = visibility_after_embargo || Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED self.visibility = visibility_during_embargo else - self.visibility = visibility_after_embargo ? visibility_after_embargo : Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED + self.visibility = visibility_after_embargo || Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED end end def validate_visibility_complies_with_lease return true unless lease_expiration_date + if active_lease? expected_visibility = visibility_during_lease failure_message = "A lease is in effect for this object until #{lease_expiration_date}. Until that time the " @@ -121,14 +125,14 @@ def validate_visibility_complies_with_lease failure_message = "The lease expired on #{lease_expiration_date}. The " end if visibility != expected_visibility - failure_message << "visibility should be #{expected_visibility} but it is currently #{visibility}. Call lease_visibility! on this object to repair." - self.errors[:lease] << failure_message + failure_message += "visibility should be #{expected_visibility} but it is currently #{visibility}. Call lease_visibility! on this object to repair." + errors[:lease] << failure_message return false end true end - def apply_lease(release_date, visibility_during=nil, visibility_after=nil) + def apply_lease(release_date, visibility_during = nil, visibility_after = nil) self.lease_expiration_date = release_date self.visibility_during_lease = visibility_during unless visibility_during.nil? self.visibility_after_lease = visibility_after unless visibility_after.nil? @@ -137,7 +141,7 @@ def apply_lease(release_date, visibility_during=nil, visibility_after=nil) end def deactivate_lease! - lease && lease.deactivate! + lease&.deactivate! visibility_will_change! end @@ -145,27 +149,26 @@ def deactivate_lease! def lease_visibility! if lease_expiration_date if active_lease? - self.visibility_during_lease = visibility_during_lease ? visibility_during_lease : Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED - self.visibility_after_lease = visibility_after_lease ? visibility_after_lease : Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE + self.visibility_during_lease = visibility_during_lease || Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED + self.visibility_after_lease = visibility_after_lease || Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE self.visibility = visibility_during_lease else - self.visibility = visibility_after_lease ? visibility_after_lease : Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE + self.visibility = visibility_after_lease || Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE end end end private - # @return [true, false] true if there is an embargo set up and the visibility will change - def deactivate_embargo?(value) - embargo && embargo.embargo_release_date && value != embargo.visibility_during_embargo - end - - # @return [true, false] true if there is a lease set up and the visibility will change - def deactivate_lease?(value) - lease && lease.lease_expiration_date && value != lease.visibility_during_lease - end + # @return [true, false] true if there is an embargo set up and the visibility will change + def deactivate_embargo?(value) + embargo&.embargo_release_date && value != embargo.visibility_during_embargo + end + # @return [true, false] true if there is a lease set up and the visibility will change + def deactivate_lease?(value) + lease&.lease_expiration_date && value != lease.visibility_during_lease + end end end end diff --git a/hydra-access-controls/app/models/concerns/hydra/access_controls/permissions.rb b/hydra-access-controls/app/models/concerns/hydra/access_controls/permissions.rb index 6e3c62475..92972dd4c 100644 --- a/hydra-access-controls/app/models/concerns/hydra/access_controls/permissions.rb +++ b/hydra-access-controls/app/models/concerns/hydra/access_controls/permissions.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module AccessControls module Permissions @@ -6,8 +8,8 @@ module Permissions included do belongs_to :access_control, predicate: ::ACL.accessControl, class_name: 'Hydra::AccessControl' - before_destroy do |obj| - access_control.destroy unless access_control.nil? + before_destroy do |_obj| + access_control&.destroy end after_save do # Only force save if autosave woudn't be called normally @@ -27,7 +29,7 @@ def permission_delegate def to_solr(solr_doc = {}) super.tap do |doc| - [:discover, :read, :edit].each do |access| + %i[discover read edit].each do |access| vals = send("#{access}_groups") doc[Hydra.config.permissions[access].group] = vals unless vals.empty? vals = send("#{access}_users") @@ -57,6 +59,7 @@ def permissions_attributes=(attributes_collection) end next if existing.blank? + selected = existing.find { |perm| perm.agent_name == prop[:name] } prop['id'] = selected.id if selected end @@ -356,7 +359,7 @@ def set_edit_users(users, eligible_users) protected def has_destroy_flag?(hash) - %w(1 true).include?(hash['_destroy'].to_s) + %w[1 true].include?(hash['_destroy'].to_s) end private @@ -432,24 +435,27 @@ def group_permissions def group_agent?(agent) raise 'no agent' unless agent.present? + agent.first.rdf_subject.to_s.start_with?(GROUP_AGENT_URL_PREFIX) end def person_agent?(agent) raise 'no agent' unless agent.present? + agent.first.rdf_subject.to_s.start_with?(PERSON_AGENT_URL_PREFIX) end # Removes any permissions if both a delete and an update are found for the same id # or if a delete is present without an id. def remove_bad_deletes(collection) - collection.delete_if { |permission| (has_destroy_flag?(permission) && !permission.has_key?(:id)) } + collection.delete_if { |permission| (has_destroy_flag?(permission) && !permission.key?(:id)) } collection.each do |permission| next unless has_destroy_flag?(permission) + delete_id = permission.fetch(:id, nil) - if collection.map { |c| c if c.fetch(:id, nil) == delete_id }.compact.count > 1 + if collection.map { |c| c if c.fetch(:id, nil) == delete_id }.compact.count > 1 collection.delete_if { |permission| permission.fetch(:id, nil) == delete_id } - end + end end end end diff --git a/hydra-access-controls/app/models/concerns/hydra/access_controls/visibility.rb b/hydra-access-controls/app/models/concerns/hydra/access_controls/visibility.rb index 78197449d..4b794da12 100644 --- a/hydra-access-controls/app/models/concerns/hydra/access_controls/visibility.rb +++ b/hydra-access-controls/app/models/concerns/hydra/access_controls/visibility.rb @@ -1,9 +1,12 @@ +# frozen_string_literal: true + module Hydra::AccessControls module Visibility extend ActiveSupport::Concern def visibility=(value) return if value.nil? + # only set explicit permissions case value when AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC @@ -33,33 +36,33 @@ def visibility_changed? private - # Override represented_visibility if you want to add another visibility that is - # represented as a read group (e.g. on-campus) - # @return [Array] a list of visibility types that are represented as read groups - def represented_visibility - [AccessRight::PERMISSION_TEXT_VALUE_AUTHENTICATED, - AccessRight::PERMISSION_TEXT_VALUE_PUBLIC] - end + # Override represented_visibility if you want to add another visibility that is + # represented as a read group (e.g. on-campus) + # @return [Array] a list of visibility types that are represented as read groups + def represented_visibility + [AccessRight::PERMISSION_TEXT_VALUE_AUTHENTICATED, + AccessRight::PERMISSION_TEXT_VALUE_PUBLIC] + end - def visibility_will_change! - @visibility_will_change = true - end + def visibility_will_change! + @visibility_will_change = true + end - def public_visibility! - visibility_will_change! unless visibility == AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC - remove_groups = represented_visibility - [AccessRight::PERMISSION_TEXT_VALUE_PUBLIC] - set_read_groups([AccessRight::PERMISSION_TEXT_VALUE_PUBLIC], remove_groups) - end + def public_visibility! + visibility_will_change! unless visibility == AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC + remove_groups = represented_visibility - [AccessRight::PERMISSION_TEXT_VALUE_PUBLIC] + set_read_groups([AccessRight::PERMISSION_TEXT_VALUE_PUBLIC], remove_groups) + end - def registered_visibility! - visibility_will_change! unless visibility == AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED - remove_groups = represented_visibility - [AccessRight::PERMISSION_TEXT_VALUE_AUTHENTICATED] - set_read_groups([AccessRight::PERMISSION_TEXT_VALUE_AUTHENTICATED], remove_groups) - end + def registered_visibility! + visibility_will_change! unless visibility == AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED + remove_groups = represented_visibility - [AccessRight::PERMISSION_TEXT_VALUE_AUTHENTICATED] + set_read_groups([AccessRight::PERMISSION_TEXT_VALUE_AUTHENTICATED], remove_groups) + end - def private_visibility! - visibility_will_change! unless visibility == AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE - set_read_groups([], represented_visibility) - end + def private_visibility! + visibility_will_change! unless visibility == AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE + set_read_groups([], represented_visibility) + end end end diff --git a/hydra-access-controls/app/models/concerns/hydra/access_controls/with_access_right.rb b/hydra-access-controls/app/models/concerns/hydra/access_controls/with_access_right.rb index 3417804c4..4c030419b 100644 --- a/hydra-access-controls/app/models/concerns/hydra/access_controls/with_access_right.rb +++ b/hydra-access-controls/app/models/concerns/hydra/access_controls/with_access_right.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module AccessControls module WithAccessRight @@ -7,14 +9,14 @@ module WithAccessRight include Hydra::AccessControls::Permissions end - delegate :open_access?, :open_access_with_embargo_release_date?, + delegate :open_access?, :open_access_with_embargo_release_date?, :authenticated_only_access?, :private_access?, to: :access_rights protected - def access_rights - @access_rights ||= AccessRight.new(self) - end + def access_rights + @access_rights ||= AccessRight.new(self) + end end end end diff --git a/hydra-access-controls/app/models/concerns/hydra/admin_policy_behavior.rb b/hydra-access-controls/app/models/concerns/hydra/admin_policy_behavior.rb index 3cc16d64b..f45113398 100644 --- a/hydra-access-controls/app/models/concerns/hydra/admin_policy_behavior.rb +++ b/hydra-access-controls/app/models/concerns/hydra/admin_policy_behavior.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module AdminPolicyBehavior extend ActiveSupport::Concern @@ -7,15 +9,15 @@ module AdminPolicyBehavior belongs_to :default_embargo, predicate: Hydra::ACL.hasEmbargo, class_name: 'Hydra::AccessControls::Embargo' end - def to_solr(solr_doc=Hash.new) + def to_solr(solr_doc = {}) f = merged_policies super.tap do |doc| - ['discover'.freeze, 'read'.freeze, 'edit'.freeze].each do |access| - doc[Hydra.config.permissions.inheritable[access.to_sym][:group]] = f[access]['group'.freeze] if f[access] - doc[Hydra.config.permissions.inheritable[access.to_sym][:individual]] = f[access]['person'.freeze] if f[access] + %w[discover read edit].each do |access| + doc[Hydra.config.permissions.inheritable[access.to_sym][:group]] = f[access]['group'] if f[access] + doc[Hydra.config.permissions.inheritable[access.to_sym][:individual]] = f[access]['person'] if f[access] end if default_embargo - key = Hydra.config.permissions.inheritable.embargo.release_date.sub(/_[^_]+$/, '') #Strip off the suffix + key = Hydra.config.permissions.inheritable.embargo.release_date.sub(/_[^_]+$/, '') # Strip off the suffix ActiveFedora::Indexing::Inserter.insert_field(doc, key, default_embargo.embargo_release_date, :stored_sortable) end end @@ -31,13 +33,12 @@ def merged_policies end end - ## Updates those permissions that are provided to it. Does not replace any permissions unless they are provided # @example # obj.default_permissions= [{:name=>"group1", :access=>"discover", :type=>'group'}, # {:name=>"group2", :access=>"discover", :type=>'group'}] def default_permissions=(params) - perm_hash = {'person' => defaultRights.users, 'group'=> defaultRights.groups} + perm_hash = { 'person' => defaultRights.users, 'group' => defaultRights.groups } params.each do |row| if row[:type] == 'user' || row[:type] == 'person' perm_hash['person'][row[:name]] = row[:access] diff --git a/hydra-access-controls/app/models/concerns/hydra/ip_based_ability.rb b/hydra-access-controls/app/models/concerns/hydra/ip_based_ability.rb index c6191a1d1..e9412f197 100644 --- a/hydra-access-controls/app/models/concerns/hydra/ip_based_ability.rb +++ b/hydra-access-controls/app/models/concerns/hydra/ip_based_ability.rb @@ -1,13 +1,15 @@ +# frozen_string_literal: true + module Hydra # include this on your ability class to add ip based groups to your user module IpBasedAbility - def user_groups @user_groups ||= super + ip_based_groups end def ip_based_groups return [] unless options.key?(:remote_ip) + IpBasedGroups.for(options.fetch(:remote_ip)) end end diff --git a/hydra-access-controls/app/models/concerns/hydra/rights.rb b/hydra-access-controls/app/models/concerns/hydra/rights.rb index 9b6005df7..72850dfcb 100644 --- a/hydra-access-controls/app/models/concerns/hydra/rights.rb +++ b/hydra-access-controls/app/models/concerns/hydra/rights.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module Rights extend ActiveSupport::Concern diff --git a/hydra-access-controls/app/models/concerns/hydra/with_depositor.rb b/hydra-access-controls/app/models/concerns/hydra/with_depositor.rb index 92d02c1f7..565db1f32 100644 --- a/hydra-access-controls/app/models/concerns/hydra/with_depositor.rb +++ b/hydra-access-controls/app/models/concerns/hydra/with_depositor.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::WithDepositor # Adds metadata about the depositor to the asset and # grants edit permissions to the +depositor+ @@ -5,9 +7,7 @@ module Hydra::WithDepositor def apply_depositor_metadata(depositor) depositor_id = depositor.respond_to?(:user_key) ? depositor.user_key : depositor - if respond_to? :depositor - self.depositor = depositor_id - end + self.depositor = depositor_id if respond_to? :depositor self.edit_users += [depositor_id] true end diff --git a/hydra-access-controls/app/models/hydra/access_control.rb b/hydra-access-controls/app/models/hydra/access_control.rb index a384c4233..932d1e12d 100644 --- a/hydra-access-controls/app/models/hydra/access_control.rb +++ b/hydra-access-controls/app/models/hydra/access_control.rb @@ -1,7 +1,8 @@ +# frozen_string_literal: true + module Hydra class AccessControl < ActiveFedora::Base - - before_destroy do |obj| + before_destroy do |_obj| contains.destroy_all end @@ -20,6 +21,7 @@ def permissions=(records) def permissions_attributes=(attribute_list) raise ArgumentError unless attribute_list.is_a? Array + any_destroyed = false attribute_list.each do |attributes| if attributes.key?(:id) @@ -68,6 +70,7 @@ def find(id) unless id.start_with?(@owner.id) raise ArgumentError, "requested ACL (#{id}) is not a member of #{@owner.id}" end + ActiveFedora::Base.find(id) end diff --git a/hydra-access-controls/app/models/hydra/access_controls/access_control_list.rb b/hydra-access-controls/app/models/hydra/access_controls/access_control_list.rb index a8c07392d..6eb1ae439 100644 --- a/hydra-access-controls/app/models/hydra/access_controls/access_control_list.rb +++ b/hydra-access-controls/app/models/hydra/access_controls/access_control_list.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::AccessControls class AccessControlList < ActiveFedora::Base belongs_to :access_to, predicate: ::ACL.accessTo, class_name: 'ActiveFedora::Base' diff --git a/hydra-access-controls/app/models/hydra/access_controls/embargo.rb b/hydra-access-controls/app/models/hydra/access_controls/embargo.rb index 7e7d74607..2e9498706 100644 --- a/hydra-access-controls/app/models/hydra/access_controls/embargo.rb +++ b/hydra-access-controls/app/models/hydra/access_controls/embargo.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + module Hydra::AccessControls class Embargo < ActiveFedora::Base - property :visibility_during_embargo, predicate: Hydra::ACL.visibilityDuringEmbargo, multiple:false - property :visibility_after_embargo, predicate: Hydra::ACL.visibilityAfterEmbargo, multiple:false - property :embargo_release_date, predicate: Hydra::ACL.embargoReleaseDate, multiple:false + property :visibility_during_embargo, predicate: Hydra::ACL.visibilityDuringEmbargo, multiple: false + property :visibility_after_embargo, predicate: Hydra::ACL.visibilityAfterEmbargo, multiple: false + property :embargo_release_date, predicate: Hydra::ACL.embargoReleaseDate, multiple: false property :embargo_history, predicate: Hydra::ACL.embargoHistory def embargo_release_date=(date) - date = DateTime.parse(date) if date.kind_of?(String) + date = DateTime.parse(date) if date.is_a?(String) super(date) end @@ -17,7 +19,8 @@ def active? # Deactivates the embargo and logs a message to the embargo_history property def deactivate! return unless embargo_release_date - embargo_state = active? ? "active" : "expired" + + embargo_state = active? ? 'active' : 'expired' embargo_record = embargo_history_message(embargo_state, Date.today, embargo_release_date, visibility_during_embargo, visibility_after_embargo) self.embargo_release_date = nil self.visibility_during_embargo = nil @@ -29,18 +32,19 @@ def to_hash {}.tap do |doc| date_field_name = Hydra.config.permissions.embargo.release_date.sub(/_dtsi/, '') ActiveFedora::Indexing::Inserter.insert_field(doc, date_field_name, embargo_release_date, :stored_sortable) - doc[ActiveFedora.index_field_mapper.solr_name("visibility_during_embargo", :symbol)] = visibility_during_embargo unless visibility_during_embargo.nil? - doc[ActiveFedora.index_field_mapper.solr_name("visibility_after_embargo", :symbol)] = visibility_after_embargo unless visibility_after_embargo.nil? - doc[ActiveFedora.index_field_mapper.solr_name("embargo_history", :symbol)] = embargo_history unless embargo_history.nil? + doc[ActiveFedora.index_field_mapper.solr_name('visibility_during_embargo', :symbol)] = visibility_during_embargo unless visibility_during_embargo.nil? + doc[ActiveFedora.index_field_mapper.solr_name('visibility_after_embargo', :symbol)] = visibility_after_embargo unless visibility_after_embargo.nil? + doc[ActiveFedora.index_field_mapper.solr_name('embargo_history', :symbol)] = embargo_history unless embargo_history.nil? end end + protected - # Create the log message used when deactivating an embargo - # This method may be overriden in order to transform the values of the passed parameters. - def embargo_history_message(state, deactivate_date, release_date, visibility_during, visibility_after) - I18n.t 'hydra.embargo.history_message', state: state, deactivate_date: deactivate_date, release_date: release_date, - visibility_during: visibility_during, visibility_after: visibility_after - end + # Create the log message used when deactivating an embargo + # This method may be overriden in order to transform the values of the passed parameters. + def embargo_history_message(state, deactivate_date, release_date, visibility_during, visibility_after) + I18n.t 'hydra.embargo.history_message', state: state, deactivate_date: deactivate_date, release_date: release_date, + visibility_during: visibility_during, visibility_after: visibility_after + end end end diff --git a/hydra-access-controls/app/models/hydra/access_controls/lease.rb b/hydra-access-controls/app/models/hydra/access_controls/lease.rb index 9b69672bd..8b504d963 100644 --- a/hydra-access-controls/app/models/hydra/access_controls/lease.rb +++ b/hydra-access-controls/app/models/hydra/access_controls/lease.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + module Hydra::AccessControls class Lease < ActiveFedora::Base - property :visibility_during_lease, predicate: Hydra::ACL.visibilityDuringLease, multiple:false - property :visibility_after_lease, predicate: Hydra::ACL.visibilityAfterLease, multiple:false - property :lease_expiration_date, predicate: Hydra::ACL.leaseExpirationDate, multiple:false + property :visibility_during_lease, predicate: Hydra::ACL.visibilityDuringLease, multiple: false + property :visibility_after_lease, predicate: Hydra::ACL.visibilityAfterLease, multiple: false + property :lease_expiration_date, predicate: Hydra::ACL.leaseExpirationDate, multiple: false property :lease_history, predicate: Hydra::ACL.leaseHistory def lease_expiration_date=(date) - date = DateTime.parse(date) if date.kind_of?(String) + date = DateTime.parse(date) if date.is_a?(String) super(date) end @@ -16,7 +18,8 @@ def active? def deactivate! return unless lease_expiration_date - lease_state = active? ? "active" : "expired" + + lease_state = active? ? 'active' : 'expired' lease_record = lease_history_message(lease_state, Date.today, lease_expiration_date, visibility_during_lease, visibility_after_lease) self.lease_expiration_date = nil self.visibility_during_lease = nil @@ -29,18 +32,19 @@ def to_hash date_field_name = Hydra.config.permissions.lease.expiration_date.sub(/_dtsi/, '') ActiveFedora::Indexing::Inserter.insert_field(doc, date_field_name, lease_expiration_date, :stored_sortable) - doc[ActiveFedora.index_field_mapper.solr_name("visibility_during_lease", :symbol)] = visibility_during_lease unless visibility_during_lease.nil? - doc[ActiveFedora.index_field_mapper.solr_name("visibility_after_lease", :symbol)] = visibility_after_lease unless visibility_after_lease.nil? - doc[ActiveFedora.index_field_mapper.solr_name("lease_history", :symbol)] = lease_history unless lease_history.nil? + doc[ActiveFedora.index_field_mapper.solr_name('visibility_during_lease', :symbol)] = visibility_during_lease unless visibility_during_lease.nil? + doc[ActiveFedora.index_field_mapper.solr_name('visibility_after_lease', :symbol)] = visibility_after_lease unless visibility_after_lease.nil? + doc[ActiveFedora.index_field_mapper.solr_name('lease_history', :symbol)] = lease_history unless lease_history.nil? end end protected - # Create the log message used when deactivating a lease - # This method may be overriden in order to transform the values of the passed parameters. - def lease_history_message(state, deactivate_date, expiration_date, visibility_during, visibility_after) - I18n.t 'hydra.lease.history_message', state: state, deactivate_date: deactivate_date, expiration_date: expiration_date, - visibility_during: visibility_during, visibility_after: visibility_after - end + + # Create the log message used when deactivating a lease + # This method may be overriden in order to transform the values of the passed parameters. + def lease_history_message(state, deactivate_date, expiration_date, visibility_during, visibility_after) + I18n.t 'hydra.lease.history_message', state: state, deactivate_date: deactivate_date, expiration_date: expiration_date, + visibility_during: visibility_during, visibility_after: visibility_after + end end end diff --git a/hydra-access-controls/app/models/hydra/access_controls/permission.rb b/hydra-access-controls/app/models/hydra/access_controls/permission.rb index cf957d803..658b92e30 100644 --- a/hydra-access-controls/app/models/hydra/access_controls/permission.rb +++ b/hydra-access-controls/app/models/hydra/access_controls/permission.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + module Hydra::AccessControls - AGENT_URL_PREFIX = 'http://projecthydra.org/ns/auth/'.freeze - GROUP_AGENT_URL_PREFIX = 'http://projecthydra.org/ns/auth/group'.freeze - PERSON_AGENT_URL_PREFIX = 'http://projecthydra.org/ns/auth/person'.freeze + AGENT_URL_PREFIX = 'http://projecthydra.org/ns/auth/' + GROUP_AGENT_URL_PREFIX = 'http://projecthydra.org/ns/auth/group' + PERSON_AGENT_URL_PREFIX = 'http://projecthydra.org/ns/auth/person' class Permission < AccessControlList has_many :admin_policies, inverse_of: :default_permissions, class_name: 'Hydra::AdminPolicy' @@ -69,6 +71,7 @@ def parsed_agent def build_agent(name, type) raise "Can't build agent #{inspect}" unless name && type + self.agent = case type when 'group' build_agent_resource(GROUP_AGENT_URL_PREFIX, name) @@ -85,6 +88,7 @@ def build_agent_resource(prefix, name) def build_access(access) raise "Can't build access #{inspect}" unless access + self.mode = case access when 'read' [Mode.new(::ACL.Read)] diff --git a/hydra-access-controls/app/models/hydra/permissions_solr_document.rb b/hydra-access-controls/app/models/hydra/permissions_solr_document.rb index 55f3cfe86..33127988a 100644 --- a/hydra-access-controls/app/models/hydra/permissions_solr_document.rb +++ b/hydra-access-controls/app/models/hydra/permissions_solr_document.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + class Hydra::PermissionsSolrDocument < SolrDocument def under_embargo? - #permissions = permissions_doc(params[:id]) + # permissions = permissions_doc(params[:id]) embargo_key = Hydra.config.permissions.embargo.release_date if self[embargo_key] embargo_date = Date.parse(self[embargo_key].split(/T/)[0]) diff --git a/hydra-access-controls/app/models/role_mapper.rb b/hydra-access-controls/app/models/role_mapper.rb index f7f5b3fa0..236d52b1d 100644 --- a/hydra-access-controls/app/models/role_mapper.rb +++ b/hydra-access-controls/app/models/role_mapper.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + # RoleMapper This is used by AccessControlsEnforcement to get users' Roles (used in access permissions) -# If you are using something like Shibboleth or LDAP to get users' Roles, you should override this Class. -# Your override should include a Module that implements the same behaviors as Hydra::RoleMapperBehavior +# If you are using something like Shibboleth or LDAP to get users' Roles, you should override this Class. +# Your override should include a Module that implements the same behaviors as Hydra::RoleMapperBehavior class RoleMapper include Hydra::RoleMapperBehavior end diff --git a/hydra-access-controls/app/services/hydra/embargo_service.rb b/hydra-access-controls/app/services/hydra/embargo_service.rb index 3132729bc..800dbdbd0 100644 --- a/hydra-access-controls/app/services/hydra/embargo_service.rb +++ b/hydra-access-controls/app/services/hydra/embargo_service.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module EmbargoService class << self diff --git a/hydra-access-controls/app/services/hydra/lease_service.rb b/hydra-access-controls/app/services/hydra/lease_service.rb index 802a71d2b..49494f958 100644 --- a/hydra-access-controls/app/services/hydra/lease_service.rb +++ b/hydra-access-controls/app/services/hydra/lease_service.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module LeaseService class << self @@ -20,4 +22,3 @@ def assets_with_deactivated_leases end end end - diff --git a/hydra-access-controls/app/validators/hydra/future_date_validator.rb b/hydra-access-controls/app/validators/hydra/future_date_validator.rb index 823e5195e..854386fd2 100644 --- a/hydra-access-controls/app/validators/hydra/future_date_validator.rb +++ b/hydra-access-controls/app/validators/hydra/future_date_validator.rb @@ -1,18 +1,19 @@ +# frozen_string_literal: true + module Hydra class FutureDateValidator < ActiveModel::EachValidator - def validate_each(record, attribute, value) if value.present? begin if date = value.to_date if date <= Date.today - record.errors[attribute] << "Must be a future date" + record.errors[attribute] << 'Must be a future date' end else - record.errors[attribute] << "Invalid Date Format" + record.errors[attribute] << 'Invalid Date Format' end rescue ArgumentError, NoMethodError - record.errors[attribute] << "Invalid Date Format" + record.errors[attribute] << 'Invalid Date Format' end end end diff --git a/hydra-access-controls/app/vocabularies/acl.rb b/hydra-access-controls/app/vocabularies/acl.rb index 91b3d5c14..4e2d1e6b7 100644 --- a/hydra-access-controls/app/vocabularies/acl.rb +++ b/hydra-access-controls/app/vocabularies/acl.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class ACL < RDF::StrictVocabulary('http://www.w3.org/ns/auth/acl#') property :accessTo property :mode diff --git a/hydra-access-controls/app/vocabularies/hydra/acl.rb b/hydra-access-controls/app/vocabularies/hydra/acl.rb index d559b7f36..5e6924268 100644 --- a/hydra-access-controls/app/vocabularies/hydra/acl.rb +++ b/hydra-access-controls/app/vocabularies/hydra/acl.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra class ACL < RDF::StrictVocabulary('http://projecthydra.org/ns/auth/acl#') property :Discover # extends http://www.w3.org/ns/auth/acl#Access diff --git a/hydra-access-controls/hydra-access-controls.gemspec b/hydra-access-controls/hydra-access-controls.gemspec index 1066a52b7..9adc8cb1b 100644 --- a/hydra-access-controls/hydra-access-controls.gemspec +++ b/hydra-access-controls/hydra-access-controls.gemspec @@ -1,30 +1,31 @@ -# -*- encoding: utf-8 -*- -version = File.read(File.expand_path("../../HYDRA_VERSION", __FILE__)).strip +# frozen_string_literal: true + +version = File.read(File.expand_path('../HYDRA_VERSION', __dir__)).strip Gem::Specification.new do |gem| - gem.authors = ["Chris Beer", "Justin Coyne", "Matt Zumwalt"] - gem.email = ["hydra-tech@googlegroups.com"] - gem.description = %q{Access controls for project hydra} - gem.summary = %q{Access controls for project hydra} - gem.homepage = "http://projecthydra.org" + gem.authors = ['Chris Beer', 'Justin Coyne', 'Matt Zumwalt'] + gem.email = ['hydra-tech@googlegroups.com'] + gem.description = 'Access controls for project hydra' + gem.summary = 'Access controls for project hydra' + gem.homepage = 'http://projecthydra.org' - gem.files = `git ls-files`.split($\) - gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } + gem.files = `git ls-files`.split($OUTPUT_RECORD_SEPARATOR) + gem.executables = gem.files.grep(%r{^bin/}).map { |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) - gem.name = "hydra-access-controls" - gem.require_paths = ["lib"] + gem.name = 'hydra-access-controls' + gem.require_paths = ['lib'] gem.version = version - gem.license = "APACHE-2.0" + gem.license = 'APACHE-2.0' gem.required_ruby_version = '>= 1.9.3' + gem.add_dependency 'active-fedora', '>= 10.0.0', '< 13' gem.add_dependency 'activesupport', '>= 4', '< 6' - gem.add_dependency "active-fedora", '>= 10.0.0', '< 13' - gem.add_dependency "blacklight", '>= 5.16' - gem.add_dependency "blacklight-access_controls", '~> 0.6.0' + gem.add_dependency 'blacklight', '>= 5.16' + gem.add_dependency 'blacklight-access_controls', '~> 0.6.0' gem.add_dependency 'cancancan', '~> 1.8' gem.add_dependency 'deprecation', '~> 1.0' - gem.add_development_dependency "rake", '~> 10.1' + gem.add_development_dependency 'rake', '~> 10.1' gem.add_development_dependency 'rspec', '~> 3.1' end diff --git a/hydra-access-controls/lib/active_fedora/accessible_by.rb b/hydra-access-controls/lib/active_fedora/accessible_by.rb index 2833bbdb1..a8f50385b 100644 --- a/hydra-access-controls/lib/active_fedora/accessible_by.rb +++ b/hydra-access-controls/lib/active_fedora/accessible_by.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + ActiveFedora::QueryMethods.module_eval do extend ActiveSupport::Concern included do @@ -6,16 +8,16 @@ def accessible_by(ability, action = :index) permission_types = case action - when :index then [:discover, :read, :edit] - when :show, :read then [:read, :edit] - when :update, :edit, :create, :new, :destroy then [:edit] + when :index then %i[discover read edit] + when :show, :read then %i[read edit] + when :update, :edit, :create, :new, :destroy then [:edit] end - filters = gated_discovery_filters(permission_types, ability).join(" OR ") + filters = gated_discovery_filters(permission_types, ability).join(' OR ') spawn.where!(filters) end end ActiveFedora::Querying.module_eval do - delegate :accessible_by, :to=>:all + delegate :accessible_by, to: :all end diff --git a/hydra-access-controls/lib/hydra-access-controls.rb b/hydra-access-controls/lib/hydra-access-controls.rb index 897c167a5..53b0e1a36 100644 --- a/hydra-access-controls/lib/hydra-access-controls.rb +++ b/hydra-access-controls/lib/hydra-access-controls.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + require 'rails' require 'active-fedora' require 'blacklight' require 'cancan' -require "deprecation" +require 'deprecation' require 'blacklight-access_controls' module Hydra @@ -26,7 +28,7 @@ def configure(_ = nil) yield @config if block_given? @config end - alias :config :configure + alias config configure end class Engine < Rails::Engine; end diff --git a/hydra-access-controls/lib/hydra/ability.rb b/hydra-access-controls/lib/hydra/ability.rb index 7875a9dd3..08a4de1fc 100644 --- a/hydra-access-controls/lib/hydra/ability.rb +++ b/hydra-access-controls/lib/hydra/ability.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Code for [CANCAN] access to Hydra models module Hydra @@ -14,11 +16,11 @@ module Ability include Hydra::PermissionsQuery include Blacklight::SearchHelper - self.ability_logic = [:create_permissions, :edit_permissions, :read_permissions, :discover_permissions, :download_permissions, :custom_permissions] + self.ability_logic = %i[create_permissions edit_permissions read_permissions discover_permissions download_permissions custom_permissions] end def self.user_class - Hydra.config[:user_model] ? Hydra.config[:user_model].constantize : ::User + Hydra.config[:user_model] ? Hydra.config[:user_model].constantize : ::User end def initialize(user, options = {}) @@ -26,7 +28,7 @@ def initialize(user, options = {}) @user = @current_user # just in case someone was using this in an override. Just don't. @options = options @cache = Blacklight::AccessControls::PermissionsCache.new - hydra_default_permissions() + hydra_default_permissions end def hydra_default_permissions @@ -72,15 +74,14 @@ def discover_permissions # Download permissions are exercised in Hydra::Controller::DownloadBehavior def download_permissions can :download, ActiveFedora::File do |file| - parent_uri = file.uri.to_s.sub(/\/[^\/]*$/, '') + parent_uri = file.uri.to_s.sub(%r{/[^/]*$}, '') parent_id = ActiveFedora::Base.uri_to_id(parent_uri) can? :read, parent_id # i.e, can download if can read parent resource end end ## Override custom permissions in your own app to add more permissions beyond what is defined by default. - def custom_permissions - end + def custom_permissions; end protected @@ -95,9 +96,10 @@ def test_edit(id) def edit_groups(id) doc = permissions_doc(id) return [] if doc.nil? + eg = doc[self.class.edit_group_field] || [] Rails.logger.debug("[CANCAN] edit_groups: #{eg.inspect}") - return eg + eg end # edit implies read, so read_groups is the union of edit and read groups @@ -111,9 +113,10 @@ def read_groups(id) def edit_users(id) doc = permissions_doc(id) return [] if doc.nil? + ep = doc[self.class.edit_user_field] || [] Rails.logger.debug("[CANCAN] edit_users: #{ep.inspect}") - return ep + ep end # edit implies read, so read_users is the union of edit and read users @@ -124,7 +127,6 @@ def read_users(id) rp end - module ClassMethods def read_group_field Hydra.config.permissions.read.group diff --git a/hydra-access-controls/lib/hydra/access_controls_enforcement.rb b/hydra-access-controls/lib/hydra/access_controls_enforcement.rb index 025d29d87..46f3ab685 100644 --- a/hydra-access-controls/lib/hydra/access_controls_enforcement.rb +++ b/hydra-access-controls/lib/hydra/access_controls_enforcement.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::AccessControlsEnforcement extend ActiveSupport::Concern include Blacklight::AccessControls::Enforcement @@ -17,7 +19,7 @@ def under_embargo? # Which permission levels (logical OR) will grant you the ability to discover documents in a search. # Overrides blacklight-access_controls method. def discovery_permissions - @discovery_permissions ||= ["edit","discover","read"] + @discovery_permissions ||= %w[edit discover read] end # Find the name of the solr field for this type of permission. @@ -27,5 +29,4 @@ def solr_field_for(permission_type, permission_category) permissions = Hydra.config.permissions[permission_type.to_sym] permission_category == 'group' ? permissions.group : permissions.individual end - end diff --git a/hydra-access-controls/lib/hydra/admin_policy.rb b/hydra-access-controls/lib/hydra/admin_policy.rb index dad876750..f42f279ea 100644 --- a/hydra-access-controls/lib/hydra/admin_policy.rb +++ b/hydra-access-controls/lib/hydra/admin_policy.rb @@ -1,6 +1,7 @@ +# frozen_string_literal: true + module Hydra class AdminPolicy < ActiveFedora::Base - include Hydra::AdminPolicyBehavior include Hydra::AccessControls::Permissions diff --git a/hydra-access-controls/lib/hydra/config.rb b/hydra-access-controls/lib/hydra/config.rb index a66bf8642..4c023d78b 100644 --- a/hydra-access-controls/lib/hydra/config.rb +++ b/hydra-access-controls/lib/hydra/config.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra class Config def initialize @@ -5,29 +7,29 @@ def initialize @user_model = 'User' end - def []= key, value + def []=(key, value) case key - when :permissions - self.permissions = value - when :user_model - self.user_model = value - when :id_to_resource_uri - self.id_to_resource_uri = value - else - raise "Unknown key" + when :permissions + self.permissions = value + when :user_model + self.user_model = value + when :id_to_resource_uri + self.id_to_resource_uri = value + else + raise 'Unknown key' end end - def [] key + def [](key) case key - when :permissions - permissions - when :user_model - user_model - when :id_to_resource_uri - id_to_resource_uri - else - raise "Unknown key #{key}" + when :permissions + permissions + when :user_model + user_model + when :id_to_resource_uri + id_to_resource_uri + else + raise "Unknown key #{key}" end end @@ -50,10 +52,10 @@ def default_user_key_field # # @return [Lambda] a method to convert ID to a URI def id_to_resource_uri - @id_to_resource_uri ||= lambda { |id, _graph| ActiveFedora::Base.translate_id_to_uri.call(id) } + @id_to_resource_uri ||= ->(id, _graph) { ActiveFedora::Base.translate_id_to_uri.call(id) } end - def permissions= values + def permissions=(values) @permissions.merge! values end @@ -61,44 +63,45 @@ class PermissionsConfig attr_accessor :policy_class, :embargo, :lease def initialize @values = {} - [:discover, :read, :edit].each do |key| + %i[discover read edit].each do |key| @values[key] = GroupPermission.new( - group: solr_name("#{prefix}#{key}_access_group", :symbol), - individual: solr_name("#{prefix}#{key}_access_person", :symbol)) + group: solr_name("#{prefix}#{key}_access_group", :symbol), + individual: solr_name("#{prefix}#{key}_access_person", :symbol) + ) end @embargo = EmbargoConfig.new({}, prefix: prefix) @lease = LeaseConfig.new({}, prefix: prefix) end - def merge! values - values.each {|k, v| self[k] = v } + def merge!(values) + values.each { |k, v| self[k] = v } end - def []= key, value + def []=(key, value) case key - when :discover, :read, :edit - self.assign_value key, value - when :inheritable - inheritable.merge! value - when :policy_class - self.policy_class = value - when :owner - Rails.logger.warn "':owner' is no longer a valid configuration for Hydra. Please remove it from your configuration." - else - raise "Unknown key `#{key.inspect}`" + when :discover, :read, :edit + assign_value key, value + when :inheritable + inheritable.merge! value + when :policy_class + self.policy_class = value + when :owner + Rails.logger.warn "':owner' is no longer a valid configuration for Hydra. Please remove it from your configuration." + else + raise "Unknown key `#{key.inspect}`" end end - def [] key + def [](key) case key - when :discover, :read, :edit - @values[key] - when :inheritable - inheritable - when :policy_class - @policy_class - else - raise "Unknown key #{key}" + when :discover, :read, :edit + @values[key] + when :inheritable + inheritable + when :policy_class + @policy_class + else + raise "Unknown key #{key}" end end @@ -118,24 +121,23 @@ def edit @values[:edit] end - def discover= val + def discover=(val) assign_value :discover, val end - def read= val + def read=(val) assign_value :read, val end - def edit= val + def edit=(val) assign_value :edit, val end protected - def prefix - end + def prefix; end - def assign_value key, val + def assign_value(key, val) @values[key].merge!(val) end @@ -145,11 +147,11 @@ def solr_name(*args) class EmbargoConfig attr_accessor :release_date, :visibility_during, :visibility_after, :history - def initialize(values = {}, attributes={prefix:''}) + def initialize(_values = {}, attributes = { prefix: '' }) @release_date = solr_name("#{attributes[:prefix]}embargo_release_date", :stored_sortable, type: :date) - @visibility_during = solr_name("visibility_during_embargo", :symbol) - @visibility_after = solr_name("visibility_after_embargo", :symbol) - @history = solr_name("embargo_history", :symbol) + @visibility_during = solr_name('visibility_during_embargo', :symbol) + @visibility_after = solr_name('visibility_after_embargo', :symbol) + @history = solr_name('embargo_history', :symbol) end def solr_name(*args) @@ -159,11 +161,11 @@ def solr_name(*args) class LeaseConfig attr_accessor :expiration_date, :visibility_during, :visibility_after, :history - def initialize(values = {}, attributes={prefix:''}) + def initialize(_values = {}, attributes = { prefix: '' }) @expiration_date = solr_name("#{attributes[:prefix]}lease_expiration_date", :stored_sortable, type: :date) - @visibility_during = solr_name("visibility_during_lease", :symbol) - @visibility_after = solr_name("visibility_after_lease", :symbol) - @history = solr_name("lease_history", :symbol) + @visibility_during = solr_name('visibility_during_lease', :symbol) + @visibility_after = solr_name('visibility_after_lease', :symbol) + @history = solr_name('lease_history', :symbol) end def solr_name(*args) @@ -176,16 +178,18 @@ class GroupPermission def initialize(values = {}) merge! values end - def merge! values + + def merge!(values) @group = values[:group] @individual = values[:individual] end - def [] key + + def [](key) case key - when :group, :individual - send key - else - raise "Unknown key" + when :group, :individual + send key + else + raise 'Unknown key' end end end @@ -193,9 +197,10 @@ def [] key class InheritablePermissionsConfig < PermissionsConfig protected - def prefix - 'inheritable_' - end + + def prefix + 'inheritable_' + end end end end diff --git a/hydra-access-controls/lib/hydra/ip_based_groups.rb b/hydra-access-controls/lib/hydra/ip_based_groups.rb index cf0615b38..ffedf51d0 100644 --- a/hydra-access-controls/lib/hydra/ip_based_groups.rb +++ b/hydra-access-controls/lib/hydra/ip_based_groups.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'ipaddr' module Hydra class IpBasedGroups @@ -20,39 +22,38 @@ def include_ip?(ip_string) private - def subnets - @subnets ||= @subnet_strings.map { |s| IPAddr.new(s) } - end - end - - def self.groups - load_groups.fetch('groups').map { |h| Group.new(h) } + def subnets + @subnets ||= @subnet_strings.map { |s| IPAddr.new(s) } end + end - def self.filename - 'config/hydra_ip_range.yml' - end + def self.groups + load_groups.fetch('groups').map { |h| Group.new(h) } + end - def self.load_groups - require 'yaml' + def self.filename + 'config/hydra_ip_range.yml' + end - file = File.join(Rails.root, filename) + def self.load_groups + require 'yaml' - unless File.exists?(file) - raise "ip-range configuration file not found. Expected: #{file}." - end + file = File.join(Rails.root, filename) - begin - yml = YAML::load_file(file) - rescue - raise("#{filename} was found, but could not be parsed.\n") - end - unless yml.is_a? Hash - raise("#{filename} was found, but was blank or malformed.\n") - end + unless File.exist?(file) + raise "ip-range configuration file not found. Expected: #{file}." + end - yml.fetch(Rails.env) + begin + yml = YAML.load_file(file) + rescue StandardError + raise("#{filename} was found, but could not be parsed.\n") + end + unless yml.is_a? Hash + raise("#{filename} was found, but was blank or malformed.\n") end + yml.fetch(Rails.env) + end end end diff --git a/hydra-access-controls/lib/hydra/permissions_query.rb b/hydra-access-controls/lib/hydra/permissions_query.rb index 929d8bb0c..d107327fd 100644 --- a/hydra-access-controls/lib/hydra/permissions_query.rb +++ b/hydra-access-controls/lib/hydra/permissions_query.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module PermissionsQuery extend ActiveSupport::Concern @@ -9,6 +11,5 @@ module PermissionsQuery def permissions_document_class Hydra::PermissionsSolrDocument end - end end diff --git a/hydra-access-controls/lib/hydra/policy_aware_ability.rb b/hydra-access-controls/lib/hydra/policy_aware_ability.rb index fda105ed9..f829c0ab3 100644 --- a/hydra-access-controls/lib/hydra/policy_aware_ability.rb +++ b/hydra-access-controls/lib/hydra/policy_aware_ability.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + # Repeats access controls evaluation methods, but checks against a governing "Policy" object (or "Collection" object) that provides inherited access controls. module Hydra::PolicyAwareAbility extend ActiveSupport::Concern include Blacklight::AccessControls::Ability include Hydra::Ability - IS_GOVERNED_BY_SOLR_FIELD = "isGovernedBy_ssim".freeze + IS_GOVERNED_BY_SOLR_FIELD = 'isGovernedBy_ssim' # Extends Hydra::Ability.test_edit to try policy controls if object-level controls deny access def test_edit(id) @@ -23,13 +25,15 @@ def test_read(id) def policy_id_for(object_id) policy_id = policy_id_cache[object_id] return policy_id if policy_id + solr_result = ActiveFedora::Base.search_with_conditions({ id: object_id }, fl: governed_by_solr_field).first return unless solr_result + policy_id_cache[object_id] = policy_id = Array(solr_result[governed_by_solr_field]).first end def governed_by_solr_field - # TODO the solr key could be derived if we knew the class of the object: + # TODO: the solr key could be derived if we knew the class of the object: # ModsAsset.reflect_on_association(:admin_policy).solr_key IS_GOVERNED_BY_SOLR_FIELD end @@ -46,9 +50,10 @@ def policy_permissions_doc(policy_id) def test_edit_from_policy(object_id) policy_id = policy_id_for(object_id) return false if policy_id.nil? + Rails.logger.debug("[CANCAN] -policy- Does the POLICY #{policy_id} provide EDIT permissions for #{current_user.user_key}?") - group_intersection = user_groups & edit_groups_from_policy( policy_id ) - result = !group_intersection.empty? || edit_users_from_policy( policy_id ).include?(current_user.user_key) + group_intersection = user_groups & edit_groups_from_policy(policy_id) + result = !group_intersection.empty? || edit_users_from_policy(policy_id).include?(current_user.user_key) Rails.logger.debug("[CANCAN] -policy- decision: #{result}") result end @@ -57,9 +62,10 @@ def test_edit_from_policy(object_id) def test_read_from_policy(object_id) policy_id = policy_id_for(object_id) return false if policy_id.nil? + Rails.logger.debug("[CANCAN] -policy- Does the POLICY #{policy_id} provide READ permissions for #{current_user.user_key}?") - group_intersection = user_groups & read_groups_from_policy( policy_id ) - result = !group_intersection.empty? || read_users_from_policy( policy_id ).include?(current_user.user_key) + group_intersection = user_groups & read_groups_from_policy(policy_id) + result = !group_intersection.empty? || read_users_from_policy(policy_id).include?(current_user.user_key) Rails.logger.debug("[CANCAN] -policy- decision: #{result}") result end @@ -68,9 +74,9 @@ def test_read_from_policy(object_id) def edit_groups_from_policy(policy_id) policy_permissions = policy_permissions_doc(policy_id) edit_group_field = Hydra.config.permissions.inheritable[:edit][:group] - eg = ((policy_permissions == nil || policy_permissions.fetch(edit_group_field,nil) == nil) ? [] : policy_permissions.fetch(edit_group_field,nil)) + eg = (policy_permissions.nil? || policy_permissions.fetch(edit_group_field, nil).nil? ? [] : policy_permissions.fetch(edit_group_field, nil)) Rails.logger.debug("[CANCAN] -policy- edit_groups: #{eg.inspect}") - return eg + eg end # Returns the list of groups granted read access by the policy object identified by policy_id @@ -78,18 +84,18 @@ def edit_groups_from_policy(policy_id) def read_groups_from_policy(policy_id) policy_permissions = policy_permissions_doc(policy_id) read_group_field = Hydra.config.permissions.inheritable[:read][:group] - rg = edit_groups_from_policy(policy_id) | ((policy_permissions == nil || policy_permissions.fetch(read_group_field,nil) == nil) ? [] : policy_permissions.fetch(read_group_field,nil)) + rg = edit_groups_from_policy(policy_id) | (policy_permissions.nil? || policy_permissions.fetch(read_group_field, nil).nil? ? [] : policy_permissions.fetch(read_group_field, nil)) Rails.logger.debug("[CANCAN] -policy- read_groups: #{rg.inspect}") - return rg + rg end # Returns the list of users granted edit access by the policy object identified by policy_id def edit_users_from_policy(policy_id) policy_permissions = policy_permissions_doc(policy_id) edit_user_field = Hydra.config.permissions.inheritable[:edit][:individual] - eu = ((policy_permissions == nil || policy_permissions.fetch(edit_user_field,nil) == nil) ? [] : policy_permissions.fetch(edit_user_field,nil)) + eu = (policy_permissions.nil? || policy_permissions.fetch(edit_user_field, nil).nil? ? [] : policy_permissions.fetch(edit_user_field, nil)) Rails.logger.debug("[CANCAN] -policy- edit_users: #{eu.inspect}") - return eu + eu end # Returns the list of users granted read access by the policy object identified by policy_id @@ -97,9 +103,9 @@ def edit_users_from_policy(policy_id) def read_users_from_policy(policy_id) policy_permissions = policy_permissions_doc(policy_id) read_user_field = Hydra.config.permissions.inheritable[:read][:individual] - ru = edit_users_from_policy(policy_id) | ((policy_permissions == nil || policy_permissions.fetch(read_user_field, nil) == nil) ? [] : policy_permissions.fetch(read_user_field, nil)) + ru = edit_users_from_policy(policy_id) | (policy_permissions.nil? || policy_permissions.fetch(read_user_field, nil).nil? ? [] : policy_permissions.fetch(read_user_field, nil)) Rails.logger.debug("[CANCAN] -policy- read_users: #{ru.inspect}") - return ru + ru end private @@ -107,5 +113,4 @@ def read_users_from_policy(policy_id) def policy_id_cache @policy_id_cache ||= {} end - end diff --git a/hydra-access-controls/lib/hydra/policy_aware_access_controls_enforcement.rb b/hydra-access-controls/lib/hydra/policy_aware_access_controls_enforcement.rb index 7e17ab84e..d7f82d815 100644 --- a/hydra-access-controls/lib/hydra/policy_aware_access_controls_enforcement.rb +++ b/hydra-access-controls/lib/hydra/policy_aware_access_controls_enforcement.rb @@ -1,19 +1,21 @@ +# frozen_string_literal: true + # Repeats access controls evaluation methods, but checks against a governing "Policy" object (or "Collection" object) that provides inherited access controls. module Hydra::PolicyAwareAccessControlsEnforcement - # Extends Hydra::AccessControlsEnforcement.apply_gated_discovery to reflect policy-provided access. # Appends the result of policy_clauses into the :fq # @param [Hash] solr_parameters the current solr parameters, to be modified herein! def apply_gated_discovery(solr_parameters) super - logger.debug("POLICY-aware Solr parameters: #{ solr_parameters.inspect }") + logger.debug("POLICY-aware Solr parameters: #{solr_parameters.inspect}") end # @return [String,nil] solr query for finding all objects whose policies grant discover access to current_user def policy_clauses policy_ids = policies_with_access return nil if policy_ids.empty? - '(' + policy_ids.map {|id| ActiveFedora::SolrQueryBuilder.construct_query_for_rel(isGovernedBy: id)}.join(' OR '.freeze) + ')' + + '(' + policy_ids.map { |id| ActiveFedora::SolrQueryBuilder.construct_query_for_rel(isGovernedBy: id) }.join(' OR ') + ')' end # Find all the policies that grant discover/read/edit permissions to this user or any of its groups. @@ -23,21 +25,21 @@ def policies_with_access user_access_filters = [] user_access_filters += apply_policy_group_permissions(discovery_permissions) user_access_filters += apply_policy_user_permissions(discovery_permissions) - result = policy_class.search_with_conditions( user_access_filters.join(" OR "), fl: "id", rows: policy_class.count ) + result = policy_class.search_with_conditions(user_access_filters.join(' OR '), fl: 'id', rows: policy_class.count) logger.debug "get policies: #{result}\n\n" - result.map {|h| h['id']} + result.map { |h| h['id'] } end # for groups # @param [Array{String,#to_sym}] permission_types symbols (or equivalent) from Hydra.config.permissions.inheritable def apply_policy_group_permissions(permission_types = discovery_permissions) - user_access_filters = [] - current_ability.user_groups.each_with_index do |group, i| - permission_types.each do |type| - user_access_filters << escape_filter(Hydra.config.permissions.inheritable[type.to_sym].group, group) - end + user_access_filters = [] + current_ability.user_groups.each_with_index do |group, _i| + permission_types.each do |type| + user_access_filters << escape_filter(Hydra.config.permissions.inheritable[type.to_sym].group, group) end - user_access_filters + end + user_access_filters end # for individual user access @@ -45,6 +47,7 @@ def apply_policy_group_permissions(permission_types = discovery_permissions) def apply_policy_user_permissions(permission_types = discovery_permissions) user = current_ability.current_user return [] unless user && user.user_key.present? + permission_types.map do |type| escape_filter(Hydra.config.permissions.inheritable[type.to_sym].individual, user.user_key) end @@ -52,7 +55,7 @@ def apply_policy_user_permissions(permission_types = discovery_permissions) # Override method from blacklight-access_controls def discovery_permissions - @discovery_permissions ||= ["edit", "discover", "read"] + @discovery_permissions ||= %w[edit discover read] end # Returns the Model used for AdminPolicy objects. @@ -67,9 +70,7 @@ def policy_class def gated_discovery_filters filters = super additional_clauses = policy_clauses - unless additional_clauses.blank? - filters << additional_clauses - end + filters << additional_clauses unless additional_clauses.blank? filters end @@ -80,5 +81,4 @@ def solr_field_for(permission_type, permission_category) permissions = Hydra.config.permissions[permission_type.to_sym] permission_category == 'group' ? permissions.group : permissions.individual end - end diff --git a/hydra-access-controls/lib/hydra/role_mapper_behavior.rb b/hydra-access-controls/lib/hydra/role_mapper_behavior.rb index 795e062db..afee63dd2 100644 --- a/hydra-access-controls/lib/hydra/role_mapper_behavior.rb +++ b/hydra-access-controls/lib/hydra/role_mapper_behavior.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::RoleMapperBehavior extend ActiveSupport::Concern extend Deprecation @@ -15,12 +17,12 @@ def fetch_groups(user:) # @param user_or_uid either the User object or user id # If you pass in a nil User object (ie. user isn't logged in), or a uid that doesn't exist, it will return an empty array def roles(user_or_uid) - Deprecation.warn(self, "roles is deprecated and will be removed in Hydra-Head 11. Use fetch_groups instead") + Deprecation.warn(self, 'roles is deprecated and will be removed in Hydra-Head 11. Use fetch_groups instead') user_id = case user_or_uid - when String - user_or_uid - else - user_or_uid.user_key + when String + user_or_uid + else + user_or_uid.user_key end _groups(user_id) end @@ -33,52 +35,51 @@ def map @map ||= load_role_map end - def byname - @byname ||= map.each_with_object(Hash.new{ |h,k| h[k] = [] }) do |(role, usernames), memo| - Array(usernames).each { |x| memo[x] << role} + @byname ||= map.each_with_object(Hash.new { |h, k| h[k] = [] }) do |(role, usernames), memo| + Array(usernames).each { |x| memo[x] << role } end end private - ## - # @param user_id [String] the identfying user key - # @return [Array] a list of group names. If a nil user id, or a user id that doesn't exist is passed in, it will return an empty array - def _groups(user_id) - byname[user_id].dup || [] + ## + # @param user_id [String] the identfying user key + # @return [Array] a list of group names. If a nil user id, or a user id that doesn't exist is passed in, it will return an empty array + def _groups(user_id) + byname[user_id].dup || [] + end + + def load_role_map + require 'erb' + require 'yaml' + + filename = 'config/role_map.yml' + file = File.join(Rails.root, filename) + + unless File.exist?(file) + raise "You are missing a role map configuration file: #{filename}. Have you run \"rails generate hydra:head\"?" end - def load_role_map - require 'erb' - require 'yaml' - - filename = 'config/role_map.yml' - file = File.join(Rails.root, filename) - - unless File.exists?(file) - raise "You are missing a role map configuration file: #{filename}. Have you run \"rails generate hydra:head\"?" - end - - begin - erb = ERB.new(IO.read(file)).result(binding) - rescue - raise("#{file} was found, but could not be parsed with ERB. \n#{$!.inspect}") - end - - begin - yml = YAML::load(erb) - rescue - raise("#{filename} was found, but could not be parsed.\n") - end - unless yml.is_a? Hash - raise("#{filename} was found, but was blank or malformed.\n") - end - - roles = yml.fetch(Rails.env) - raise "No roles were found for the #{Rails.env} environment in #{file}" unless roles - roles + begin + erb = ERB.new(IO.read(file)).result(binding) + rescue StandardError + raise("#{file} was found, but could not be parsed with ERB. \n#{$ERROR_INFO.inspect}") end + + begin + yml = YAML.safe_load(erb) + rescue StandardError + raise("#{filename} was found, but could not be parsed.\n") + end + unless yml.is_a? Hash + raise("#{filename} was found, but was blank or malformed.\n") + end + + roles = yml.fetch(Rails.env) + raise "No roles were found for the #{Rails.env} environment in #{file}" unless roles + + roles + end end end - diff --git a/hydra-access-controls/lib/hydra/shared_spec/group_service_interface.rb b/hydra-access-controls/lib/hydra/shared_spec/group_service_interface.rb index 5906e64b9..fb88f795e 100644 --- a/hydra-access-controls/lib/hydra/shared_spec/group_service_interface.rb +++ b/hydra-access-controls/lib/hydra/shared_spec/group_service_interface.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + RSpec.shared_examples 'a Hydra group_service interface' do before do raise 'adapter must be set with `let(:group_service)`' unless @@ -10,7 +12,7 @@ describe '#fetch_groups' do it 'requires a user: keyword arg' do - expect(group_service.method(:fetch_groups).parameters).to eq([[:keyreq, :user]]) + expect(group_service.method(:fetch_groups).parameters).to eq([%i[keyreq user]]) end end end diff --git a/hydra-access-controls/lib/hydra/user.rb b/hydra-access-controls/lib/hydra/user.rb index 38a654430..ff0a0c9f7 100644 --- a/hydra-access-controls/lib/hydra/user.rb +++ b/hydra-access-controls/lib/hydra/user.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + # Injects behaviors into User model so that it will work with Hydra Access Controls # By default, this module assumes you are using the User model created by Blacklight, which uses Devise. # To integrate your own User implementation into Hydra, override this Module or define your own User model in app/models/user.rb within your Hydra head. module Hydra::User extend ActiveSupport::Concern include Blacklight::AccessControls::User - + included do class_attribute :group_service self.group_service = RoleMapper @@ -13,7 +15,7 @@ module Hydra::User def groups group_service.fetch_groups(user: self) end - + module ClassMethods # This method finds User objects using the user_key as specified by the # Devise authentication_keys configuration variable. This method encapsulates diff --git a/hydra-access-controls/spec/factories.rb b/hydra-access-controls/spec/factories.rb index 51e891865..a6b9788f6 100644 --- a/hydra-access-controls/spec/factories.rb +++ b/hydra-access-controls/spec/factories.rb @@ -1,60 +1,61 @@ -FactoryBot.define do +# frozen_string_literal: true +FactoryBot.define do # Users # Prototype user factory - factory :user, :aliases => [:owner] do |u| + factory :user, aliases: [:owner] do |_u| sequence :uid do |n| "person#{n}" end password { uid } end - factory :archivist, :parent=>:user do |u| + factory :archivist, parent: :user do |_u| uid { 'archivist1' } password { 'archivist1' } end - factory :registered_user, :parent=>:user do |u| + factory :registered_user, parent: :user do |_u| uid { 'registered_user' } password { 'registered_user' } end - factory :staff, :parent=>:user do |u| + factory :staff, parent: :user do |_u| uid { 'staff1' } password { 'staff1' } end - factory :student, :parent=>:user do |u| + factory :student, parent: :user do |_u| uid { 'student1' } password { 'student1' } end - factory :joe_creator, :parent=>:user do |u| + factory :joe_creator, parent: :user do |_u| uid { 'joe_creator' } password { 'joe_creator' } end - factory :martia_morocco, :parent=>:user do |u| + factory :martia_morocco, parent: :user do |_u| uid { 'martia_morocco' } password { 'martia_morocco' } end - factory :ira_instructor, :parent=>:user do |u| + factory :ira_instructor, parent: :user do |_u| uid { 'ira_instructor' } password { 'ira_instructor' } end - factory :calvin_collaborator, :parent=>:user do |u| + factory :calvin_collaborator, parent: :user do |_u| uid { 'calvin_collaborator' } password { 'calvin_collaborator' } end - factory :sara_student, :parent=>:user do |u| + factory :sara_student, parent: :user do |_u| uid { 'sara_student' } password { 'sara_student' } end - factory :louis_librarian, :parent=>:user do |u| + factory :louis_librarian, parent: :user do |_u| uid { 'louis_librarian' } password { 'louis_librarian' } end - factory :carol_curator, :parent=>:user do |u| + factory :carol_curator, parent: :user do |_u| uid { 'carol_curator' } password { 'carol_curator' } end - factory :alice_admin, :parent=>:user do |u| + factory :alice_admin, parent: :user do |_u| uid { 'alice_admin' } password { 'alice_admin' } end @@ -63,31 +64,29 @@ # Repository Objects # - factory :asset, :class => ModsAsset do |o| + factory :asset, class: ModsAsset do |o| end - factory :admin_policy, :class => Hydra::AdminPolicy do |o| + factory :admin_policy, class: Hydra::AdminPolicy do |o| end - factory :default_access_asset, :parent=>:asset do |a| - permissions_attributes { [{ name: "joe_creator", access: "edit", type: "person" }] } + factory :default_access_asset, parent: :asset do |_a| + permissions_attributes { [{ name: 'joe_creator', access: 'edit', type: 'person' }] } end - factory :dept_access_asset, :parent=>:asset do |a| - permissions_attributes { [{ name: "africana-faculty", access: "read", type: "group" }, { name: "joe_creator", access: "edit", type: "person" }] } + factory :dept_access_asset, parent: :asset do |_a| + permissions_attributes { [{ name: 'africana-faculty', access: 'read', type: 'group' }, { name: 'joe_creator', access: 'edit', type: 'person' }] } end - factory :group_edit_asset, :parent=>:asset do |a| - permissions_attributes { [{ name:"africana-faculty", access: "edit", type: "group" }, {name: "calvin_collaborator", access: "edit", type: "person"}] } + factory :group_edit_asset, parent: :asset do |_a| + permissions_attributes { [{ name: 'africana-faculty', access: 'edit', type: 'group' }, { name: 'calvin_collaborator', access: 'edit', type: 'person' }] } end - factory :org_read_access_asset, :parent=>:asset do |a| - permissions_attributes { [{ name: "registered", access: "read", type: "group" }, { name: "joe_creator", access: "edit", type: "person" }, { name: "calvin_collaborator", access: "edit", type: "person" }] } + factory :org_read_access_asset, parent: :asset do |_a| + permissions_attributes { [{ name: 'registered', access: 'read', type: 'group' }, { name: 'joe_creator', access: 'edit', type: 'person' }, { name: 'calvin_collaborator', access: 'edit', type: 'person' }] } end - factory :open_access_asset, :parent=>:asset do |a| - permissions_attributes { [{ name: "public", access: "read", type: "group" }, { name: "joe_creator", access: "edit", type: "person" }, { name: "calvin_collaborator", access: "edit", type: "person" }] } + factory :open_access_asset, parent: :asset do |_a| + permissions_attributes { [{ name: 'public', access: 'read', type: 'group' }, { name: 'joe_creator', access: 'edit', type: 'person' }, { name: 'calvin_collaborator', access: 'edit', type: 'person' }] } end - end - diff --git a/hydra-access-controls/spec/indexers/embargo_indexer_spec.rb b/hydra-access-controls/spec/indexers/embargo_indexer_spec.rb index 8518ce340..ef8879668 100644 --- a/hydra-access-controls/spec/indexers/embargo_indexer_spec.rb +++ b/hydra-access-controls/spec/indexers/embargo_indexer_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::AccessControls::EmbargoIndexer do @@ -12,7 +14,7 @@ let(:indexer) { described_class.new(embargo) } subject { indexer.generate_solr_document } - it "has the fields" do + it 'has the fields' do expect(subject['visibility_during_embargo_ssim']).to eq 'authenticated' expect(subject['visibility_after_embargo_ssim']).to eq 'open' expect(subject['embargo_release_date_dtsi']).to eq '2010-10-10T00:00:00Z' diff --git a/hydra-access-controls/spec/indexers/lease_indexer_spec.rb b/hydra-access-controls/spec/indexers/lease_indexer_spec.rb index e6b1e185f..7913f8b06 100644 --- a/hydra-access-controls/spec/indexers/lease_indexer_spec.rb +++ b/hydra-access-controls/spec/indexers/lease_indexer_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::AccessControls::LeaseIndexer do @@ -12,7 +14,7 @@ let(:indexer) { described_class.new(lease) } subject { indexer.generate_solr_document } - it "has the fields" do + it 'has the fields' do expect(subject['visibility_during_lease_ssim']).to eq 'open' expect(subject['visibility_after_lease_ssim']).to eq 'authenticated' expect(subject['lease_expiration_date_dtsi']).to eq '2010-10-10T00:00:00Z' diff --git a/hydra-access-controls/spec/services/embargo_service_spec.rb b/hydra-access-controls/spec/services/embargo_service_spec.rb index 2a40521e7..8d8c3d836 100644 --- a/hydra-access-controls/spec/services/embargo_service_spec.rb +++ b/hydra-access-controls/spec/services/embargo_service_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::EmbargoService do @@ -6,31 +8,31 @@ let!(:work_with_expired_embargo1) do FactoryBot.build(:asset, embargo_release_date: past_date.to_s).tap do |work| - work.save(validate:false) + work.save(validate: false) end end let!(:work_with_expired_embargo2) do FactoryBot.build(:asset, embargo_release_date: past_date.to_s).tap do |work| - work.save(validate:false) + work.save(validate: false) end end - let!(:work_with_embargo_in_effect) { FactoryBot.create(:asset, embargo_release_date: future_date.to_s)} - let!(:work_without_embargo) { FactoryBot.create(:asset)} + let!(:work_with_embargo_in_effect) { FactoryBot.create(:asset, embargo_release_date: future_date.to_s) } + let!(:work_without_embargo) { FactoryBot.create(:asset) } - describe "#assets_with_expired_embargoes" do - it "returns an array of assets with expired embargoes" do - returned_ids = subject.assets_with_expired_embargoes.map {|a| a.id} + describe '#assets_with_expired_embargoes' do + it 'returns an array of assets with expired embargoes' do + returned_ids = subject.assets_with_expired_embargoes.map(&:id) expect(returned_ids).to include work_with_expired_embargo1.id, work_with_expired_embargo2.id expect(returned_ids).to_not include work_with_embargo_in_effect.id, work_without_embargo.id end end - describe "#assets_under_embargo" do - it "returns all assets with embargo release date set" do + describe '#assets_under_embargo' do + it 'returns all assets with embargo release date set' do result = subject.assets_under_embargo - returned_ids = subject.assets_under_embargo.map {|a| a.id} + returned_ids = subject.assets_under_embargo.map(&:id) expect(returned_ids).to include work_with_expired_embargo1.id, work_with_expired_embargo2.id, work_with_embargo_in_effect.id expect(returned_ids).to_not include work_without_embargo.id end diff --git a/hydra-access-controls/spec/services/lease_service_spec.rb b/hydra-access-controls/spec/services/lease_service_spec.rb index c085c3479..e73678e26 100644 --- a/hydra-access-controls/spec/services/lease_service_spec.rb +++ b/hydra-access-controls/spec/services/lease_service_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::LeaseService do @@ -16,20 +18,20 @@ end end - let!(:work_with_lease_in_effect) { FactoryBot.create(:asset, lease_expiration_date: future_date.to_s)} - let!(:work_without_lease) { FactoryBot.create(:asset)} + let!(:work_with_lease_in_effect) { FactoryBot.create(:asset, lease_expiration_date: future_date.to_s) } + let!(:work_without_lease) { FactoryBot.create(:asset) } - describe "#assets_with_expired_leases" do - it "returns an array of assets with expired embargoes" do - returned_ids = subject.assets_with_expired_leases.map {|a| a.id} + describe '#assets_with_expired_leases' do + it 'returns an array of assets with expired embargoes' do + returned_ids = subject.assets_with_expired_leases.map(&:id) expect(returned_ids).to include work_with_expired_lease1.id, work_with_expired_lease2.id expect(returned_ids).to_not include work_with_lease_in_effect.id, work_without_lease.id end end - describe "#assets_under_lease" do - it "returns an array of assets with expired embargoes" do - returned_ids = subject.assets_under_lease.map {|a| a.id} + describe '#assets_under_lease' do + it 'returns an array of assets with expired embargoes' do + returned_ids = subject.assets_under_lease.map(&:id) expect(returned_ids).to include work_with_expired_lease1.id, work_with_expired_lease2.id, work_with_lease_in_effect.id expect(returned_ids).to_not include work_without_lease.id end diff --git a/hydra-access-controls/spec/spec_helper.rb b/hydra-access-controls/spec/spec_helper.rb index 4ab0a8ea0..01ff89acd 100644 --- a/hydra-access-controls/spec/spec_helper.rb +++ b/hydra-access-controls/spec/spec_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + ENV['RAILS_ENV'] ||= 'test' require 'engine_cart' path = File.expand_path(File.join('..', '..', '..', '.internal_test_app'), __FILE__) @@ -19,7 +21,7 @@ def coverage_needed? require 'simplecov' require 'coveralls' - SimpleCov.root(File.expand_path('../../../', __FILE__)) + SimpleCov.root(File.expand_path('../..', __dir__)) SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new( [ SimpleCov::Formatter::HTMLFormatter, @@ -34,21 +36,21 @@ def coverage_needed? require 'active_support/dependencies' relative_load_paths = ["#{Blacklight.root}/app/controllers/concerns", "#{Blacklight.root}/app/models", - "app/models", - "app/models/concerns", - "app/indexers", - "app/services", - "app/validators", - "app/vocabularies"] + 'app/models', + 'app/models/concerns', + 'app/indexers', + 'app/services', + 'app/validators', + 'app/vocabularies'] ActiveSupport::Dependencies.autoload_paths += relative_load_paths require 'support/mods_asset' require 'support/solr_document' -require "support/user" -require "factory_bot" +require 'support/user' +require 'factory_bot' require 'rspec/mocks' require 'rspec/its' -require "factories" +require 'factories' # HttpLogger.logger = Logger.new(STDOUT) # HttpLogger.ignore = [/localhost:8983\/solr/] diff --git a/hydra-access-controls/spec/support/mods_asset.rb b/hydra-access-controls/spec/support/mods_asset.rb index 283a755f3..bc6ebde91 100644 --- a/hydra-access-controls/spec/support/mods_asset.rb +++ b/hydra-access-controls/spec/support/mods_asset.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + class ModsAsset < ActiveFedora::Base include Hydra::AccessControls::Embargoable # This is how we're associating admin policies with assets. # You can associate them however you want, just use the :is_governed_by relationship - belongs_to :admin_policy, class_name: "Hydra::AdminPolicy", predicate: ActiveFedora::RDF::ProjectHydra.isGovernedBy + belongs_to :admin_policy, class_name: 'Hydra::AdminPolicy', predicate: ActiveFedora::RDF::ProjectHydra.isGovernedBy end diff --git a/hydra-access-controls/spec/support/solr_document.rb b/hydra-access-controls/spec/support/solr_document.rb index 110642690..68b5f7348 100644 --- a/hydra-access-controls/spec/support/solr_document.rb +++ b/hydra-access-controls/spec/support/solr_document.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + class SolrDocument - def initialize(source_doc={}, solr_response=nil) + def initialize(source_doc = {}, _solr_response = nil) @source_doc = source_doc end @@ -7,7 +9,7 @@ def id fetch(:id) end - def fetch(field, default = nil) + def fetch(field, _default = nil) @source_doc[field] end @@ -15,4 +17,3 @@ def [](field) @source_doc[field] end end - diff --git a/hydra-access-controls/spec/support/user.rb b/hydra-access-controls/spec/support/user.rb index bac87e30b..d25dc80ed 100644 --- a/hydra-access-controls/spec/support/user.rb +++ b/hydra-access-controls/spec/support/user.rb @@ -1,12 +1,12 @@ +# frozen_string_literal: true + class User - include Hydra::User attr_accessor :uid - def initialize(params={}) + def initialize(params = {}) self.uid = params.delete(:uid) if params[:uid] super end - end diff --git a/hydra-access-controls/spec/unit/ability_spec.rb b/hydra-access-controls/spec/unit/ability_spec.rb index a85af72e1..c1a0d3c4e 100644 --- a/hydra-access-controls/spec/unit/ability_spec.rb +++ b/hydra-access-controls/spec/unit/ability_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'cancan/matchers' @@ -5,50 +7,49 @@ before do allow(Devise).to receive(:authentication_keys).and_return(['uid']) end - describe "class methods" do + describe 'class methods' do subject { Ability } - its(:read_group_field) { should == 'read_access_group_ssim'} - its(:read_user_field) { should == 'read_access_person_ssim'} - its(:edit_group_field) { should == 'edit_access_group_ssim'} - its(:edit_user_field) { should == 'edit_access_person_ssim'} - its(:discover_group_field) { should == 'discover_access_group_ssim'} - its(:discover_user_field) { should == 'discover_access_person_ssim'} + its(:read_group_field) { should == 'read_access_group_ssim' } + its(:read_user_field) { should == 'read_access_person_ssim' } + its(:edit_group_field) { should == 'edit_access_group_ssim' } + its(:edit_user_field) { should == 'edit_access_person_ssim' } + its(:discover_group_field) { should == 'discover_access_group_ssim' } + its(:discover_user_field) { should == 'discover_access_person_ssim' } end subject { Ability.new(user) } - context "for a not-signed in user" do + context 'for a not-signed in user' do before do allow_any_instance_of(User).to receive(:email).and_return(nil) allow_any_instance_of(User).to receive(:new_record?).and_return(true) end let(:user) { nil } - it "calls custom_permissions" do + it 'calls custom_permissions' do expect_any_instance_of(Ability).to receive(:custom_permissions) subject.can?(:delete, 7) end it { should_not be_able_to(:create, ActiveFedora::Base) } end - context "for a signed in user" do + context 'for a signed in user' do let(:user) { FactoryBot.build(:registered_user) } it { should_not be_able_to(:create, ActiveFedora::Base) } end + # NOTES: + # See spec/requests/... for test coverage describing WHAT should appear on a page based on access permissions + # Test coverage for discover permission is in spec/requests/gated_discovery_spec.rb -# NOTES: -# See spec/requests/... for test coverage describing WHAT should appear on a page based on access permissions -# Test coverage for discover permission is in spec/requests/gated_discovery_spec.rb - - describe "Given an asset that has been made publicly discoverable" do + describe 'Given an asset that has been made publicly discoverable' do let(:asset) { FactoryBot.create(:asset) } before do - asset.permissions_attributes = [{ name: "public", access: "discover", type: "group" }, { name: "joe_creator", access: "edit", type: "person" }, { name: "calvin_collaborator", access: "edit", type: "person" }] + asset.permissions_attributes = [{ name: 'public', access: 'discover', type: 'group' }, { name: 'joe_creator', access: 'edit', type: 'person' }, { name: 'calvin_collaborator', access: 'edit', type: 'person' }] asset.save end - context "Then a not-signed-in user" do + context 'Then a not-signed-in user' do let(:user) { nil } it { should be_able_to(:discover, asset) } it { should_not be_able_to(:read, asset) } @@ -57,7 +58,7 @@ it { should_not be_able_to(:destroy, asset) } end - context "Then a registered user" do + context 'Then a registered user' do let(:user) { FactoryBot.build(:registered_user) } it { should be_able_to(:discover, asset) } it { should_not be_able_to(:read, asset) } @@ -67,15 +68,15 @@ end end - describe "Given an asset that has been made publicly available (ie. open access)" do - #let(:asset) { FactoryBot.create(:open_access_asset) } + describe 'Given an asset that has been made publicly available (ie. open access)' do + # let(:asset) { FactoryBot.create(:open_access_asset) } let(:asset) { FactoryBot.create(:asset) } before do - asset.permissions_attributes = [{ name: "public", access: "read", type: "group" }, { name: "joe_creator", access: "edit", type: "person" }, { name: "calvin_collaborator", access: "edit", type: "person" }] + asset.permissions_attributes = [{ name: 'public', access: 'read', type: 'group' }, { name: 'joe_creator', access: 'edit', type: 'person' }, { name: 'calvin_collaborator', access: 'edit', type: 'person' }] asset.save end - context "Then a not-signed-in user" do + context 'Then a not-signed-in user' do let(:user) { nil } it { should be_able_to(:discover, asset) } it { should be_able_to(:read, asset) } @@ -84,7 +85,7 @@ it { should_not be_able_to(:destroy, asset) } end - context "Then a registered user" do + context 'Then a registered user' do let(:user) { FactoryBot.build(:registered_user) } it { should be_able_to(:discover, asset) } it { should be_able_to(:read, asset) } @@ -94,14 +95,14 @@ end end - describe "Given an asset with no custom access set" do + describe 'Given an asset with no custom access set' do let(:asset) { FactoryBot.create(:asset) } before do - asset.permissions_attributes = [{ name: "joe_creator", access: "edit", type: "person" }] + asset.permissions_attributes = [{ name: 'joe_creator', access: 'edit', type: 'person' }] asset.save end let(:solr_doc) { SolrDocument.new(asset.to_solr.merge(id: asset.id)) } - context "Then a not-signed-in user" do + context 'Then a not-signed-in user' do let(:user) { User.new } it { should_not be_able_to(:discover, asset) } it { should_not be_able_to(:read, asset) } @@ -109,7 +110,7 @@ it { should_not be_able_to(:update, asset) } it { should_not be_able_to(:destroy, asset) } end - context "Then a registered user" do + context 'Then a registered user' do let(:user) { FactoryBot.build(:registered_user) } it { should_not be_able_to(:discover, asset) } it { should_not be_able_to(:read, asset) } @@ -117,7 +118,7 @@ it { should_not be_able_to(:update, asset) } it { should_not be_able_to(:destroy, asset) } end - context "Then the Creator" do + context 'Then the Creator' do let(:user) { FactoryBot.build(:joe_creator) } it { should be_able_to(:discover, asset) } it { should be_able_to(:read, asset) } @@ -131,14 +132,14 @@ end end - describe "Given an asset which registered users have read access to" do + describe 'Given an asset which registered users have read access to' do # let(:asset) { FactoryBot.create(:org_read_access_asset) } let(:asset) { FactoryBot.create(:asset) } before do - asset.permissions_attributes = [{ name: "registered", access: "read", type: "group" }, { name: "joe_creator", access: "edit", type: "person" }, { name: "calvin_collaborator", access: "edit", type: "person" }] + asset.permissions_attributes = [{ name: 'registered', access: 'read', type: 'group' }, { name: 'joe_creator', access: 'edit', type: 'person' }, { name: 'calvin_collaborator', access: 'edit', type: 'person' }] asset.save end - context "The a registered user" do + context 'The a registered user' do let(:user) { FactoryBot.build(:registered_user) } before do allow(user).to receive(:new_record?).and_return(false) @@ -153,15 +154,15 @@ end end - describe "Given an asset with collaborator" do + describe 'Given an asset with collaborator' do let(:asset) { FactoryBot.create(:asset) } before do - asset.permissions_attributes = [{ name:"africana-faculty", access: "edit", type: "group" }, {name: "calvin_collaborator", access: "edit", type: "person"}] + asset.permissions_attributes = [{ name: 'africana-faculty', access: 'edit', type: 'group' }, { name: 'calvin_collaborator', access: 'edit', type: 'person' }] asset.save end after { asset.destroy } - context "Then a collaborator with edit access (user permision)" do + context 'Then a collaborator with edit access (user permision)' do let(:user) { FactoryBot.build(:calvin_collaborator) } it { should be_able_to(:discover, asset) } @@ -172,24 +173,24 @@ it { should_not be_able_to(:admin, asset) } end - context "Then a collaborator with edit access (group permision)" do + context 'Then a collaborator with edit access (group permision)' do let(:user) { FactoryBot.build(:martia_morocco) } before do - allow(user).to receive(:groups).and_return(["faculty", "africana-faculty"]) + allow(user).to receive(:groups).and_return(['faculty', 'africana-faculty']) end it { should be_able_to(:read, asset) } end end - describe "Given an asset where dept can read & registered users can discover" do + describe 'Given an asset where dept can read & registered users can discover' do # let(:asset) { FactoryBot.create(:dept_access_asset) } let(:asset) { FactoryBot.create(:asset) } before do - asset.permissions_attributes = [{ name: "africana-faculty", access: "read", type: "group" }, { name: "joe_creator", access: "edit", type: "person" }] + asset.permissions_attributes = [{ name: 'africana-faculty', access: 'read', type: 'group' }, { name: 'joe_creator', access: 'edit', type: 'person' }] asset.save end - context "Then a registered user" do + context 'Then a registered user' do let(:user) { FactoryBot.build(:registered_user) } it { should_not be_able_to(:discover, asset) } @@ -200,10 +201,10 @@ it { should_not be_able_to(:admin, asset) } end - context "Then someone whose role/group has read access" do + context 'Then someone whose role/group has read access' do let(:user) { FactoryBot.build(:martia_morocco) } before do - allow(user).to receive(:groups).and_return(["faculty", "africana-faculty"]) + allow(user).to receive(:groups).and_return(['faculty', 'africana-faculty']) end it { should be_able_to(:discover, asset) } @@ -215,13 +216,12 @@ end end - - describe "custom method" do + describe 'custom method' do before do class MyAbility include Blacklight::AccessControls::Ability include Hydra::Ability - self.ability_logic +=[:setup_my_permissions] + self.ability_logic += [:setup_my_permissions] def setup_my_permissions can :accept, ActiveFedora::Base @@ -237,14 +237,13 @@ def setup_my_permissions subject { MyAbility.new(user) } it { should be_able_to(:accept, ActiveFedora::Base) } - end - describe "calling ability on two separate objects" do + describe 'calling ability on two separate objects' do let(:asset1) { FactoryBot.create(:asset) } let(:asset2) { FactoryBot.create(:asset) } before do - asset1.permissions_attributes = [{ name: "registered", access: "read", type: "group" }, { name: "joe_creator", access: "edit", type: "person" }, { name: "calvin_collaborator", access: "edit", type: "person" }] + asset1.permissions_attributes = [{ name: 'registered', access: 'read', type: 'group' }, { name: 'joe_creator', access: 'edit', type: 'person' }, { name: 'calvin_collaborator', access: 'edit', type: 'person' }] asset1.save end let(:user) { FactoryBot.build(:calvin_collaborator) } # has access to @asset1, but not @asset2 @@ -253,25 +252,25 @@ def setup_my_permissions asset2.destroy end - it "is readable in the first instance and not in the second instance" do + it 'is readable in the first instance and not in the second instance' do # We had a bug around this where it keeps returning the access for the first object queried expect(subject).to be_able_to(:edit, asset1) expect(subject).to_not be_able_to(:edit, asset2) end end - describe "download permissions" do + describe 'download permissions' do let(:asset) { FactoryBot.create(:asset) } let(:user) { FactoryBot.build(:user) } - let(:file) { ActiveFedora::File.new() } + let(:file) { ActiveFedora::File.new } before { allow(file).to receive(:uri).and_return(uri) } after { asset.destroy } - context "in AF < 9.2" do + context 'in AF < 9.2' do let(:uri) { "#{asset.uri}/ds1" } - context "user has read permission on the object" do + context 'user has read permission on the object' do before do asset.read_users = [user.user_key] asset.save! @@ -281,16 +280,16 @@ def setup_my_permissions it { should be_able_to(:download, file) } end - context "user lacks read permission on the object and file" do + context 'user lacks read permission on the object and file' do it { should_not be_able_to(:read, asset) } it { should_not be_able_to(:download, file) } end end - context "in AF >= 9.2" do + context 'in AF >= 9.2' do let(:uri) { RDF::URI("#{asset.uri}/ds1") } - context "user has read permission on the object" do + context 'user has read permission on the object' do before do asset.read_users = [user.user_key] asset.save! diff --git a/hydra-access-controls/spec/unit/access_controls_enforcement_spec.rb b/hydra-access-controls/spec/unit/access_controls_enforcement_spec.rb index 9e95c5f7d..c4e47c35b 100644 --- a/hydra-access-controls/spec/unit/access_controls_enforcement_spec.rb +++ b/hydra-access-controls/spec/unit/access_controls_enforcement_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::AccessControlsEnforcement do diff --git a/hydra-access-controls/spec/unit/access_right_spec.rb b/hydra-access-controls/spec/unit/access_right_spec.rb index 9315f971d..b9cf8a818 100644 --- a/hydra-access-controls/spec/unit/access_right_spec.rb +++ b/hydra-access-controls/spec/unit/access_right_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::AccessControls::AccessRight do @@ -15,11 +17,11 @@ [true, Hydra::AccessControls::AccessRight::PERMISSION_TEXT_VALUE_PUBLIC, nil, 2.days.from_now, false, false, false, true], [true, Hydra::AccessControls::AccessRight::PERMISSION_TEXT_VALUE_PUBLIC, nil, 2.days.ago, false, false, false, true], [true, Hydra::AccessControls::AccessRight::PERMISSION_TEXT_VALUE_AUTHENTICATED, nil, nil, false, true, false, false], - [true, nil, nil, nil, false, false, true, false], + [true, nil, nil, nil, false, false, true, false], [true, nil, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC, nil, true, false, false, false], [true, nil, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED, nil, false, true, false, false], [true, nil, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE, nil, false, false, true, false], - [true, nil, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_EMBARGO, nil, false, false, false, true], + [true, nil, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_EMBARGO, nil, false, false, false, true] ].each do |given_persisted, givin_permission, given_visibility, given_embargo_release_date, expected_open_access, expected_authentication_only, expected_private, expected_open_access_with_embargo_release_date| spec_text = <<-TEXT @@ -39,9 +41,9 @@ it spec_text do permissions = if givin_permission - [Hydra::AccessControls::Permission.new(type: 'group', access: 'edit', name: givin_permission)] - else - [] + [Hydra::AccessControls::Permission.new(type: 'group', access: 'edit', name: givin_permission)] + else + [] end permissionable = double( diff --git a/hydra-access-controls/spec/unit/accessible_by_spec.rb b/hydra-access-controls/spec/unit/accessible_by_spec.rb index 5d937ec77..121ac99b0 100644 --- a/hydra-access-controls/spec/unit/accessible_by_spec.rb +++ b/hydra-access-controls/spec/unit/accessible_by_spec.rb @@ -1,34 +1,36 @@ +# frozen_string_literal: true + require 'spec_helper' -describe "active_fedora/accessible_by" do - let(:user) {FactoryBot.build(:ira_instructor)} - let(:ability) {Ability.new(user)} - let(:private_obj) {FactoryBot.create(:asset)} - let(:public_obj) {FactoryBot.create(:asset)} - let(:editable_obj) {FactoryBot.create(:asset)} +describe 'active_fedora/accessible_by' do + let(:user) { FactoryBot.build(:ira_instructor) } + let(:ability) { Ability.new(user) } + let(:private_obj) { FactoryBot.create(:asset) } + let(:public_obj) { FactoryBot.create(:asset) } + let(:editable_obj) { FactoryBot.create(:asset) } before do - private_obj.permissions_attributes = [{ name: "joe_creator", access: "edit", type: "person" }] + private_obj.permissions_attributes = [{ name: 'joe_creator', access: 'edit', type: 'person' }] private_obj.save - public_obj.permissions_attributes = [{ name: "public", access: "read", type: "group" }, { name: "joe_creator", access: "edit", type: "person" }, { name: "calvin_collaborator", access: "edit", type: "person" }] + public_obj.permissions_attributes = [{ name: 'public', access: 'read', type: 'group' }, { name: 'joe_creator', access: 'edit', type: 'person' }, { name: 'calvin_collaborator', access: 'edit', type: 'person' }] public_obj.save - editable_obj.permissions_attributes = [{ name:"africana-faculty", access: "edit", type: "group" }, {name: "calvin_collaborator", access: "edit", type: "person"}] + editable_obj.permissions_attributes = [{ name: 'africana-faculty', access: 'edit', type: 'group' }, { name: 'calvin_collaborator', access: 'edit', type: 'person' }] editable_obj.save - expect(user).to receive(:groups).at_most(:once).and_return(["faculty", "africana-faculty"]) + expect(user).to receive(:groups).at_most(:once).and_return(['faculty', 'africana-faculty']) end after do ModsAsset.delete_all end - describe "#accsesible_by" do - it "should return objects readable by the ability" do + describe '#accsesible_by' do + it 'should return objects readable by the ability' do expect(ModsAsset.accessible_by(ability)).to eq [public_obj, editable_obj] end - it "should return object editable by the ability" do + it 'should return object editable by the ability' do expect(ModsAsset.accessible_by(ability, :edit)).to eq [editable_obj] end - it "should return only public objects for an anonymous user" do + it 'should return only public objects for an anonymous user' do expect(ModsAsset.accessible_by(Ability.new(nil))).to eq [public_obj] end end diff --git a/hydra-access-controls/spec/unit/admin_policy_spec.rb b/hydra-access-controls/spec/unit/admin_policy_spec.rb index bb68e4b4d..587c4f3b2 100644 --- a/hydra-access-controls/spec/unit/admin_policy_spec.rb +++ b/hydra-access-controls/spec/unit/admin_policy_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::AdminPolicy do @@ -5,97 +7,95 @@ allow(Devise).to receive(:authentication_keys).and_return(['uid']) end - describe "when setting attributes" do + describe 'when setting attributes' do before do - subject.title = ["My title"] - subject.description = ["My description"] + subject.title = ['My title'] + subject.description = ['My description'] end - its(:title) { is_expected.to eq "My title"} - its(:description) { is_expected.to eq "My description"} + its(:title) { is_expected.to eq 'My title' } + its(:description) { is_expected.to eq 'My description' } end - - describe "to_solr" do - subject { Hydra::AdminPolicy.new(:title=>["Foobar"]).to_solr } - it "should have title_ssim" do - expect(subject[ActiveFedora.index_field_mapper.solr_name('title', type: :string)]).to eq ["Foobar"] + describe 'to_solr' do + subject { Hydra::AdminPolicy.new(title: ['Foobar']).to_solr } + it 'should have title_ssim' do + expect(subject[ActiveFedora.index_field_mapper.solr_name('title', type: :string)]).to eq ['Foobar'] end end - describe "updating default permissions" do - it "should create new group permissions" do - subject.default_permissions.build({:name=>'group1', :access=>'discover', :type=>'group'}) - expect(subject.default_permissions.map(&:to_hash)).to eq [{:type=>'group', :access=>'discover', :name=>'group1'}] + describe 'updating default permissions' do + it 'should create new group permissions' do + subject.default_permissions.build(name: 'group1', access: 'discover', type: 'group') + expect(subject.default_permissions.map(&:to_hash)).to eq [{ type: 'group', access: 'discover', name: 'group1' }] end - it "should create new user permissions" do - subject.default_permissions.build({:name=>'user1', :access=>'discover', :type=>'person'}) - expect(subject.default_permissions.map(&:to_hash)).to eq [{:type=>'person', :access=>'discover', :name=>'user1'}] + it 'should create new user permissions' do + subject.default_permissions.build(name: 'user1', access: 'discover', type: 'person') + expect(subject.default_permissions.map(&:to_hash)).to eq [{ type: 'person', access: 'discover', name: 'user1' }] end - it "should not replace existing groups" do - subject.default_permissions.build({:name=>'group1', :access=>'discover', :type=>'group'}) - subject.default_permissions.build({:name=>'group2', :access=>'discover', :type=>'group'}) - expect(subject.default_permissions.map(&:to_hash)).to eq [{:type=>'group', :access=>'discover', :name=>'group1'}, - {:type=>'group', :access=>'discover', :name=>'group2'}] + it 'should not replace existing groups' do + subject.default_permissions.build(name: 'group1', access: 'discover', type: 'group') + subject.default_permissions.build(name: 'group2', access: 'discover', type: 'group') + expect(subject.default_permissions.map(&:to_hash)).to eq [{ type: 'group', access: 'discover', name: 'group1' }, + { type: 'group', access: 'discover', name: 'group2' }] end - it "should not replace existing users" do - subject.default_permissions.build({:name=>'user1', :access=>'discover', :type=>'person'}) - subject.default_permissions.build({:name=>'user2', :access=>'discover', :type=>'person'}) - expect(subject.default_permissions.map(&:to_hash)).to eq [{:type=>'person', :access=>'discover', :name=>'user1'}, - {:type=>'person', :access=>'discover', :name=>'user2'}] + it 'should not replace existing users' do + subject.default_permissions.build(name: 'user1', access: 'discover', type: 'person') + subject.default_permissions.build(name: 'user2', access: 'discover', type: 'person') + expect(subject.default_permissions.map(&:to_hash)).to eq [{ type: 'person', access: 'discover', name: 'user1' }, + { type: 'person', access: 'discover', name: 'user2' }] end - it "updates permissions on existing users" do - subject.default_permissions.build({:name=>'user1', :access=>'discover', :type=>'person'}) + it 'updates permissions on existing users' do + subject.default_permissions.build(name: 'user1', access: 'discover', type: 'person') subject.default_permissions.first.mode = [Hydra::AccessControls::Mode.new(::ACL.Write)] - expect(subject.default_permissions.map(&:to_hash)).to eq [{:type=>'person', :access=>'edit', :name=>'user1'}] + expect(subject.default_permissions.map(&:to_hash)).to eq [{ type: 'person', access: 'edit', name: 'user1' }] end - it "updates permissions on existing groups" do - subject.default_permissions.build({:name=>'group1', :access=>'discover', :type=>'group'}) + it 'updates permissions on existing groups' do + subject.default_permissions.build(name: 'group1', access: 'discover', type: 'group') subject.default_permissions.first.mode = [Hydra::AccessControls::Mode.new(::ACL.Write)] - expect(subject.default_permissions.map(&:to_hash)).to eq [{:type=>'group', :access=>'edit', :name=>'group1'}] + expect(subject.default_permissions.map(&:to_hash)).to eq [{ type: 'group', access: 'edit', name: 'group1' }] end it "should assign user permissions when :type == 'person'" do - subject.default_permissions.build({:name=>'user1', :access=>'discover', :type=>'person'}) - expect(subject.default_permissions.map(&:to_hash)).to eq [{:type=>'person', :access=>'discover', :name=>'user1'}] + subject.default_permissions.build(name: 'user1', access: 'discover', type: 'person') + expect(subject.default_permissions.map(&:to_hash)).to eq [{ type: 'person', access: 'discover', name: 'user1' }] end - it "should raise an ArgumentError when the :type hashkey is invalid" do - expect { subject.default_permissions.build({:name=>'user1', :access=>'read', :type=>'foo'}) }.to raise_error(ArgumentError, 'Unknown agent type "foo"') + it 'should raise an ArgumentError when the :type hashkey is invalid' do + expect { subject.default_permissions.build(name: 'user1', access: 'read', type: 'foo') }.to raise_error(ArgumentError, 'Unknown agent type "foo"') end end - describe "Inheritable rights" do + describe 'Inheritable rights' do let(:policy) { described_class.new } before do policy.default_permissions.build([ - {:name=>"africana-faculty", :access=>"edit", :type=>"group"}, - {:name=>"cool-kids", :access=>"edit", :type=>"group"}, - {:name=>"julius_caesar", :access=>"edit", :type=>"person"}, - {:name=>"slightlycoolkids", :access=>"read", :type=>"group"}, - {:name=>"nero", :access=>"read", :type=>"person"}, - {:name=>"posers", :access=>"discover", :type=>"group"}, - {:name=>"constantine", :access=>"discover", :type=>"person"} - ]) - policy.build_default_embargo.embargo_release_date = "2102-10-01" + { name: 'africana-faculty', access: 'edit', type: 'group' }, + { name: 'cool-kids', access: 'edit', type: 'group' }, + { name: 'julius_caesar', access: 'edit', type: 'person' }, + { name: 'slightlycoolkids', access: 'read', type: 'group' }, + { name: 'nero', access: 'read', type: 'person' }, + { name: 'posers', access: 'discover', type: 'group' }, + { name: 'constantine', access: 'discover', type: 'person' } + ]) + policy.build_default_embargo.embargo_release_date = '2102-10-01' end - describe "persisting" do + describe 'persisting' do before do policy.save! policy.reload end - it "has the permissions that were set" do + it 'has the permissions that were set' do expect(policy.default_permissions.size).to eq 7 end - end - describe "indexing" do + describe 'indexing' do subject { policy.to_solr } - it "should not affect normal solr permissions fields" do + it 'should not affect normal solr permissions fields' do expect(subject).to_not have_key Hydra.config.permissions.discover.group expect(subject).to_not have_key Hydra.config.permissions.discover.individual expect(subject).to_not have_key Hydra.config.permissions.read.group @@ -105,28 +105,27 @@ expect(subject).to_not have_key Hydra.config.permissions.embargo.release_date end - it "should provide prefixed/inherited solr permissions fields" do - expect(subject[Hydra.config.permissions.inheritable.discover.group]).to eq ["posers"] - expect(subject[Hydra.config.permissions.inheritable.discover.individual]).to eq ["constantine"] - expect(subject[Hydra.config.permissions.inheritable.read.group]).to eq ["slightlycoolkids"] - expect(subject[Hydra.config.permissions.inheritable.read.individual]).to eq ["nero"] - expect(subject[Hydra.config.permissions.inheritable.edit.group]).to match_array ["africana-faculty", "cool-kids"] + it 'should provide prefixed/inherited solr permissions fields' do + expect(subject[Hydra.config.permissions.inheritable.discover.group]).to eq ['posers'] + expect(subject[Hydra.config.permissions.inheritable.discover.individual]).to eq ['constantine'] + expect(subject[Hydra.config.permissions.inheritable.read.group]).to eq ['slightlycoolkids'] + expect(subject[Hydra.config.permissions.inheritable.read.individual]).to eq ['nero'] + expect(subject[Hydra.config.permissions.inheritable.edit.group]).to match_array ['africana-faculty', 'cool-kids'] - expect(subject[Hydra.config.permissions.inheritable.edit.individual]).to eq ["julius_caesar"] - expect(subject[Hydra.config.permissions.inheritable.embargo.release_date]).to eq DateTime.parse("2102-10-01").to_time.utc.iso8601 + expect(subject[Hydra.config.permissions.inheritable.edit.individual]).to eq ['julius_caesar'] + expect(subject[Hydra.config.permissions.inheritable.embargo.release_date]).to eq DateTime.parse('2102-10-01').to_time.utc.iso8601 end end - end # # Policy-based Access Controls # - describe "When accessing assets with Policies associated" do + describe 'When accessing assets with Policies associated' do let(:user) { FactoryBot.build(:martia_morocco) } before do - allow(user).to receive(:groups).and_return(["faculty", "africana-faculty"]) + allow(user).to receive(:groups).and_return(['faculty', 'africana-faculty']) end before(:all) do @@ -141,25 +140,25 @@ class TestAbility subject { TestAbility.new(user) } - context "Given a policy grants read access to a group I belong to" do + context 'Given a policy grants read access to a group I belong to' do before do @policy = Hydra::AdminPolicy.new - @policy.default_permissions.build({:type=>"group", :access=>"read", :name=>"africana-faculty"}) + @policy.default_permissions.build(type: 'group', access: 'read', name: 'africana-faculty') @policy.save end - context "And a subscribing asset does not grant access" do - before do - @asset = ModsAsset.new() + context 'And a subscribing asset does not grant access' do + before do + @asset = ModsAsset.new @asset.admin_policy = @policy @asset.save end - it "Then I should be able to view the asset" do - expect(subject.can?(:read, @asset)).to be true - end + it 'Then I should be able to view the asset' do + expect(subject.can?(:read, @asset)).to be true + end - it "Then I should not be able to edit, update and destroy the asset" do + it 'Then I should not be able to edit, update and destroy the asset' do expect(subject.can?(:edit, @asset)).to be false expect(subject.can?(:update, @asset)).to be false expect(subject.can?(:destroy, @asset)).to be false @@ -167,44 +166,44 @@ class TestAbility end end - context "Given a policy grants edit access to a group I belong to" do + context 'Given a policy grants edit access to a group I belong to' do before do @policy = Hydra::AdminPolicy.new - @policy.default_permissions.build({:type=>"group", :access=>"edit", :name=>"africana-faculty"}) + @policy.default_permissions.build(type: 'group', access: 'edit', name: 'africana-faculty') @policy.save end - context "And a subscribing asset does not grant access" do - before do - @asset = ModsAsset.new() + context 'And a subscribing asset does not grant access' do + before do + @asset = ModsAsset.new @asset.admin_policy = @policy @asset.save end - it "Then I should be able to view the asset" do - expect(subject.can?(:read, @asset)).to be true - end + it 'Then I should be able to view the asset' do + expect(subject.can?(:read, @asset)).to be true + end - it "Then I should be able to edit/update/destroy the asset" do + it 'Then I should be able to edit/update/destroy the asset' do expect(subject.can?(:edit, @asset)).to be true expect(subject.can?(:update, @asset)).to be true expect(subject.can?(:destroy, @asset)).to be true end - end + end - context "And a subscribing asset grants read access to me as an individual" do - before do - @asset = ModsAsset.new() + context 'And a subscribing asset grants read access to me as an individual' do + before do + @asset = ModsAsset.new @asset.read_users = [user.uid] @asset.admin_policy = @policy @asset.save end - it "Then I should be able to view the asset" do - expect(subject.can?(:read, @asset)).to be true - end + it 'Then I should be able to view the asset' do + expect(subject.can?(:read, @asset)).to be true + end - it "Then I should be able to edit/update/destroy the asset" do + it 'Then I should be able to edit/update/destroy the asset' do expect(subject.can?(:edit, @asset)).to be true expect(subject.can?(:update, @asset)).to be true expect(subject.can?(:destroy, @asset)).to be true @@ -212,43 +211,43 @@ class TestAbility end end - context "Given a policy does not grant access to any group I belong to" do + context 'Given a policy does not grant access to any group I belong to' do before do @policy = Hydra::AdminPolicy.new @policy.save end - context "And a subscribing asset does not grant access" do + context 'And a subscribing asset does not grant access' do before do - @asset = ModsAsset.new() + @asset = ModsAsset.new @asset.admin_policy = @policy @asset.save end - it "Then I should not be able to view the asset" do - expect(subject.can?(:read, @asset)).to be false - end + it 'Then I should not be able to view the asset' do + expect(subject.can?(:read, @asset)).to be false + end - it "Then I should not be able to edit/update/destroy the asset" do + it 'Then I should not be able to edit/update/destroy the asset' do expect(subject.can?(:edit, @asset)).to be false expect(subject.can?(:update, @asset)).to be false expect(subject.can?(:destroy, @asset)).to be false end end - context "And a subscribing asset grants read access to me as an individual" do + context 'And a subscribing asset grants read access to me as an individual' do before do - @asset = ModsAsset.new() + @asset = ModsAsset.new @asset.read_users = [user.uid] @asset.admin_policy = @policy @asset.save end - it "Then I should be able to view the asset" do - expect(subject.can?(:read, @asset)).to be true - end + it 'Then I should be able to view the asset' do + expect(subject.can?(:read, @asset)).to be true + end - it "Then I should not be able to edit/update/destroy the asset" do + it 'Then I should not be able to edit/update/destroy the asset' do expect(subject.can?(:edit, @asset)).to be false expect(subject.can?(:update, @asset)).to be false expect(subject.can?(:destroy, @asset)).to be false diff --git a/hydra-access-controls/spec/unit/collection_relationship_spec.rb b/hydra-access-controls/spec/unit/collection_relationship_spec.rb index 48d7f611d..67d949bf2 100644 --- a/hydra-access-controls/spec/unit/collection_relationship_spec.rb +++ b/hydra-access-controls/spec/unit/collection_relationship_spec.rb @@ -1,31 +1,33 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::AccessControl::CollectionRelationship do let(:access_control) { Hydra::AccessControl.new } let(:relationship) { access_control.relationship } - describe "#==" do + describe '#==' do subject { relationship } - it "compares to array" do + it 'compares to array' do expect(subject).to eq [] end end - describe "#first" do + describe '#first' do let!(:one) { relationship.build(name: 'user1', type: 'person', access: 'read') } let!(:two) { relationship.build(name: 'user2', type: 'person', access: 'read') } subject { relationship.first } it { is_expected.to be one } end - describe "#last" do + describe '#last' do let!(:one) { relationship.build(name: 'user1', type: 'person', access: 'read') } let!(:two) { relationship.build(name: 'user2', type: 'person', access: 'read') } subject { relationship.last } it { is_expected.to be two } end - describe "#include?" do + describe '#include?' do let!(:one) { relationship.build(name: 'user1', type: 'person', access: 'read') } let(:two) { Hydra::AccessControls::Permission.new(name: 'user2', type: 'person', access: 'read') } it 'returns a boolean' do @@ -34,69 +36,69 @@ end end - describe "#empty?" do + describe '#empty?' do subject { relationship.empty? } it { is_expected.to be true } end - describe "#each" do + describe '#each' do let!(:one) { relationship.build(name: 'user1', type: 'person', access: 'read') } let!(:two) { relationship.build(name: 'user2', type: 'person', access: 'read') } let(:counter) { double } - it "invokes the block with each object" do + it 'invokes the block with each object' do expect(counter).to receive(:check).with(one) expect(counter).to receive(:check).with(two) relationship.each { |o| counter.check(o) } end end - describe "#map" do + describe '#map' do let!(:one) { relationship.build(name: 'user1', type: 'person', access: 'read') } let!(:two) { relationship.build(name: 'user2', type: 'person', access: 'read') } - it "maps each element through the block" do - expect(relationship.map { |o| o.agent_name }).to eq ['user1', 'user2'] + it 'maps each element through the block' do + expect(relationship.map(&:agent_name)).to eq %w[user1 user2] end end - describe "#detect" do + describe '#detect' do let!(:one) { relationship.build(name: 'user1', type: 'person', access: 'read') } let!(:two) { relationship.build(name: 'user2', type: 'person', access: 'read') } - it "finds the first match" do + it 'finds the first match' do expect(relationship.detect { |o| o.agent_name == 'user2' }).to eq two end end - describe "#find" do + describe '#find' do before do access_control.save! end let!(:one) { relationship.create(name: 'user1', type: 'person', access: 'read') } let!(:two) { relationship.create(name: 'user2', type: 'person', access: 'read') } - context "when the id is in the set" do - it "finds matches by id" do + context 'when the id is in the set' do + it 'finds matches by id' do expect(relationship.find(two.id)).to eq two end end - context "when the id is not the set" do - it "raises an error" do + context 'when the id is not the set' do + it 'raises an error' do expect { relationship.find('999') }.to raise_error ArgumentError, "requested ACL (999) is not a member of #{access_control.id}" end end end - describe "#any?" do + describe '#any?' do let!(:one) { relationship.build(name: 'user1', type: 'person', access: 'read') } let!(:two) { relationship.build(name: 'user2', type: 'person', access: 'read') } - it "invokes the block with each object" do + it 'invokes the block with each object' do expect(relationship.any? { |o| o.agent_name == 'user2' }).to be true end end - describe "#all?" do + describe '#all?' do let!(:one) { relationship.build(name: 'user1', type: 'person', access: 'read') } let!(:two) { relationship.build(name: 'user2', type: 'person', access: 'read') } let(:counter) { double } - context "when all members satisfy the condition" do + context 'when all members satisfy the condition' do subject { relationship.all? { |o| o.type == 'person' } } it { is_expected.to be true } end @@ -106,14 +108,14 @@ end end - describe "#destroy_all" do + describe '#destroy_all' do before do access_control.save! end let!(:one) { relationship.create(name: 'user1', type: 'person', access: 'read') } let!(:two) { relationship.create(name: 'user2', type: 'person', access: 'read') } - it "invokes the block with each object" do - expect { relationship.destroy_all }.to change { Hydra::AccessControls::Permission.count}.by(-2) + it 'invokes the block with each object' do + expect { relationship.destroy_all }.to change { Hydra::AccessControls::Permission.count }.by(-2) end end end diff --git a/hydra-access-controls/spec/unit/config_spec.rb b/hydra-access-controls/spec/unit/config_spec.rb index 7b240abd8..87fbad155 100644 --- a/hydra-access-controls/spec/unit/config_spec.rb +++ b/hydra-access-controls/spec/unit/config_spec.rb @@ -1,61 +1,63 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::Config do let (:config) { subject } - it "Should accept a hash based config" do - # This specifies the solr field names of permissions-related fields. - # You only need to change these values if you've indexed permissions by some means other than the Hydra's built-in tooling. - # If you change these, you must also update the permissions request handler in your solrconfig.xml to return those values - config[:permissions] = { - discover: { group: ActiveFedora.index_field_mapper.solr_name("discover_access_group", :symbol), - individual: ActiveFedora.index_field_mapper.solr_name("discover_access_person", :symbol)}, - read: { group: ActiveFedora.index_field_mapper.solr_name("read_access_group", :symbol), - individual: ActiveFedora.index_field_mapper.solr_name("read_access_person", :symbol)}, - edit: { group: ActiveFedora.index_field_mapper.solr_name("edit_access_group", :symbol), - individual: ActiveFedora.index_field_mapper.solr_name("edit_access_person", :symbol)}, - owner: ActiveFedora.index_field_mapper.solr_name("depositor", :symbol), - } - config.permissions.embargo.release_date = ActiveFedora.index_field_mapper.solr_name("embargo_release_date", ActiveFedora::Indexing::Descriptor.new(:date, :stored, :indexed)) - - # specify the user model - config[:user_model] = 'User' - - expect(config[:permissions][:edit][:individual]).to eq 'edit_access_person_ssim' + it 'Should accept a hash based config' do + # This specifies the solr field names of permissions-related fields. + # You only need to change these values if you've indexed permissions by some means other than the Hydra's built-in tooling. + # If you change these, you must also update the permissions request handler in your solrconfig.xml to return those values + config[:permissions] = { + discover: { group: ActiveFedora.index_field_mapper.solr_name('discover_access_group', :symbol), + individual: ActiveFedora.index_field_mapper.solr_name('discover_access_person', :symbol) }, + read: { group: ActiveFedora.index_field_mapper.solr_name('read_access_group', :symbol), + individual: ActiveFedora.index_field_mapper.solr_name('read_access_person', :symbol) }, + edit: { group: ActiveFedora.index_field_mapper.solr_name('edit_access_group', :symbol), + individual: ActiveFedora.index_field_mapper.solr_name('edit_access_person', :symbol) }, + owner: ActiveFedora.index_field_mapper.solr_name('depositor', :symbol) + } + config.permissions.embargo.release_date = ActiveFedora.index_field_mapper.solr_name('embargo_release_date', ActiveFedora::Indexing::Descriptor.new(:date, :stored, :indexed)) + + # specify the user model + config[:user_model] = 'User' + + expect(config[:permissions][:edit][:individual]).to eq 'edit_access_person_ssim' end - it "should accept a struct based config" do - # This specifies the solr field names of permissions-related fields. - # You only need to change these values if you've indexed permissions by some means other than the Hydra's built-in tooling. - # If you change these, you must also update the permissions request handler in your solrconfig.xml to return those values - config.permissions.discover.group = ActiveFedora.index_field_mapper.solr_name("discover_access_group", :symbol) + it 'should accept a struct based config' do + # This specifies the solr field names of permissions-related fields. + # You only need to change these values if you've indexed permissions by some means other than the Hydra's built-in tooling. + # If you change these, you must also update the permissions request handler in your solrconfig.xml to return those values + config.permissions.discover.group = ActiveFedora.index_field_mapper.solr_name('discover_access_group', :symbol) - # specify the user model - config.user_model = 'User' + # specify the user model + config.user_model = 'User' - expect(config.permissions.discover.group).to eq 'discover_access_group_ssim' - expect(config.user_model).to eq 'User' + expect(config.permissions.discover.group).to eq 'discover_access_group_ssim' + expect(config.user_model).to eq 'User' end - it "should have inheritable attributes" do - expect(config[:permissions][:inheritable][:edit][:individual]).to eq 'inheritable_edit_access_person_ssim' + it 'should have inheritable attributes' do + expect(config[:permissions][:inheritable][:edit][:individual]).to eq 'inheritable_edit_access_person_ssim' end - it "should have a nil policy_class" do - expect(config[:permissions][:policy_class]).to be_nil + it 'should have a nil policy_class' do + expect(config[:permissions][:policy_class]).to be_nil end - it "has defaults" do + it 'has defaults' do expect(config.permissions.read.individual).to eq 'read_access_person_ssim' expect(config.permissions.embargo.release_date).to eq 'embargo_release_date_dtsi' expect(config.user_model).to eq 'User' expect(config.user_key_field).to eq :email end - describe "user_key_field" do + describe 'user_key_field' do after do # restore default config.user_key_field = :email end - - it "is settable" do + + it 'is settable' do config.user_key_field = :uid expect(config.user_key_field).to eq :uid end diff --git a/hydra-access-controls/spec/unit/embargoable_spec.rb b/hydra-access-controls/spec/unit/embargoable_spec.rb index eabe40067..d25d57e45 100644 --- a/hydra-access-controls/spec/unit/embargoable_spec.rb +++ b/hydra-access-controls/spec/unit/embargoable_spec.rb @@ -1,7 +1,8 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::AccessControls::Embargoable do - before do class TestModel < ActiveFedora::Base def save(returning_value = true) @@ -14,8 +15,8 @@ def save(returning_value = true) after { Object.send(:remove_const, :TestModel) } - let(:future_date) { Date.today+2 } - let(:past_date) { Date.today-2 } + let(:future_date) { Date.today + 2 } + let(:past_date) { Date.today - 2 } let(:model) { TestModel.new } subject { model } @@ -30,16 +31,16 @@ def save(returning_value = true) end describe 'validations' do - context "with dates" do + context 'with dates' do subject { ModsAsset.new(lease_expiration_date: past_date, embargo_release_date: past_date) } - it "validates embargo_release_date and lease_expiration_date" do + it 'validates embargo_release_date and lease_expiration_date' do expect(subject).to_not be_valid expect(subject.errors[:lease_expiration_date]).to eq ['Must be a future date'] expect(subject.errors[:embargo_release_date]).to eq ['Must be a future date'] end end - context "without an embargo" do + context 'without an embargo' do subject { ModsAsset.new } before { subject.valid? } @@ -55,7 +56,7 @@ def save(returning_value = true) end context 'visibility=' do - context "when the object is not under embargo or lease" do + context 'when the object is not under embargo or lease' do before do subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE end @@ -65,22 +66,22 @@ def save(returning_value = true) end end - context "when changing from embargo" do + context 'when changing from embargo' do before do subject.embargo_release_date = future_date.to_s end - it "wipes out associated embargo metadata" do + it 'wipes out associated embargo metadata' do expect(subject).to receive(:deactivate_embargo!) subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC end end - context "when changing from lease" do + context 'when changing from lease' do before do subject.apply_lease(future_date.to_s, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE) end - it "wipes out associated lease metadata and marks visibility as changed" do + it 'wipes out associated lease metadata and marks visibility as changed' do expect(subject).to receive(:deactivate_lease!) subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC expect(subject).to be_visibility_changed @@ -89,27 +90,27 @@ def save(returning_value = true) end describe '#apply_embargo' do - it "applies appropriate embargo_visibility settings" do - expect { + it 'applies appropriate embargo_visibility settings' do + expect do subject.apply_embargo(future_date.to_s, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC) - }.to change { subject.visibility_changed? }.from(false).to(true) + end.to change { subject.visibility_changed? }.from(false).to(true) expect(subject).to be_under_embargo - expect(subject.visibility).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE + expect(subject.visibility).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE expect(subject.embargo_release_date).to eq future_date expect(subject.visibility_after_embargo).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC end - context "when no before/after visibility is provided" do - it "relies on defaults" do + context 'when no before/after visibility is provided' do + it 'relies on defaults' do subject.apply_embargo(future_date.to_s) expect(subject).to be_under_embargo - expect(subject.visibility).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE + expect(subject.visibility).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE expect(subject.embargo_release_date).to eq future_date expect(subject.visibility_after_embargo).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED end end - context "when the same embargo is applied" do + context 'when the same embargo is applied' do before do subject.apply_embargo(future_date.to_s) if ActiveModel.version < Gem::Version.new('4.2.0') @@ -133,7 +134,7 @@ def save(returning_value = true) subject.embargo_release_date = release_date end - context "when the embargo is expired" do + context 'when the embargo is expired' do let(:release_date) { past_date.to_s } it "should remove the associated embargo information and record it in the object's embargo history" do @@ -146,14 +147,15 @@ def save(returning_value = true) end end - context "when the embargo is active" do + context 'when the embargo is active' do let(:release_date) { future_date.to_s } it "should remove the associated embargo information and record it in the object's embargo history" do - expect { + expect do subject.deactivate_embargo! - }.to change { subject.under_embargo? }.from(true).to(false).and change { - subject.visibility_changed? }.from(false).to(true) + end.to change { subject.under_embargo? }.from(true).to(false).and change { + subject.visibility_changed? + } .from(false).to(true) expect(subject.embargo_release_date).to be_nil expect(subject.visibility_during_embargo).to be_nil expect(subject.visibility_after_embargo).to be_nil @@ -162,10 +164,10 @@ def save(returning_value = true) end end - context "when there is no embargo" do + context 'when there is no embargo' do let(:release_date) { nil } - it "should not do anything" do + it 'should not do anything' do subject.deactivate_embargo! expect(subject.embargo_history).to eq [] end @@ -173,26 +175,26 @@ def save(returning_value = true) end context 'apply_lease' do - context "when the initial value is restricted" do - it "applies appropriate embargo_visibility settings" do + context 'when the initial value is restricted' do + it 'applies appropriate embargo_visibility settings' do subject.apply_lease(future_date.to_s, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE) expect(subject).to be_active_lease expect(subject).to be_visibility_changed - expect(subject.visibility).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC + expect(subject.visibility).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC expect(subject.lease_expiration_date).to eq future_date expect(subject.visibility_after_lease).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE end - context "when before/after visibility is not provided" do - it "sets default values" do + context 'when before/after visibility is not provided' do + it 'sets default values' do subject.apply_lease(future_date.to_s) - expect(subject.visibility_during_lease).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED + expect(subject.visibility_during_lease).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED expect(subject.lease_expiration_date).to eq future_date expect(subject.visibility_after_lease).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE end end - context "when the same lease is applied" do + context 'when the same lease is applied' do before do subject.apply_lease(future_date.to_s) if ActiveModel.version < Gem::Version.new('4.2.0') @@ -209,19 +211,19 @@ def save(returning_value = true) end end - context "when the initial value is public" do + context 'when the initial value is public' do before do subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC # reset the changed log subject.send(:instance_variable_set, :@visibility_will_change, false) end - it "applies appropriate embargo_visibility settings" do - expect { + it 'applies appropriate embargo_visibility settings' do + expect do subject.apply_lease(future_date.to_s, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC, Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE) - }.to change { subject.visibility_changed? }.from(false).to(true) + end.to change { subject.visibility_changed? }.from(false).to(true) expect(subject).to be_active_lease - expect(subject.visibility).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC + expect(subject.visibility).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC expect(subject.lease_expiration_date).to eq future_date expect(subject.visibility_after_lease).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE end @@ -235,13 +237,13 @@ def save(returning_value = true) subject.visibility_after_lease = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE end - context "when the lease is expired" do + context 'when the lease is expired' do let(:expiration_date) { past_date.to_s } it "should remove the associated lease information and record it in the object's lease history" do - expect { + expect do subject.deactivate_lease! - }.to change { subject.visibility_changed? }.from(false).to(true) + end.to change { subject.visibility_changed? }.from(false).to(true) expect(subject.lease_expiration_date).to be_nil expect(subject.visibility_during_lease).to be_nil expect(subject.visibility_after_lease).to be_nil @@ -250,13 +252,13 @@ def save(returning_value = true) end end - context "when the lease is active" do + context 'when the lease is active' do let(:expiration_date) { future_date.to_s } it "should remove the associated lease information and record it in the object's lease history" do - expect { + expect do subject.deactivate_lease! - }.to change { subject.active_lease? }.from(true).to(false) + end.to change { subject.active_lease? }.from(true).to(false) expect(subject.lease_expiration_date).to be_nil expect(subject.visibility_during_lease).to be_nil expect(subject.visibility_after_lease).to be_nil @@ -265,10 +267,10 @@ def save(returning_value = true) end end - context "when there is no lease" do + context 'when there is no lease' do let(:expiration_date) { nil } - it "should not do anything" do + it 'should not do anything' do subject.deactivate_lease! expect(subject.lease_history).to eq [] end @@ -276,14 +278,14 @@ def save(returning_value = true) end context 'under_embargo?' do - context "when embargo date is past" do - it "should return false" do + context 'when embargo date is past' do + it 'should return false' do subject.embargo_release_date = past_date.to_s expect(subject).to_not be_under_embargo end end - context "when embargo date is in future" do - it "should return true" do + context 'when embargo date is in future' do + it 'should return true' do subject.embargo_release_date = future_date.to_s expect(subject).to be_under_embargo end @@ -295,7 +297,7 @@ def save(returning_value = true) subject.visibility_during_embargo = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE subject.visibility_after_embargo = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC end - context "(embargo still in effect)" do + context '(embargo still in effect)' do it 'returns true if current visibility matches visibility_during_embargo' do subject.visibility = subject.visibility_during_embargo subject.embargo_release_date = future_date.to_s @@ -308,7 +310,7 @@ def save(returning_value = true) expect(subject.errors[:embargo].first).to eq "An embargo is in effect for this object until #{subject.embargo_release_date}. Until that time the visibility should be #{Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE} but it is currently #{Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED}. Call embargo_visibility! on this object to repair." end end - context "(embargo expired)" do + context '(embargo expired)' do it 'returns true if current visibility matches visibility_after_embargo' do subject.visibility = subject.visibility_after_embargo subject.embargo_release_date = past_date.to_s @@ -323,7 +325,6 @@ def save(returning_value = true) end end - context 'embargo_visibility!' do let(:future_date) { 2.days.from_now } let(:past_date) { 2.days.ago } @@ -339,7 +340,7 @@ def save(returning_value = true) subject.embargo_visibility! expect(subject.visibility).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC end - it "defaults to private if visibility_after_embargo is not set" do + it 'defaults to private if visibility_after_embargo is not set' do subject.visibility_after_embargo = nil subject.embargo_release_date = past_date.to_s subject.embargo_visibility! @@ -373,7 +374,7 @@ def save(returning_value = true) subject.visibility_during_lease = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC subject.visibility_after_lease = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE end - context "(lease expired)" do + context '(lease expired)' do it 'returns true if current visibility matches visibility_after_lease' do subject.visibility = subject.visibility_after_lease subject.lease_expiration_date = past_date.to_s @@ -386,7 +387,7 @@ def save(returning_value = true) expect(subject.errors[:lease].first).to eq "The lease expired on #{subject.lease_expiration_date}. The visibility should be #{Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE} but it is currently #{Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC}. Call lease_visibility! on this object to repair." end end - context "(lease still in effect)" do + context '(lease still in effect)' do it 'returns true if current visibility matches visibility_during_embargo' do subject.visibility = subject.visibility_during_lease subject.lease_expiration_date = future_date.to_s @@ -399,10 +400,8 @@ def save(returning_value = true) expect(subject.errors[:lease].first).to eq "A lease is in effect for this object until #{subject.lease_expiration_date}. Until that time the visibility should be #{Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC} but it is currently #{Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED}. Call lease_visibility! on this object to repair." end end - end - context 'lease_visibility!' do before do subject.visibility_during_lease = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC @@ -416,7 +415,7 @@ def save(returning_value = true) subject.lease_visibility! expect(subject.visibility).to eq Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE end - it "defaults to private if visibility_after_lease is not set" do + it 'defaults to private if visibility_after_lease is not set' do subject.visibility_after_lease = nil subject.lease_expiration_date = past_date.to_s subject.lease_visibility! @@ -442,7 +441,6 @@ def save(returning_value = true) end end - context 'persistence' do let(:the_date) { 2.days.from_now } @@ -457,16 +455,15 @@ def save(returning_value = true) end it 'raises an error on an empty string' do - expect { + expect do subject.embargo_release_date = '' - }.to raise_error(ArgumentError, "invalid date") + end.to raise_error(ArgumentError, 'invalid date') end it 'does not persist an invalid string' do - expect { - subject.embargo_release_date = "Tim" - }.to raise_error(ArgumentError, "invalid date") + expect do + subject.embargo_release_date = 'Tim' + end.to raise_error(ArgumentError, 'invalid date') end end - end diff --git a/hydra-access-controls/spec/unit/ip_base_ability_spec.rb b/hydra-access-controls/spec/unit/ip_base_ability_spec.rb index e25e6a5b3..8972ab822 100644 --- a/hydra-access-controls/spec/unit/ip_base_ability_spec.rb +++ b/hydra-access-controls/spec/unit/ip_base_ability_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::IpBasedAbility do @@ -7,25 +9,25 @@ class TestAbility < Ability end end - let(:user) { double(groups: ['one', 'two'], new_record?: false) } + let(:user) { double(groups: %w[one two], new_record?: false) } let(:ability) { TestAbility.new(user, args) } let(:args) { {} } - describe "#user_groups" do + describe '#user_groups' do subject { ability.user_groups } - context "when no ip is passed" do - it { is_expected.to eq ['public', 'one', 'two', 'registered'] } + context 'when no ip is passed' do + it { is_expected.to eq %w[public one two registered] } end - context "when ip is passed" do - context "and it is in range" do + context 'when ip is passed' do + context 'and it is in range' do let(:args) { { remote_ip: '10.0.1.12' } } it { is_expected.to eq ['public', 'one', 'two', 'registered', 'on-campus'] } end - context "and it is out of range" do + context 'and it is out of range' do let(:args) { { remote_ip: '10.0.4.12' } } - it { is_expected.to eq ['public', 'one', 'two', 'registered'] } + it { is_expected.to eq %w[public one two registered] } end end end diff --git a/hydra-access-controls/spec/unit/permission_spec.rb b/hydra-access-controls/spec/unit/permission_spec.rb index 73280a14a..0ab2f962c 100644 --- a/hydra-access-controls/spec/unit/permission_spec.rb +++ b/hydra-access-controls/spec/unit/permission_spec.rb @@ -1,61 +1,62 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::AccessControls::Permission do - - describe "an initialized instance" do + describe 'an initialized instance' do let(:permission) { described_class.new(type: 'person', name: 'bob', access: 'read') } - it "should set predicates" do + it 'should set predicates' do expect(permission.agent.first.rdf_subject).to eq ::RDF::URI.new('http://projecthydra.org/ns/auth/person#bob') expect(permission.mode.first.rdf_subject).to eq ACL.Read end - describe "#to_hash" do + describe '#to_hash' do subject { permission.to_hash } it { should eq(type: 'person', name: 'bob', access: 'read') } end - describe "#agent_name" do + describe '#agent_name' do subject { permission.agent_name } it { should eq 'bob' } end - describe "#access" do + describe '#access' do subject { permission.access } it { should eq 'read' } end - describe "#type" do + describe '#type' do subject { permission.type } it { should eq 'person' } end end - describe "equality comparison" do + describe 'equality comparison' do let(:perm1) { described_class.new(type: 'person', name: 'bob', access: 'read') } let(:perm2) { described_class.new(type: 'person', name: 'bob', access: 'read') } let(:perm3) { described_class.new(type: 'person', name: 'jane', access: 'read') } - it "should be equal if all values are equal" do + it 'should be equal if all values are equal' do expect(perm1).to eq perm2 end - it "should be unequal if some values are unequal" do + it 'should be unequal if some values are unequal' do expect(perm1).to_not eq perm3 expect(perm2).to_not eq perm3 end end - describe "URI escaping" do + describe 'URI escaping' do let(:permission) { described_class.new(type: 'person', name: 'john doe', access: 'read') } let(:permission2) { described_class.new(type: 'group', name: 'hydra devs', access: 'read') } - it "should escape agent when building" do + it 'should escape agent when building' do expect(permission.agent.first.rdf_subject.to_s).to eq 'http://projecthydra.org/ns/auth/person#john%20doe' expect(permission2.agent.first.rdf_subject.to_s).to eq 'http://projecthydra.org/ns/auth/group#hydra%20devs' end - it "should unescape agent when parsing" do + it 'should unescape agent when parsing' do expect(permission.agent_name).to eq 'john doe' expect(permission2.agent_name).to eq 'hydra devs' end @@ -64,7 +65,7 @@ let(:permission) { described_class.new(type: 'person', name: user, access: 'read') } let(:user) { FactoryBot.build(:archivist, email: 'archivist1@example.com') } - it "uses string and escape agent when building" do + it 'uses string and escape agent when building' do expect(permission.agent.first.rdf_subject.to_s).to eq 'http://projecthydra.org/ns/auth/person#archivist1@example.com' end end diff --git a/hydra-access-controls/spec/unit/permissions_spec.rb b/hydra-access-controls/spec/unit/permissions_spec.rb index 0003524c5..da3db7b73 100644 --- a/hydra-access-controls/spec/unit/permissions_spec.rb +++ b/hydra-access-controls/spec/unit/permissions_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::AccessControls::Permissions do @@ -10,245 +12,246 @@ class Foo < ActiveFedora::Base let(:model) { Foo.new } subject { model } - describe "#permisisons" do + describe '#permisisons' do subject { model.permissions } it { is_expected.to be_kind_of Hydra::AccessControl::CollectionRelationship } end - it "has a set of permissions" do - subject.read_groups=['group1', 'group2'] - subject.edit_users=['user1'] - subject.read_users=['user2', 'user3'] + it 'has a set of permissions' do + subject.read_groups = %w[group1 group2] + subject.edit_users = ['user1'] + subject.read_users = %w[user2 user3] expect(subject.permissions.to_a).to all(be_kind_of(Hydra::AccessControls::Permission)) - expect(subject.permissions.map(&:to_hash)).to match_array [{type: "group", access: "read", name: "group1"}, - { type: "group", access: "read", name: "group2" }, - { type: "person", access: "read", name: "user2" }, - { type: "person", access: "read", name: "user3" }, - { type: "person", access: "edit", name: "user1" }] + expect(subject.permissions.map(&:to_hash)).to match_array [{ type: 'group', access: 'read', name: 'group1' }, + { type: 'group', access: 'read', name: 'group2' }, + { type: 'person', access: 'read', name: 'user2' }, + { type: 'person', access: 'read', name: 'user3' }, + { type: 'person', access: 'edit', name: 'user1' }] end - describe "building a new permission" do - it "sets the accessTo association" do + describe 'building a new permission' do + it 'sets the accessTo association' do subject.save! perm = subject.permissions.build(name: 'user1', type: 'person', access: 'read') expect(perm.access_to_id).to eq subject.id end - it "autosaves the permissions" do + it 'autosaves the permissions' do subject.permissions.build(name: 'user1', type: 'person', access: 'read') subject.save! foo = Foo.find(subject.id) expect(foo.permissions) - .to contain_exactly(have_attributes(access: 'read', + .to contain_exactly(have_attributes(access: 'read', access_to_id: subject.id, - agent_name: 'user1', - type: 'person')) + agent_name: 'user1', + type: 'person')) end end - describe "updating permissions" do - describe "with nested attributes" do - let(:original_permissions) { [{ type: "person", access: "edit", name: "jcoyne" }] } + describe 'updating permissions' do + describe 'with nested attributes' do + let(:original_permissions) { [{ type: 'person', access: 'edit', name: 'jcoyne' }] } before do subject.save! subject.permissions_attributes = original_permissions end - context "with ids" do + context 'with ids' do let(:permission_id) { ActiveFedora::Base.uri_to_id(subject.permissions.last.rdf_subject.to_s) } - it "clears the cache" do - expect { - subject.permissions_attributes = [{ id: permission_id, type: "person", access: "read", name: "jcoyne" }] - }.to change { subject.permissions.map(&:to_hash) } + it 'clears the cache' do + expect do + subject.permissions_attributes = [{ id: permission_id, type: 'person', access: 'read', name: 'jcoyne' }] + end.to change { subject.permissions.map(&:to_hash) } .from(original_permissions) - .to([{ type: "person", access: "read", name: "jcoyne" }]) + .to([{ type: 'person', access: 'read', name: 'jcoyne' }]) end end - context "when a hash is passed" do + context 'when a hash is passed' do before do - subject.permissions_attributes = {'0' => { type: "group", access:"read", name:"group1" }, - '1' => { type: 'person', access: 'edit', name: 'user2' }} + subject.permissions_attributes = { '0' => { type: 'group', access: 'read', name: 'group1' }, + '1' => { type: 'person', access: 'edit', name: 'user2' } } end - it "handles a hash" do + it 'handles a hash' do expect(subject.permissions.size).to eq 3 expect(subject.permissions.to_a).to all(be_a(Hydra::AccessControls::Permission)) expect(subject.permissions.map(&:to_hash)).to match_array [ - { type: "person", access: "edit", name: "jcoyne" }, - { type: "group", access: "read", name: "group1" }, - { type: "person", access: "edit", name: "user2" }] + { type: 'person', access: 'edit', name: 'jcoyne' }, + { type: 'group', access: 'read', name: 'group1' }, + { type: 'person', access: 'edit', name: 'user2' } + ] end end - it "creates new group permissions" do - subject.permissions_attributes = [{ type: "group", access: "read", name: "group1" }] + it 'creates new group permissions' do + subject.permissions_attributes = [{ type: 'group', access: 'read', name: 'group1' }] expect(subject.permissions.size).to eq 2 expect(subject.permissions.to_a).to all(be_a(Hydra::AccessControls::Permission)) - expect(subject.permissions[0].to_hash).to eq(type: "person", access: "edit", name: "jcoyne") - expect(subject.permissions[1].to_hash).to eq(type: "group", access: "read", name: "group1") + expect(subject.permissions[0].to_hash).to eq(type: 'person', access: 'edit', name: 'jcoyne') + expect(subject.permissions[1].to_hash).to eq(type: 'group', access: 'read', name: 'group1') end - it "creates new user permissions" do - subject.permissions_attributes = [{ type: "person", access: "read", name: "user1" }] + it 'creates new user permissions' do + subject.permissions_attributes = [{ type: 'person', access: 'read', name: 'user1' }] expect(subject.permissions.size).to eq 2 expect(subject.permissions.to_a).to all(be_a(Hydra::AccessControls::Permission)) - expect(subject.permissions[0].to_hash).to eq(type: "person", access: "edit", name: "jcoyne") - expect(subject.permissions[1].to_hash).to eq(type: "person", access: "read", name: "user1") + expect(subject.permissions[0].to_hash).to eq(type: 'person', access: 'edit', name: 'jcoyne') + expect(subject.permissions[1].to_hash).to eq(type: 'person', access: 'read', name: 'user1') end - context "when called multiple times" do + context 'when called multiple times' do it "doesn't replace existing groups" do - subject.permissions_attributes = [{ type: "group", access: "read", name: "group1" }] - subject.permissions_attributes = [{ type: "group", access: "read", name: "group2" }] + subject.permissions_attributes = [{ type: 'group', access: 'read', name: 'group1' }] + subject.permissions_attributes = [{ type: 'group', access: 'read', name: 'group2' }] expect(subject.permissions.size).to eq 3 expect(subject.permissions.to_a).to all(be_a(Hydra::AccessControls::Permission)) - expect(subject.permissions[0].to_hash).to eq(type: "person", access: "edit", name: "jcoyne") - expect(subject.permissions[1].to_hash).to eq(type: "group", access: "read", name: "group1") - expect(subject.permissions[2].to_hash).to eq(type: "group", access: "read", name: "group2") + expect(subject.permissions[0].to_hash).to eq(type: 'person', access: 'edit', name: 'jcoyne') + expect(subject.permissions[1].to_hash).to eq(type: 'group', access: 'read', name: 'group1') + expect(subject.permissions[2].to_hash).to eq(type: 'group', access: 'read', name: 'group2') end it "doesn't replace existing users" do - subject.permissions_attributes = [{ type: "person", access: "read", name: "user1" }] - subject.permissions_attributes = [{ type: "person", access: "read", name: "user2" }] + subject.permissions_attributes = [{ type: 'person', access: 'read', name: 'user1' }] + subject.permissions_attributes = [{ type: 'person', access: 'read', name: 'user2' }] expect(subject.permissions.size).to eq 3 expect(subject.permissions.to_a).to all(be_a(Hydra::AccessControls::Permission)) - expect(subject.permissions[0].to_hash).to eq(type: "person", access: "edit", name: "jcoyne") - expect(subject.permissions[1].to_hash).to eq(type: "person", access: "read", name: "user1") - expect(subject.permissions[2].to_hash).to eq(type: "person", access: "read", name: "user2") + expect(subject.permissions[0].to_hash).to eq(type: 'person', access: 'edit', name: 'jcoyne') + expect(subject.permissions[1].to_hash).to eq(type: 'person', access: 'read', name: 'user1') + expect(subject.permissions[2].to_hash).to eq(type: 'person', access: 'read', name: 'user2') end - it "updates permissions on existing users" do - subject.update permissions_attributes: [{ type: "person", access: "read", name: "user1" }] - subject.update permissions_attributes: [{ type: "person", access: "edit", name: "user1" }] + it 'updates permissions on existing users' do + subject.update permissions_attributes: [{ type: 'person', access: 'read', name: 'user1' }] + subject.update permissions_attributes: [{ type: 'person', access: 'edit', name: 'user1' }] expect(subject.permissions.size).to eq 2 expect(subject.permissions.to_a).to all(be_a(Hydra::AccessControls::Permission)) - expect(subject.permissions[0].to_hash).to eq(type: "person", access: "edit", name: "jcoyne") - expect(subject.permissions[1].to_hash).to eq(type: "person", access: "edit", name: "user1") + expect(subject.permissions[0].to_hash).to eq(type: 'person', access: 'edit', name: 'jcoyne') + expect(subject.permissions[1].to_hash).to eq(type: 'person', access: 'edit', name: 'user1') end - it "updates permissions on existing groups" do - subject.update permissions_attributes: [{ type: "group", access: "read", name: "group1" }] - subject.update permissions_attributes: [{ type: "group", access: "edit", name: "group1" }] + it 'updates permissions on existing groups' do + subject.update permissions_attributes: [{ type: 'group', access: 'read', name: 'group1' }] + subject.update permissions_attributes: [{ type: 'group', access: 'edit', name: 'group1' }] expect(subject.permissions.map(&:to_hash)).to match_array [ - { type: "group", access: "edit", name: "group1" }, - { type: "person", access: "edit", name: "jcoyne" }] + { type: 'group', access: 'edit', name: 'group1' }, + { type: 'person', access: 'edit', name: 'jcoyne' } + ] end end - context "when the destroy flag is set" do + context 'when the destroy flag is set' do let(:reloaded) { subject.reload.permissions.map(&:to_hash) } let(:permissions_id) { ActiveFedora::Base.uri_to_id(subject.permissions.last.rdf_subject.to_s) } - context "to a truthy value" do - context "when updating users" do + context 'to a truthy value' do + context 'when updating users' do before do - subject.update permissions_attributes: [{ type: "person", access: "read", name: "user1" }] - subject.update permissions_attributes: [{ id: permissions_id, type: "person", access: "edit", name: "user1", _destroy: 'true' }] + subject.update permissions_attributes: [{ type: 'person', access: 'read', name: 'user1' }] + subject.update permissions_attributes: [{ id: permissions_id, type: 'person', access: 'edit', name: 'user1', _destroy: 'true' }] end - it "removes permissions on existing users" do + it 'removes permissions on existing users' do indexed_result = ActiveFedora::SolrService.query("id:#{subject.id}").first['edit_access_person_ssim'] expect(indexed_result).to eq ['jcoyne'] - expect(subject.permissions.map(&:to_hash)).to eq [{ name: "jcoyne", type: "person", access: "edit" }] - expect(reloaded).to eq [{ name: "jcoyne", type: "person", access: "edit" }] + expect(subject.permissions.map(&:to_hash)).to eq [{ name: 'jcoyne', type: 'person', access: 'edit' }] + expect(reloaded).to eq [{ name: 'jcoyne', type: 'person', access: 'edit' }] end end - context "when updating groups" do + context 'when updating groups' do before do - subject.update permissions_attributes: [{ type: "group", access: "read", name: "group1" }] - subject.update permissions_attributes: [{ id: permissions_id, type: "group", access: "edit", name: "group1", _destroy: '1' }] + subject.update permissions_attributes: [{ type: 'group', access: 'read', name: 'group1' }] + subject.update permissions_attributes: [{ id: permissions_id, type: 'group', access: 'edit', name: 'group1', _destroy: '1' }] end - it "removes permissions on existing groups" do - #See what actually gets stored in solr + it 'removes permissions on existing groups' do + # See what actually gets stored in solr indexed_result = ActiveFedora::SolrService.query("id:#{subject.id}").first['edit_access_group_ssim'] expect(indexed_result).to be_nil - expect(reloaded).to eq [{ type: "person", access: "edit", name: "jcoyne" }] + expect(reloaded).to eq [{ type: 'person', access: 'edit', name: 'jcoyne' }] end end - context "when destroy and update are simultaneously set for the same id" do + context 'when destroy and update are simultaneously set for the same id' do let(:simultaneous) do [ - { id: permissions_id, type: "group", access: "read", name: "group1", _destroy: '1' }, - { id: permissions_id, type: "group", access: "read", name: "group1", } + { id: permissions_id, type: 'group', access: 'read', name: 'group1', _destroy: '1' }, + { id: permissions_id, type: 'group', access: 'read', name: 'group1' } ] end before do - subject.update permissions_attributes: [{ type: "group", access: "read", name: "group1" }] + subject.update permissions_attributes: [{ type: 'group', access: 'read', name: 'group1' }] subject.update permissions_attributes: simultaneous end - it "leaves the permissions unchanged" do - expect(reloaded).to contain_exactly({name: "jcoyne", type: "person", access: "edit"}, {name: "group1", type: "group", access: "read"}) + it 'leaves the permissions unchanged' do + expect(reloaded).to contain_exactly({ name: 'jcoyne', type: 'person', access: 'edit' }, name: 'group1', type: 'group', access: 'read') end end - context "when destroy is present without an id" do + context 'when destroy is present without an id' do let(:missing_id) do - [ { type: "group", access: "read", name: "group1", _destroy: '1' } ] + [{ type: 'group', access: 'read', name: 'group1', _destroy: '1' }] end before do subject.update permissions_attributes: missing_id end - it "leaves the permissions unchanged" do - expect(reloaded).to contain_exactly({name: "jcoyne", type: "person", access: "edit"}) + it 'leaves the permissions unchanged' do + expect(reloaded).to contain_exactly(name: 'jcoyne', type: 'person', access: 'edit') end end - context "when updating multiple different permissions at the same time" do + context 'when updating multiple different permissions at the same time' do before do - subject.update permissions_attributes: [{ type: "group", access: "read", name: "group1" }] + subject.update permissions_attributes: [{ type: 'group', access: 'read', name: 'group1' }] subject.update permissions_attributes: [ - { id: permissions_id, type: "group", access: "read", name: "group1", _destroy: '1' }, - { type: "group", access: "edit", name: "group2" }, - { type: "person", access: "read", name: "joebob" } + { id: permissions_id, type: 'group', access: 'read', name: 'group1', _destroy: '1' }, + { type: 'group', access: 'edit', name: 'group2' }, + { type: 'person', access: 'read', name: 'joebob' } ] end - it "removes permissions on existing groups and updates the others" do + it 'removes permissions on existing groups and updates the others' do expect(reloaded).to contain_exactly( - {name: "jcoyne", type: "person", access: "edit"}, - {name: "group2", type: "group", access: "edit"}, - {name: "joebob", type: "person", access: "read"} + { name: 'jcoyne', type: 'person', access: 'edit' }, + { name: 'group2', type: 'group', access: 'edit' }, + name: 'joebob', type: 'person', access: 'read' ) end end end - context "to a falsy value" do - + context 'to a falsy value' do it "doesn't remove the record" do - subject.update permissions_attributes: [{ type: "group", access: "read", name: "group1" }] - subject.update permissions_attributes: [{ id: permissions_id, type: "group", access: "edit", name: "group1", _destroy: '0' }] - expect(reloaded).to match_array [{ type: "group", access: "edit", name: "group1" }, - { type: "person", access: "edit", name: "jcoyne" }] + subject.update permissions_attributes: [{ type: 'group', access: 'read', name: 'group1' }] + subject.update permissions_attributes: [{ id: permissions_id, type: 'group', access: 'edit', name: 'group1', _destroy: '0' }] + expect(reloaded).to match_array [{ type: 'group', access: 'edit', name: 'group1' }, + { type: 'person', access: 'edit', name: 'jcoyne' }] end end end end - describe "with the setter" do + describe 'with the setter' do before do subject.permissions = [ - Hydra::AccessControls::Permission.new(type: "group", access: "edit", name: "group1"), - Hydra::AccessControls::Permission.new(type: "person", access: "edit", name: "jcoyne")] + Hydra::AccessControls::Permission.new(type: 'group', access: 'edit', name: 'group1'), + Hydra::AccessControls::Permission.new(type: 'person', access: 'edit', name: 'jcoyne') + ] subject.save! end - it "sets the permissions" do + it 'sets the permissions' do expect(subject.edit_users).to eq ['jcoyne'] expect(subject.edit_groups).to eq ['group1'] subject.permissions = [] expect(subject.edit_users).to be_empty expect(subject.edit_groups).to be_empty end - end end - context "with rightsMetadata" do + context 'with rightsMetadata' do before do subject.permissions.build(type: 'person', access: 'read', name: 'person1') subject.permissions.build(type: 'person', access: 'discover', name: 'person2') @@ -257,46 +260,47 @@ class Foo < ActiveFedora::Base subject.permissions.build(type: 'group', access: 'edit', name: 'group-8') end - it "has read groups accessor" do + it 'has read groups accessor' do expect(subject.read_groups).to eq ['group-6', 'group-7'] end - it "has read groups string accessor" do + it 'has read groups string accessor' do expect(subject.read_groups_string).to eq 'group-6, group-7' end - it "has read groups string writer" do + it 'has read groups string writer' do subject.read_groups_string = 'umg/up.dlt.staff, group-3' expect(subject.read_groups).to eq ['umg/up.dlt.staff', 'group-3'] expect(subject.edit_groups).to eq ['group-8'] expect(subject.read_users).to eq ['person1'] end - it "only revoke eligible groups" do + it 'only revoke eligible groups' do subject.set_read_groups(['group-2', 'group-3'], ['group-6']) # 'group-7' is not eligible to be revoked expect(subject.permissions.map(&:to_hash)).to match_array([ - { name: 'group-2', type: 'group', access: 'read' }, - { name: 'group-3', type: 'group', access: 'read' }, - { name: 'group-7', type: 'group', access: 'read' }, - { name: 'group-8', type: 'group', access: 'edit' }, - { name: 'person1', type: 'person', access: 'read' }, - { name: 'person2', type: 'person', access: 'discover' }]) + { name: 'group-2', type: 'group', access: 'read' }, + { name: 'group-3', type: 'group', access: 'read' }, + { name: 'group-7', type: 'group', access: 'read' }, + { name: 'group-8', type: 'group', access: 'edit' }, + { name: 'person1', type: 'person', access: 'read' }, + { name: 'person2', type: 'person', access: 'discover' } + ]) end end - context "when the original object is destroyed" do + context 'when the original object is destroyed' do before do subject.save! subject.permissions.create(type: 'person', access: 'read', name: 'person1') subject.save! end - it "destroys the associated permissions" do + it 'destroys the associated permissions' do expect { subject.destroy }.to change { Hydra::AccessControls::Permission.count }.by(-1) end - it "does not raise an exception if permissions do not exist" do + it 'does not raise an exception if permissions do not exist' do expect { Foo.new.destroy }.not_to raise_error(NoMethodError) end end diff --git a/hydra-access-controls/spec/unit/policy_aware_ability_spec.rb b/hydra-access-controls/spec/unit/policy_aware_ability_spec.rb index 8e11c2790..5d125280a 100644 --- a/hydra-access-controls/spec/unit/policy_aware_ability_spec.rb +++ b/hydra-access-controls/spec/unit/policy_aware_ability_spec.rb @@ -1,14 +1,16 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::PolicyAwareAbility do before do - allow(Hydra.config.permissions).to receive(:inheritable).and_return({ - :discover => {:group =>"inheritable_discover_access_group_ssim", :individual=>"inheritable_discover_access_person_ssim"}, - :read => {:group =>"inheritable_read_access_group_ssim", :individual=>"inheritable_read_access_person_ssim"}, - :edit => {:group =>"inheritable_edit_access_group_ssim", :individual=>"inheritable_edit_access_person_ssim"}, - :owner => "inheritable_depositor_ssim", - :embargo_release_date => "inheritable_embargo_release_date_dtsi" - }) + allow(Hydra.config.permissions).to receive(:inheritable).and_return( + discover: { group: 'inheritable_discover_access_group_ssim', individual: 'inheritable_discover_access_person_ssim' }, + read: { group: 'inheritable_read_access_group_ssim', individual: 'inheritable_read_access_person_ssim' }, + edit: { group: 'inheritable_edit_access_group_ssim', individual: 'inheritable_edit_access_person_ssim' }, + owner: 'inheritable_depositor_ssim', + embargo_release_date: 'inheritable_embargo_release_date_dtsi' + ) end before do @@ -21,11 +23,11 @@ class PolicyAwareClass Hydra::AdminPolicy.create do |p| # Set the inheritable permissions p.default_permissions.build [ - { type: "group", access: "read", name: "africana-faculty" }, - { type: "group", access: "edit", name: "cool_kids" }, - { type: "group", access: "edit", name: "in_crowd" }, - { type: "person", access: "read", name: "nero" }, - { type: "person", access: "edit", name: "julius_caesar" } + { type: 'group', access: 'read', name: 'africana-faculty' }, + { type: 'group', access: 'edit', name: 'cool_kids' }, + { type: 'group', access: 'edit', name: 'in_crowd' }, + { type: 'person', access: 'read', name: 'nero' }, + { type: 'person', access: 'edit', name: 'julius_caesar' } ] end end @@ -35,18 +37,18 @@ class PolicyAwareClass Object.send(:remove_const, :PolicyAwareClass) end - let(:instance) { PolicyAwareClass.new( User.new ) } + let(:instance) { PolicyAwareClass.new(User.new) } - describe "policy_id_for" do + describe 'policy_id_for' do let(:policy2) do Hydra::AdminPolicy.create do |p| # Set the inheritable permissions p.default_permissions.build [ - { type: "group", access: "read", name: "untenured-faculty" }, - { type: "group", access: "edit", name: "awesome_kids" }, - { type: "group", access: "edit", name: "bad_crowd" }, - { type: "person", access: "read", name: "constantine" }, - { type: "person", access: "edit", name: "brutus" } + { type: 'group', access: 'read', name: 'untenured-faculty' }, + { type: 'group', access: 'edit', name: 'awesome_kids' }, + { type: 'group', access: 'edit', name: 'bad_crowd' }, + { type: 'person', access: 'read', name: 'constantine' }, + { type: 'person', access: 'edit', name: 'brutus' } ] end end @@ -60,128 +62,128 @@ class PolicyAwareClass end end - describe "policy_permissions_doc" do + describe 'policy_permissions_doc' do it "retrieves the permissions doc for the current object's policy and store for re-use" do - expect(instance).to receive(:get_permissions_solr_response_for_doc_id).with(policy.id).once.and_return("mock solr doc") - expect(instance.policy_permissions_doc(policy.id)).to eq "mock solr doc" - expect(instance.policy_permissions_doc(policy.id)).to eq "mock solr doc" - expect(instance.policy_permissions_doc(policy.id)).to eq "mock solr doc" + expect(instance).to receive(:get_permissions_solr_response_for_doc_id).with(policy.id).once.and_return('mock solr doc') + expect(instance.policy_permissions_doc(policy.id)).to eq 'mock solr doc' + expect(instance.policy_permissions_doc(policy.id)).to eq 'mock solr doc' + expect(instance.policy_permissions_doc(policy.id)).to eq 'mock solr doc' end end - describe "test_edit_from_policy" do - context "public user" do - it "returns false" do - allow(instance).to receive(:user_groups).and_return(["public"]) + describe 'test_edit_from_policy' do + context 'public user' do + it 'returns false' do + allow(instance).to receive(:user_groups).and_return(['public']) expect(instance.test_edit_from_policy(asset.id)).to be false end end - context "registered user" do - it "returns false" do - #expect(instance.user_groups).to include("registered") + context 'registered user' do + it 'returns false' do + # expect(instance.user_groups).to include("registered") expect(instance.test_edit_from_policy(asset.id)).to be false end end - context "user with policy read access only" do - it "returns false" do - allow(instance.current_user).to receive(:user_key).and_return("nero") + context 'user with policy read access only' do + it 'returns false' do + allow(instance.current_user).to receive(:user_key).and_return('nero') expect(instance.test_edit_from_policy(asset.id)).to be false end end - context "user with policy edit access" do - it "returns true" do - allow(instance.current_user).to receive(:user_key).and_return("julius_caesar") + context 'user with policy edit access' do + it 'returns true' do + allow(instance.current_user).to receive(:user_key).and_return('julius_caesar') expect(instance.test_edit_from_policy(asset.id)).to be true end end - context "user in group with policy read access" do - it "returns false" do - allow(instance).to receive(:user_groups).and_return(["africana-faculty"]) + context 'user in group with policy read access' do + it 'returns false' do + allow(instance).to receive(:user_groups).and_return(['africana-faculty']) expect(instance.test_edit_from_policy(asset.id)).to be false end end - context "user in group with policy edit access" do - it "returns true" do - allow(instance).to receive(:user_groups).and_return(["cool_kids"]) + context 'user in group with policy edit access' do + it 'returns true' do + allow(instance).to receive(:user_groups).and_return(['cool_kids']) expect(instance.test_edit_from_policy(asset.id)).to be true end end end - describe "test_read_from_policy" do - context "public user" do - it "returns false" do - allow(instance).to receive(:user_groups).and_return(["public"]) + describe 'test_read_from_policy' do + context 'public user' do + it 'returns false' do + allow(instance).to receive(:user_groups).and_return(['public']) expect(instance.test_read_from_policy(asset.id)).to be false end end - context "registered user" do - it "returns false" do + context 'registered user' do + it 'returns false' do expect(instance.test_read_from_policy(asset.id)).to be false end end - context "user with policy read access only" do - it "returns false" do - allow(instance.current_user).to receive(:user_key).and_return("nero") + context 'user with policy read access only' do + it 'returns false' do + allow(instance.current_user).to receive(:user_key).and_return('nero') expect(instance.test_read_from_policy(asset.id)).to be true end end - context "user with policy edit access" do - it "returns true" do - allow(instance.current_user).to receive(:user_key).and_return("julius_caesar") + context 'user with policy edit access' do + it 'returns true' do + allow(instance.current_user).to receive(:user_key).and_return('julius_caesar') expect(instance.test_read_from_policy(asset.id)).to be true end end - context "user in group with policy read access" do - it "returns false" do - allow(instance).to receive(:user_groups).and_return(["africana-faculty"]) + context 'user in group with policy read access' do + it 'returns false' do + allow(instance).to receive(:user_groups).and_return(['africana-faculty']) expect(instance.test_read_from_policy(asset.id)).to be true end end - context "user in group with policy edit access" do - it "returns true" do - allow(instance).to receive(:user_groups).and_return(["cool_kids"]) + context 'user in group with policy edit access' do + it 'returns true' do + allow(instance).to receive(:user_groups).and_return(['cool_kids']) expect(instance.test_read_from_policy(asset.id)).to be true end end end - describe "edit_groups_from_policy" do + describe 'edit_groups_from_policy' do subject { instance.edit_groups_from_policy(policy.id) } - it "retrieves the list of groups with edit access from the policy" do - expect(subject).to match_array ["cool_kids", "in_crowd"] + it 'retrieves the list of groups with edit access from the policy' do + expect(subject).to match_array %w[cool_kids in_crowd] end end - describe "edit_persons_from_policy" do + describe 'edit_persons_from_policy' do subject do instance.edit_users_from_policy(policy.id) end - it "retrieves the list of individuals with edit access from the policy" do - expect(subject).to eq ["julius_caesar"] + it 'retrieves the list of individuals with edit access from the policy' do + expect(subject).to eq ['julius_caesar'] end end - describe "read_groups_from_policy" do + describe 'read_groups_from_policy' do subject { instance.read_groups_from_policy(policy.id) } - it "retrieves the list of groups with read access from the policy" do - expect(subject).to match_array ["cool_kids", "in_crowd", "africana-faculty"] + it 'retrieves the list of groups with read access from the policy' do + expect(subject).to match_array ['cool_kids', 'in_crowd', 'africana-faculty'] end end - describe "read_users_from_policy" do + describe 'read_users_from_policy' do subject { instance.read_users_from_policy(policy.id) } - it "retrieves the list of individuals with read access from the policy" do - expect(subject).to eq ["julius_caesar", "nero"] + it 'retrieves the list of individuals with read access from the policy' do + expect(subject).to eq %w[julius_caesar nero] end end end diff --git a/hydra-access-controls/spec/unit/policy_aware_access_controls_enforcement_spec.rb b/hydra-access-controls/spec/unit/policy_aware_access_controls_enforcement_spec.rb index c4fe553dc..64b7a51ed 100644 --- a/hydra-access-controls/spec/unit/policy_aware_access_controls_enforcement_spec.rb +++ b/hydra-access-controls/spec/unit/policy_aware_access_controls_enforcement_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::PolicyAwareAccessControlsEnforcement do @@ -14,80 +16,76 @@ def initialize(current_ability) @current_ability = current_ability end - def current_ability - @current_ability - end + attr_reader :current_ability - def session - end + def session; end delegate :logger, to: :Rails end @sample_policies = [] # user discover - policy1 = Hydra::AdminPolicy.create(id: "test-policy1") - policy1.default_permissions.create(:type=>"person", :access=>"discover", :name=>"sara_student") + policy1 = Hydra::AdminPolicy.create(id: 'test-policy1') + policy1.default_permissions.create(type: 'person', access: 'discover', name: 'sara_student') policy1.save! @sample_policies << policy1 # user read - policy2 = Hydra::AdminPolicy.create(id: "test-policy2") - policy2.default_permissions.create(:type=>"person", :access=>"read", :name=>"sara_student") + policy2 = Hydra::AdminPolicy.create(id: 'test-policy2') + policy2.default_permissions.create(type: 'person', access: 'read', name: 'sara_student') policy2.save! @sample_policies << policy2 # user edit - policy3 = Hydra::AdminPolicy.create(id: "test-policy3") - policy3.default_permissions.create(:type=>"person", :access=>"edit", :name=>"sara_student") + policy3 = Hydra::AdminPolicy.create(id: 'test-policy3') + policy3.default_permissions.create(type: 'person', access: 'edit', name: 'sara_student') policy3.save! @sample_policies << policy3 - # group discover - policy4 = Hydra::AdminPolicy.create(id: "test-policy4") - policy4.default_permissions.create(:type=>"group", :access=>"discover", :name=>"africana-104-students") + policy4 = Hydra::AdminPolicy.create(id: 'test-policy4') + policy4.default_permissions.create(type: 'group', access: 'discover', name: 'africana-104-students') policy4.save! @sample_policies << policy4 # group read - policy5 = Hydra::AdminPolicy.create(id: "test-policy5") - policy5.default_permissions.create(:type=>"group", :access=>"read", :name=>"africana-104-students") + policy5 = Hydra::AdminPolicy.create(id: 'test-policy5') + policy5.default_permissions.create(type: 'group', access: 'read', name: 'africana-104-students') policy5.save! @sample_policies << policy5 # group edit - policy6 = Hydra::AdminPolicy.create(id: "test-policy6") - policy6.default_permissions.create(:type=>"group", :access=>"edit", :name=>"africana-104-students") + policy6 = Hydra::AdminPolicy.create(id: 'test-policy6') + policy6.default_permissions.create(type: 'group', access: 'edit', name: 'africana-104-students') policy6.save! @sample_policies << policy6 # public discover - policy7 = Hydra::AdminPolicy.create(id: "test-policy7") - policy7.default_permissions.create(:type=>"group", :access=>"discover", :name=>"public") + policy7 = Hydra::AdminPolicy.create(id: 'test-policy7') + policy7.default_permissions.create(type: 'group', access: 'discover', name: 'public') policy7.save! @sample_policies << policy7 # public read - policy8 = Hydra::AdminPolicy.create(id: "test-policy8") - policy8.default_permissions.create(:type=>"group", :access=>"read", :name=>"public") + policy8 = Hydra::AdminPolicy.create(id: 'test-policy8') + policy8.default_permissions.create(type: 'group', access: 'read', name: 'public') policy8.save! @sample_policies << policy8 # user discover policies for testing that all are applied when over 10 are applicable (9..11).each do |i| policy = Hydra::AdminPolicy.create(id: "test-policy#{i}") - policy.default_permissions.create(:type=>"person", :access=>"discover", :name=>"sara_student") + policy.default_permissions.create(type: 'person', access: 'discover', name: 'sara_student') policy.save! @sample_policies << policy end # no access - policy_no_access = Hydra::AdminPolicy.new(id: "test-policy_no_access") + policy_no_access = Hydra::AdminPolicy.new(id: 'test-policy_no_access') policy_no_access.save! @sample_policies << policy_no_access - @policies_with_access = @sample_policies.select { |p| p.id != policy_no_access.id } + @policies_with_access = @sample_policies.reject { |p| p.id == policy_no_access.id } end let(:current_ability) { Ability.new(user) } @@ -98,57 +96,57 @@ def session @solr_parameters = {} end - describe "policies_with_access" do - context "Authenticated user" do + describe 'policies_with_access' do + context 'Authenticated user' do before do - allow(user).to receive(:groups).and_return(["student", "africana-104-students"]) + allow(user).to receive(:groups).and_return(['student', 'africana-104-students']) end - it "should return the policies that provide discover permissions" do - @policies_with_access.map {|p| p.id }.each do |p| + it 'should return the policies that provide discover permissions' do + @policies_with_access.map(&:id).each do |p| expect(subject.policies_with_access).to include(p) end - expect(subject.policies_with_access).to_not include("test-policy_no_access") + expect(subject.policies_with_access).to_not include('test-policy_no_access') end - it "should allow you to configure which model to use for policies" do + it 'should allow you to configure which model to use for policies' do allow(Hydra.config.permissions).to receive(:policy_class).and_return(ModsAsset) expect(ModsAsset).to receive(:search_with_conditions).and_return([]) subject.policies_with_access end end - context "Anonymous user" do + context 'Anonymous user' do let(:user) { nil } - it "should return the policies that provide discover permissions" do - expect(subject.policies_with_access).to match_array ["test-policy7", "test-policy8"] + it 'should return the policies that provide discover permissions' do + expect(subject.policies_with_access).to match_array ['test-policy7', 'test-policy8'] end end end - describe "apply_gated_discovery" do + describe 'apply_gated_discovery' do let(:governed_field) { ActiveFedora.index_field_mapper.solr_name('isGovernedBy', :symbol) } - let(:policy_queries) { @solr_parameters[:fq].first.split(" OR ") } + let(:policy_queries) { @solr_parameters[:fq].first.split(' OR ') } before do - allow(user).to receive(:groups).and_return(["student", "africana-104-students"]) + allow(user).to receive(:groups).and_return(['student', 'africana-104-students']) end - context "when policies are included" do + context 'when policies are included' do before { subject.apply_gated_discovery(@solr_parameters) } - - it "builds a query that includes all the policies" do + + it 'builds a query that includes all the policies' do skip if ActiveFedora.version.split('.').first.to_i < 11 (1..11).each do |p| expect(policy_queries).to include(/_query_:\"{!raw f=#{governed_field}}test-policy#{p}\"/) end end end - - context "when policies are not included" do + + context 'when policies are not included' do before do allow(subject).to receive(:policy_clauses).and_return(nil) subject.apply_gated_discovery(@solr_parameters) end - it "does not include any policies in the query" do + it 'does not include any policies in the query' do (1..11).each do |p| expect(policy_queries).not_to include(/_query_:\"{!raw f=#{governed_field}}test-policy#{p}\"/) end @@ -156,26 +154,26 @@ def session end end - describe "apply_policy_role_permissions" do + describe 'apply_policy_role_permissions' do before do allow(user).to receive(:groups).and_return(groups) end - context "when there are slashes in the group names" do - let(:groups) { ["abc/123","cde/567"] } - it "escapes slashes" do + context 'when there are slashes in the group names' do + let(:groups) { ['abc/123', 'cde/567'] } + it 'escapes slashes' do user_access_filters = subject.apply_policy_group_permissions - ["edit","discover","read"].each do |type| + %w[edit discover read].each do |type| expect(user_access_filters).to include("inheritable_#{type}_access_group_ssim\:abc\\\/123") expect(user_access_filters).to include("inheritable_#{type}_access_group_ssim\:cde\\\/567") end end end - context "when there are spaces in the group names" do - let(:groups) { ["abc 123","cd/e 567"] } - it "escapes spaces" do + context 'when there are spaces in the group names' do + let(:groups) { ['abc 123', 'cd/e 567'] } + it 'escapes spaces' do user_access_filters = subject.apply_policy_group_permissions - ["edit","discover","read"].each do |type| + %w[edit discover read].each do |type| expect(user_access_filters).to include("inheritable_#{type}_access_group_ssim\:abc\\ 123") expect(user_access_filters).to include("inheritable_#{type}_access_group_ssim\:cd\\\/e\\ 567") end diff --git a/hydra-access-controls/spec/unit/role_mapper_spec.rb b/hydra-access-controls/spec/unit/role_mapper_spec.rb index a711fdb3d..dfda562c6 100644 --- a/hydra-access-controls/spec/unit/role_mapper_spec.rb +++ b/hydra-access-controls/spec/unit/role_mapper_spec.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + require 'spec_helper' require 'hydra/shared_spec/group_service_interface' RSpec.describe RoleMapper do - it "defines the 4 roles" do - expect(RoleMapper.role_names.sort).to eq %w(admin_policy_object_editor archivist donor patron researcher) + it 'defines the 4 roles' do + expect(RoleMapper.role_names.sort).to eq %w[admin_policy_object_editor archivist donor patron researcher] end - describe "map" do + describe 'map' do subject { described_class.map } - context "when there are no roles defined for the current environment" do + context 'when there are no roles defined for the current environment' do before do described_class.instance_variable_set :@map, nil allow(Rails).to receive(:env).and_return('production') end - it "raises an error" do + it 'raises an error' do expect { subject }.to raise_error RuntimeError, %r{^No roles were found for the production environment in .*config/role_map\.yml$} end end @@ -24,61 +26,61 @@ let(:group_service) { described_class } it_behaves_like 'a Hydra group_service interface' - describe "#whois" do - it "knows who is what" do - expect(RoleMapper.whois('archivist').sort).to eq %w(archivist1@example.com archivist2@example.com leland_himself@example.com) + describe '#whois' do + it 'knows who is what' do + expect(RoleMapper.whois('archivist').sort).to eq %w[archivist1@example.com archivist2@example.com leland_himself@example.com] expect(RoleMapper.whois('salesman')).to be_empty - expect(RoleMapper.whois('admin_policy_object_editor').sort).to eq %w(archivist1@example.com) + expect(RoleMapper.whois('admin_policy_object_editor').sort).to eq %w[archivist1@example.com] end end - describe "fetch_groups" do + describe 'fetch_groups' do let(:user) { instance_double(User, user_key: email, new_record?: false) } subject { RoleMapper.fetch_groups(user: user) } - context "for a user with multiple roles" do + context 'for a user with multiple roles' do let(:email) { 'leland_himself@example.com' } - it { is_expected.to match_array ['archivist', 'donor', 'patron'] } + it { is_expected.to match_array %w[archivist donor patron] } it "doesn't change its response when it's called repeatedly" do - expect(subject).to match_array ['archivist', 'donor', 'patron'] - expect(RoleMapper.fetch_groups(user: user)).to match_array ['archivist', 'donor', 'patron'] + expect(subject).to match_array %w[archivist donor patron] + expect(RoleMapper.fetch_groups(user: user)).to match_array %w[archivist donor patron] end end - context "for a user with a single role" do + context 'for a user with a single role' do let(:email) { 'archivist2@example.com' } it { is_expected.to match_array ['archivist'] } end - context "for a user with no roles" do + context 'for a user with no roles' do let(:email) { 'zeus@olympus.mt' } it { is_expected.to be_empty } end end - describe "roles" do + describe 'roles' do before do allow(Deprecation).to receive(:warn) end - it "is quer[iy]able for roles for a given user" do - expect(RoleMapper.roles('leland_himself@example.com').sort).to eq ['archivist', 'donor', 'patron'] + it 'is quer[iy]able for roles for a given user' do + expect(RoleMapper.roles('leland_himself@example.com').sort).to eq %w[archivist donor patron] expect(RoleMapper.roles('archivist2@example.com')).to eq ['archivist'] end - context "when called with a user instance" do + context 'when called with a user instance' do let(:user) { User.new(email: 'leland_himself@example.com') } before do allow(user).to receive(:new_record?).and_return(false) end it "doesn't change its response when it's called repeatedly" do - expect(RoleMapper.roles(user).sort).to eq ['archivist', 'donor', 'patron'] - expect(RoleMapper.roles(user).sort).to eq ['archivist', 'donor', 'patron'] + expect(RoleMapper.roles(user).sort).to eq %w[archivist donor patron] + expect(RoleMapper.roles(user).sort).to eq %w[archivist donor patron] end end - it "returns an empty array if there are no roles" do + it 'returns an empty array if there are no roles' do expect(RoleMapper.roles('zeus@olympus.mt')).to be_empty end end diff --git a/hydra-access-controls/spec/unit/visibility_spec.rb b/hydra-access-controls/spec/unit/visibility_spec.rb index 07b401f4b..e22e5f3cc 100644 --- a/hydra-access-controls/spec/unit/visibility_spec.rb +++ b/hydra-access-controls/spec/unit/visibility_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::AccessControls::Visibility do - describe "setting visibility" do + describe 'setting visibility' do before do class Foo < ActiveFedora::Base include Hydra::AccessControls::Permissions @@ -12,73 +14,79 @@ class Foo < ActiveFedora::Base subject { Foo.new } - [ Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE, - Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED, - Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC ] - .each do |vis| + [Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE, + Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED, + Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC] + .each do |vis| describe "to #{vis}" do - - before { subject.visibility=vis } + before { subject.visibility = vis } it "should be set to #{vis}" do expect(subject.visibility).to eql vis end - describe "and then to private" do - before { subject.visibility=Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE } - it "should be set to private" do + describe 'and then to private' do + before { subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE } + it 'should be set to private' do expect(subject.visibility).to eql Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE end - it "should have no permissions" do + it 'should have no permissions' do expect(subject.permissions.map(&:to_hash)).to be_empty end end - describe "and then to authenticated" do - before { subject.visibility=Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED } - it "should be set to authenticated" do + describe 'and then to authenticated' do + before { subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED } + it 'should be set to authenticated' do expect(subject.visibility).to eql Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED end - it "should have authenticated permissions only" do + it 'should have authenticated permissions only' do expect(subject.permissions.map(&:to_hash)).to match_array [ - {type: "group", access: "read", name: Hydra::AccessControls::AccessRight::PERMISSION_TEXT_VALUE_AUTHENTICATED } ] + { type: 'group', access: 'read', name: Hydra::AccessControls::AccessRight::PERMISSION_TEXT_VALUE_AUTHENTICATED } + ] end end - describe "and then to public" do - before { subject.visibility=Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC } - it "should be set to public" do + describe 'and then to public' do + before { subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC } + it 'should be set to public' do expect(subject.visibility).to eql Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC end - it "should have public permissions only" do + it 'should have public permissions only' do expect(subject.permissions.map(&:to_hash)).to match_array [ - {type: "group", access: "read", name: Hydra::AccessControls::AccessRight::PERMISSION_TEXT_VALUE_PUBLIC } ] + { type: 'group', access: 'read', name: Hydra::AccessControls::AccessRight::PERMISSION_TEXT_VALUE_PUBLIC } + ] end end end end end - describe "overiding visibility" do + describe 'overiding visibility' do module VisibilityOverride extend ActiveSupport::Concern include Hydra::AccessControls::Permissions - def visibility; super; end - def visibility=(value); super(value); end + def visibility + super + end + + def visibility=(value) + super(value) + end end class MockParent < ActiveFedora::Base include VisibilityOverride end it 'allows for overrides of visibility' do - expect { + expect do MockParent.new(visibility: Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE) - }.to_not raise_error + end.to_not raise_error end end - context "when represented_visibility is overridden" do + context 'when represented_visibility is overridden' do let(:model) { MockObject.new } before do class MockObject < ActiveFedora::Base @@ -88,14 +96,14 @@ def represented_visibility end end - model.read_groups = ['one', 'another'] + model.read_groups = %w[one another] end after do Object.send(:remove_const, :MockObject) end - it "replaces the represented visibility" do + it 'replaces the represented visibility' do model.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC expect(model.read_groups).to contain_exactly 'public', 'another' end diff --git a/hydra-access-controls/spec/unit/with_access_right_spec.rb b/hydra-access-controls/spec/unit/with_access_right_spec.rb index 8a09c24b6..6311757cc 100644 --- a/hydra-access-controls/spec/unit/with_access_right_spec.rb +++ b/hydra-access-controls/spec/unit/with_access_right_spec.rb @@ -1,7 +1,8 @@ -require 'spec_helper' +# frozen_string_literal: true -describe "WithAccessRight" do +require 'spec_helper' +describe 'WithAccessRight' do before do class TestClass < ActiveFedora::Base include Hydra::AccessControls::Permissions @@ -15,55 +16,54 @@ class TestClass < ActiveFedora::Base subject { TestClass.new } - context "not persisted" do - context "when it is public" do - before { subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC} - its(:authenticated_only_access?) { should be false} - its(:private_access?) { should be false} - its(:open_access?) { should be true} - its(:open_access_with_embargo_release_date?) { should be false} + context 'not persisted' do + context 'when it is public' do + before { subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC } + its(:authenticated_only_access?) { should be false } + its(:private_access?) { should be false } + its(:open_access?) { should be true } + its(:open_access_with_embargo_release_date?) { should be false } end - context "when it is private" do + context 'when it is private' do before { subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE } - its(:authenticated_only_access?) { should be false} - its(:private_access?) { should be true} - its(:open_access?) { should be false} - its(:open_access_with_embargo_release_date?) { should be false} + its(:authenticated_only_access?) { should be false } + its(:private_access?) { should be true } + its(:open_access?) { should be false } + its(:open_access_with_embargo_release_date?) { should be false } end end - context "persisted" do + context 'persisted' do before { allow(subject).to receive(:persisted?).and_return(true) } - context "when it is public" do + context 'when it is public' do before do subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC end - its(:authenticated_only_access?) { should be false} - its(:private_access?) { should be false} - its(:open_access?) { should be true} - its(:open_access_with_embargo_release_date?) { should be false} + its(:authenticated_only_access?) { should be false } + its(:private_access?) { should be false } + its(:open_access?) { should be true } + its(:open_access_with_embargo_release_date?) { should be false } end - context "when it is private" do + context 'when it is private' do before do subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE end - its(:authenticated_only_access?) { should be false} - its(:private_access?) { should be true} - its(:open_access?) { should be false} - its(:open_access_with_embargo_release_date?) { should be false} + its(:authenticated_only_access?) { should be false } + its(:private_access?) { should be true } + its(:open_access?) { should be false } + its(:open_access_with_embargo_release_date?) { should be false } end - context "when it is authenticated access" do + context 'when it is authenticated access' do before do subject.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED end - its(:authenticated_only_access?) { should be true} - its(:private_access?) { should be false} - its(:open_access?) { should be false} - its(:open_access_with_embargo_release_date?) { should be false} + its(:authenticated_only_access?) { should be true } + its(:private_access?) { should be false } + its(:open_access?) { should be false } + its(:open_access_with_embargo_release_date?) { should be false } end end - end diff --git a/hydra-access-controls/spec/unit/with_depositor_spec.rb b/hydra-access-controls/spec/unit/with_depositor_spec.rb index 2a2813e3a..b15c9aa33 100644 --- a/hydra-access-controls/spec/unit/with_depositor_spec.rb +++ b/hydra-access-controls/spec/unit/with_depositor_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::WithDepositor do @@ -15,24 +17,24 @@ def initialize subject { TestClass.new } - describe "#apply_depositor_metadata" do - it "should add edit access" do + describe '#apply_depositor_metadata' do + it 'should add edit access' do subject.apply_depositor_metadata('naomi') expect(subject.edit_users).to eq ['naomi'] end - it "should not overwrite people with edit access" do + it 'should not overwrite people with edit access' do subject.edit_users = ['jessie'] subject.apply_depositor_metadata('naomi') - expect(subject.edit_users).to match_array ['naomi', 'jessie'] + expect(subject.edit_users).to match_array %w[naomi jessie] end - it "should set depositor" do + it 'should set depositor' do subject.apply_depositor_metadata('chris') expect(subject.depositor).to eq 'chris' end - it "should accept objects that respond_to? :user_key" do + it 'should accept objects that respond_to? :user_key' do stub_user = double(:user, user_key: 'monty') subject.apply_depositor_metadata(stub_user) expect(subject.depositor).to eq 'monty' diff --git a/hydra-access-controls/spec/validators/future_date_validator_spec.rb b/hydra-access-controls/spec/validators/future_date_validator_spec.rb index 430c09aba..bf7ee6345 100644 --- a/hydra-access-controls/spec/validators/future_date_validator_spec.rb +++ b/hydra-access-controls/spec/validators/future_date_validator_spec.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + require 'spec_helper' describe Hydra::FutureDateValidator do let(:future_date) { Date.today + 2 } let(:past_date) { Date.today - 2 } - let(:validator) { Hydra::FutureDateValidator.new(attributes: [:embargo_release_date, :lease_expiration_date]) } + let(:validator) { Hydra::FutureDateValidator.new(attributes: %i[embargo_release_date lease_expiration_date]) } before do validator.validate(subject) end - - context "when date is valid" do + + context 'when date is valid' do subject { ModsAsset.new(embargo_release_date: future_date) } its(:errors) { should be_empty } end - context "when date is invalid" do + context 'when date is invalid' do subject { ModsAsset.new(lease_expiration_date: past_date) } - it "has errors" do + it 'has errors' do expect(subject.errors[:lease_expiration_date]).to eq ['Must be a future date'] end end diff --git a/hydra-access-controls/tasks/hydra-access-controls.rake b/hydra-access-controls/tasks/hydra-access-controls.rake index e7e6dae88..e981c0054 100644 --- a/hydra-access-controls/tasks/hydra-access-controls.rake +++ b/hydra-access-controls/tasks/hydra-access-controls.rake @@ -1,12 +1,14 @@ -namespace "hydra-access" do - desc "Run Continuous Integration" +# frozen_string_literal: true + +namespace 'hydra-access' do + desc 'Run Continuous Integration' task :ci do - ENV['environment'] = "test" + ENV['environment'] = 'test' solr_params = { port: 8985, verbose: true, managed: true } fcrepo_params = { port: 8986, verbose: true, managed: true, no_jms: true, fcrepo_home_dir: 'fcrepo4-test-data' } SolrWrapper.wrap(solr_params) do |solr| - solr.with_collection(name: 'hydra-test', dir: File.join(File.expand_path("../..", File.dirname(__FILE__)), "solr", "config")) do + solr.with_collection(name: 'hydra-test', dir: File.join(File.expand_path('../..', File.dirname(__FILE__)), 'solr', 'config')) do FcrepoWrapper.wrap(fcrepo_params) do Rake::Task['spec'].invoke end diff --git a/hydra-core/Rakefile b/hydra-core/Rakefile index e431f11de..1ab04bd47 100644 --- a/hydra-core/Rakefile +++ b/hydra-core/Rakefile @@ -1,10 +1,12 @@ +# frozen_string_literal: true + require 'rake/testtask' require 'bundler' require 'rspec/core/rake_task' Bundler::GemHelper.install_tasks Dir.glob('tasks/*.rake').each { |r| import r } -desc "Run specs" -RSpec::Core::RakeTask.new +desc 'Run specs' +RSpec::Core::RakeTask.new -task :default => :spec +task default: :spec diff --git a/hydra-core/app/controllers/concerns/hydra/catalog.rb b/hydra-core/app/controllers/concerns/hydra/catalog.rb index c57b925c2..325cd7dab 100644 --- a/hydra-core/app/controllers/concerns/hydra/catalog.rb +++ b/hydra-core/app/controllers/concerns/hydra/catalog.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::Catalog extend ActiveSupport::Concern include Blacklight::Catalog @@ -6,7 +8,7 @@ module Hydra::Catalog # Action-specific enforcement # Controller "before" filter for enforcing access controls on show actions # @param [Hash] opts (optional, not currently used) - def enforce_show_permissions(opts={}) + def enforce_show_permissions(opts = {}) # The "super" method comes from blacklight-access_controls. # It will check the read permissions for the record. # By default, it will return a Hydra::PermissionsSolrDocument @@ -15,7 +17,7 @@ def enforce_show_permissions(opts={}) permissions_doc = super if permissions_doc.under_embargo? && !can?(:edit, permissions_doc) - raise Hydra::AccessDenied.new("This item is under embargo. You do not have sufficient access privileges to read this document.", :edit, params[:id]) + raise Hydra::AccessDenied.new('This item is under embargo. You do not have sufficient access privileges to read this document.', :edit, params[:id]) end permissions_doc diff --git a/hydra-core/app/controllers/concerns/hydra/controller.rb b/hydra-core/app/controllers/concerns/hydra/controller.rb index 83acd6aed..43af330dd 100644 --- a/hydra-core/app/controllers/concerns/hydra/controller.rb +++ b/hydra-core/app/controllers/concerns/hydra/controller.rb @@ -1,2 +1,4 @@ +# frozen_string_literal: true + module Hydra::Controller end diff --git a/hydra-core/app/controllers/concerns/hydra/controller/controller_behavior.rb b/hydra-core/app/controllers/concerns/hydra/controller/controller_behavior.rb index 1a4da2c69..8f06aebd0 100644 --- a/hydra-core/app/controllers/concerns/hydra/controller/controller_behavior.rb +++ b/hydra-core/app/controllers/concerns/hydra/controller/controller_behavior.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Include this module into any of your Controller classes to add Hydra functionality # # @example @@ -16,17 +18,17 @@ module Hydra::Controller::ControllerBehavior # get the currently configured user identifier. Can be overridden to return whatever (ie. login, email, etc) # defaults to using whatever you have set as the Devise authentication_key def user_key - current_user.user_key if current_user + current_user&.user_key end # Override this method if you wish to customize the way access is denied def deny_access(exception) if exception.action == :edit redirect_to(main_app.url_for(action: 'show'), alert: exception.message) - elsif current_user and current_user.persisted? + elsif current_user&.persisted? redirect_to main_app.root_path, alert: exception.message else - session['user_return_to'.freeze] = request.url + session['user_return_to'] = request.url redirect_to main_app.new_user_session_path, alert: exception.message end end diff --git a/hydra-core/app/controllers/concerns/hydra/controller/download_behavior.rb b/hydra-core/app/controllers/concerns/hydra/controller/download_behavior.rb index 79b5c9fe2..f4be7a257 100644 --- a/hydra-core/app/controllers/concerns/hydra/controller/download_behavior.rb +++ b/hydra-core/app/controllers/concerns/hydra/controller/download_behavior.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module Controller module DownloadBehavior @@ -21,7 +23,7 @@ def show def render_404 respond_to do |format| - format.html { render :file => "#{Rails.root}/public/404", :layout => false, :status => :not_found } + format.html { render file: "#{Rails.root}/public/404", layout: false, status: :not_found } format.any { head :not_found } end end @@ -55,12 +57,12 @@ def load_file f = asset.attached_files[file_path] if file_path f ||= default_file raise "Unable to find a file for #{asset}" if f.nil? + f end # Handle the HTTP show request def send_content - response.headers['Accept-Ranges'] = 'bytes' if request.head? @@ -83,7 +85,6 @@ def file_name params[:filename] || file.original_name || (asset.respond_to?(:label) && asset.label) || file.id end - # render an HTTP HEAD response def content_head response.headers['Content-Length'] = file.size @@ -94,10 +95,10 @@ def content_head def send_range _, range = request.headers['HTTP_RANGE'].split('bytes=') from, to = range.split('-').map(&:to_i) - to = file.size - 1 unless to + to ||= file.size - 1 length = to - from + 1 response.headers['Content-Range'] = "bytes #{from}-#{to}/#{file.size}" - response.headers['Content-Length'] = "#{length}" + response.headers['Content-Length'] = length.to_s self.status = 206 prepare_file_headers stream_body file.stream(request.headers['HTTP_RANGE']) @@ -114,7 +115,7 @@ def prepare_file_headers response.headers['Content-Type'] = file.mime_type response.headers['Content-Length'] ||= file.size.to_s # Prevent Rack::ETag from calculating a digest over body - response.headers['Last-Modified'] = asset.modified_date.utc.strftime("%a, %d %b %Y %T GMT") + response.headers['Last-Modified'] = asset.modified_date.utc.strftime('%a, %d %b %Y %T GMT') self.content_type = file.mime_type end @@ -122,8 +123,8 @@ def prepare_file_headers def stream_body(iostream) # see https://github.com/rails/rails/issues/18714#issuecomment-96204444 - unless response.headers["Last-Modified"] || response.headers["ETag"] - Rails.logger.warn("Response may be buffered instead of streaming, best to set a Last-Modified or ETag header") + unless response.headers['Last-Modified'] || response.headers['ETag'] + Rails.logger.warn('Response may be buffered instead of streaming, best to set a Last-Modified or ETag header') end self.response_body = iostream end @@ -138,7 +139,7 @@ def default_file module ClassMethods def default_file_path - "content" + 'content' end end end diff --git a/hydra-core/app/controllers/concerns/hydra/controller/ip_based_ability.rb b/hydra-core/app/controllers/concerns/hydra/controller/ip_based_ability.rb index f7661f8bd..94d2a84f8 100644 --- a/hydra-core/app/controllers/concerns/hydra/controller/ip_based_ability.rb +++ b/hydra-core/app/controllers/concerns/hydra/controller/ip_based_ability.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::Controller module IpBasedAbility # Overriding the default method provided by cancan diff --git a/hydra-core/app/helpers/blacklight_helper.rb b/hydra-core/app/helpers/blacklight_helper.rb index 5474552de..b6722e540 100644 --- a/hydra-core/app/helpers/blacklight_helper.rb +++ b/hydra-core/app/helpers/blacklight_helper.rb @@ -1,4 +1,5 @@ +# frozen_string_literal: true + module BlacklightHelper include Hydra::BlacklightHelperBehavior end - diff --git a/hydra-core/app/helpers/hydra/blacklight_helper_behavior.rb b/hydra-core/app/helpers/hydra/blacklight_helper_behavior.rb index 7b11b1cff..d1dad5ca5 100644 --- a/hydra-core/app/helpers/hydra/blacklight_helper_behavior.rb +++ b/hydra-core/app/helpers/hydra/blacklight_helper_behavior.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + module Hydra module BlacklightHelperBehavior include Blacklight::BlacklightHelperBehavior - + ## # Given a Fedora uri, generate a reasonable partial name # Rails thinks that periods indicate a filename, so escape them with slashes. @@ -14,12 +16,12 @@ module BlacklightHelperBehavior # => 'generic_content' # type_field_to_partial_name(["text.pdf"]) # => 'text_pdf' - def type_field_to_partial_name(document, display_type) - str = Array(display_type).join(' '.freeze).underscore + def type_field_to_partial_name(_document, display_type) + str = Array(display_type).join(' ').underscore if Rails.version >= '5.0.0' - str.parameterize(separator: '_'.freeze) + str.parameterize(separator: '_') else - str.parameterize('_'.freeze) + str.parameterize('_') end end end diff --git a/hydra-core/app/models/concerns/hydra/content_negotiation.rb b/hydra-core/app/models/concerns/hydra/content_negotiation.rb index d8dfc32f0..b3f0c3c07 100644 --- a/hydra-core/app/models/concerns/hydra/content_negotiation.rb +++ b/hydra-core/app/models/concerns/hydra/content_negotiation.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + module Hydra module ContentNegotiation def self.extended(document) - document.will_export_as(:nt, "application/n-triples") - document.will_export_as(:jsonld, "application/ld+json") - document.will_export_as(:ttl, "text/turtle") + document.will_export_as(:nt, 'application/n-triples') + document.will_export_as(:jsonld, 'application/ld+json') + document.will_export_as(:ttl, 'text/turtle') end def export_as_nt @@ -11,7 +13,7 @@ def export_as_nt end def export_as_jsonld - clean_graph.dump(:jsonld, :standard_prefixes => true) + clean_graph.dump(:jsonld, standard_prefixes: true) end def export_as_ttl diff --git a/hydra-core/app/models/concerns/hydra/models.rb b/hydra-core/app/models/concerns/hydra/models.rb index 195b342a4..35c81714b 100644 --- a/hydra-core/app/models/concerns/hydra/models.rb +++ b/hydra-core/app/models/concerns/hydra/models.rb @@ -1,5 +1,6 @@ +# frozen_string_literal: true + module Hydra module Models end end - diff --git a/hydra-core/app/models/concerns/hydra/solr.rb b/hydra-core/app/models/concerns/hydra/solr.rb index de4e2306e..16daf1479 100644 --- a/hydra-core/app/models/concerns/hydra/solr.rb +++ b/hydra-core/app/models/concerns/hydra/solr.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra module Solr module Document diff --git a/hydra-core/app/models/hydra/content_negotiation/clean_graph_repository.rb b/hydra-core/app/models/hydra/content_negotiation/clean_graph_repository.rb index 1b097159a..601c6a7dc 100644 --- a/hydra-core/app/models/hydra/content_negotiation/clean_graph_repository.rb +++ b/hydra-core/app/models/hydra/content_negotiation/clean_graph_repository.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::ContentNegotiation # CleanGraphRepository has a #find interface which returns a graph for use # with content negotiation. diff --git a/hydra-core/app/models/hydra/content_negotiation/fedora_uri_replacer.rb b/hydra-core/app/models/hydra/content_negotiation/fedora_uri_replacer.rb index cbad72996..0bf738872 100644 --- a/hydra-core/app/models/hydra/content_negotiation/fedora_uri_replacer.rb +++ b/hydra-core/app/models/hydra/content_negotiation/fedora_uri_replacer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::ContentNegotiation # Replaces Fedora URIs in a graph with a Hydra-configured alternative. class FedoraUriReplacer diff --git a/hydra-core/app/models/hydra/content_negotiation/graph_finder.rb b/hydra-core/app/models/hydra/content_negotiation/graph_finder.rb index f07718346..ad10219ee 100644 --- a/hydra-core/app/models/hydra/content_negotiation/graph_finder.rb +++ b/hydra-core/app/models/hydra/content_negotiation/graph_finder.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Hydra::ContentNegotiation # Finds a graph given a connection and ID. class GraphFinder diff --git a/hydra-core/app/models/hydra/content_negotiation/replacing_graph_finder.rb b/hydra-core/app/models/hydra/content_negotiation/replacing_graph_finder.rb index 65337ec8c..fe1109ef8 100644 --- a/hydra-core/app/models/hydra/content_negotiation/replacing_graph_finder.rb +++ b/hydra-core/app/models/hydra/content_negotiation/replacing_graph_finder.rb @@ -1,8 +1,9 @@ +# frozen_string_literal: true + module Hydra::ContentNegotiation - # Decorator for Finder which replaces Fedora subjects in the graph with a + # Decorator for Finder which replaces Fedora subjects in the graph with a # configured URI class ReplacingGraphFinder < SimpleDelegator - attr_reader :replacer def initialize(graph_finder, replacer) super(graph_finder) diff --git a/hydra-core/hydra-core.gemspec b/hydra-core/hydra-core.gemspec index 70e6c3fe0..72c126547 100644 --- a/hydra-core/hydra-core.gemspec +++ b/hydra-core/hydra-core.gemspec @@ -1,25 +1,26 @@ -# -*- encoding: utf-8 -*- -version = File.read(File.expand_path("../../HYDRA_VERSION", __FILE__)).strip +# frozen_string_literal: true + +version = File.read(File.expand_path('../HYDRA_VERSION', __dir__)).strip Gem::Specification.new do |gem| - gem.authors = ["Matt Zumwalt, Bess Sadler, Julie Meloni, Naomi Dushay, Jessie Keck, John Scofield, Justin Coyne & many more. See https://github.com/projecthydra/hydra-head/contributors"] - gem.email = ["hydra-tech@googlegroups.com"] - gem.homepage = "http://projecthydra.org" - gem.summary = %q{Hydra-Head Rails Engine (requires Rails3) } - gem.description = %q{Hydra-Head is a Rails Engine containing the core code for a Hydra application. The full hydra stack includes: Blacklight, Fedora, Solr, active-fedora, solrizer, and om} + gem.authors = ['Matt Zumwalt, Bess Sadler, Julie Meloni, Naomi Dushay, Jessie Keck, John Scofield, Justin Coyne & many more. See https://github.com/projecthydra/hydra-head/contributors'] + gem.email = ['hydra-tech@googlegroups.com'] + gem.homepage = 'http://projecthydra.org' + gem.summary = 'Hydra-Head Rails Engine (requires Rails3) ' + gem.description = 'Hydra-Head is a Rails Engine containing the core code for a Hydra application. The full hydra stack includes: Blacklight, Fedora, Solr, active-fedora, solrizer, and om' - gem.files = `git ls-files`.split($\) - gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } + gem.files = `git ls-files`.split($OUTPUT_RECORD_SEPARATOR) + gem.executables = gem.files.grep(%r{^bin/}).map { |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) - gem.name = "hydra-core" - gem.require_paths = ["lib"] + gem.name = 'hydra-core' + gem.require_paths = ['lib'] gem.version = version - gem.license = "APACHE2" + gem.license = 'APACHE2' gem.required_ruby_version = '>= 1.9.3' gem.add_dependency 'hydra-access-controls', version - gem.add_dependency "railties", '>= 4.0.0', '< 6' + gem.add_dependency 'railties', '>= 4.0.0', '< 6' gem.add_development_dependency 'rails-controller-testing', '~> 1' gem.add_development_dependency 'rspec-rails', '~> 3.1' diff --git a/hydra-core/lib/application_helper.rb b/hydra-core/lib/application_helper.rb index 69d3ff512..bd692e954 100644 --- a/hydra-core/lib/application_helper.rb +++ b/hydra-core/lib/application_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Needed for testing module ApplicationHelper end diff --git a/hydra-core/lib/generators/hydra/head_generator.rb b/hydra-core/lib/generators/hydra/head_generator.rb index 4615ffccf..374577ce2 100644 --- a/hydra-core/lib/generators/hydra/head_generator.rb +++ b/hydra-core/lib/generators/hydra/head_generator.rb @@ -1,57 +1,57 @@ -# -*- encoding : utf-8 -*- +# frozen_string_literal: true + require 'rails/generators' module Hydra class HeadGenerator < Rails::Generators::Base + source_root File.expand_path('templates', __dir__) - source_root File.expand_path('../templates', __FILE__) - - argument :model_name, type: :string , default: 'User' - class_option :'skip-rspec', type: :boolean, default: false, desc: "Skip the rspec generator" - + argument :model_name, type: :string, default: 'User' + class_option :'skip-rspec', type: :boolean, default: false, desc: 'Skip the rspec generator' - desc """ - This generator makes the following changes to your application: - 1. Creates config/initializers/hydra_config.rb - 2. Creates config/fedora.yml and config/solr.yml which you may need to modify to tell the hydra head where to find fedora & solr - 3. Creates a number of role_map config files that are used in the placeholder user roles implementation - Enjoy building your Hydra Head! - """ + desc ''" + This generator makes the following changes to your application: + 1. Creates config/initializers/hydra_config.rb + 2. Creates config/fedora.yml and config/solr.yml which you may need to modify to tell the hydra head where to find fedora & solr + 3. Creates a number of role_map config files that are used in the placeholder user roles implementation + Enjoy building your Hydra Head! + "'' # # Config Files & Initializers # - # + # def add_gems gem_group :development, :test do - gem "fcrepo_wrapper" - gem "rspec-rails" unless options[:'skip-rspec'] + gem 'fcrepo_wrapper' + gem 'rspec-rails' unless options[:'skip-rspec'] end Bundler.with_clean_env do - run "bundle install" + run 'bundle install' end end def install_rspec return if options[:'skip-rspec'] + generate 'rspec:install' end def overwrite_catalog_controller - copy_file "catalog_controller.rb", "app/controllers/catalog_controller.rb" + copy_file 'catalog_controller.rb', 'app/controllers/catalog_controller.rb' end # Add Hydra to the application controller def inject_hydra_controller_behavior - insert_into_file "app/controllers/application_controller.rb", after: "include Blacklight::Controller\n" do + insert_into_file 'app/controllers/application_controller.rb', after: "include Blacklight::Controller\n" do " include Hydra::Controller::ControllerBehavior\n" end end # Add Hydra to the SearchBuilder def inject_hydra_search_builder_behavior - insert_into_file "app/models/search_builder.rb", after: "include Blacklight::Solr::SearchBuilderBehavior\n" do + insert_into_file 'app/models/search_builder.rb', after: "include Blacklight::Solr::SearchBuilderBehavior\n" do " # Add a filter query to restrict the search to documents the current user has access to\n" \ " include Hydra::AccessControlsEnforcement\n" end @@ -59,16 +59,15 @@ def inject_hydra_search_builder_behavior # Copy all files in templates/config directory to host config def create_configuration_files - # Initializers - template "config/initializers/hydra_config.rb", - "config/initializers/hydra_config.rb" + template 'config/initializers/hydra_config.rb', + 'config/initializers/hydra_config.rb' # Role Mappings - copy_file "config/role_map.yml", "config/role_map.yml" + copy_file 'config/role_map.yml', 'config/role_map.yml' # CanCan ability.rb - copy_file "ability.rb", "app/models/ability.rb" + copy_file 'ability.rb', 'app/models/ability.rb' # Fedora & Solr YAML files invoke('active_fedora:config') @@ -77,20 +76,20 @@ def create_configuration_files end def create_conneg_configuration - file_path = "config/initializers/mime_types.rb" + file_path = 'config/initializers/mime_types.rb' append_to_file file_path do - "Mime::Type.register \"application/n-triples\", :nt\n" + - "Mime::Type.register \"application/ld+json\", :jsonld\n" + - "Mime::Type.register \"text/turtle\", :ttl" + "Mime::Type.register \"application/n-triples\", :nt\n" \ + "Mime::Type.register \"application/ld+json\", :jsonld\n" \ + 'Mime::Type.register "text/turtle", :ttl' end end def inject_solr_document_conneg - file_path = "app/models/solr_document.rb" - if File.exists?(file_path) - inject_into_file file_path, :before => /end\Z/ do - "\n # Do content negotiation for AF models. \n" + - "\n use_extension( Hydra::ContentNegotiation )\n" + file_path = 'app/models/solr_document.rb' + if File.exist?(file_path) + inject_into_file file_path, before: /end\Z/ do + "\n # Do content negotiation for AF models. \n" \ + "\n use_extension( Hydra::ContentNegotiation )\n" end end end @@ -98,10 +97,10 @@ def inject_solr_document_conneg # Add Hydra behaviors to the user model def inject_hydra_user_behavior file_path = "app/models/#{model_name.underscore}.rb" - if File.exists?(file_path) + if File.exist?(file_path) inject_into_class file_path, model_name.classify do - " # Connects this user object to Hydra behaviors.\n" + - " include Hydra::User\n\n" + " # Connects this user object to Hydra behaviors.\n" \ + " include Hydra::User\n\n" end else puts " \e[31mFailure\e[0m Hydra requires a user object in order to apply access controls. This generators assumes that the model is defined in the file #{file_path}, which does not exist. If you used a different name, please re-run the generator and provide that name as an argument. Such as \b rails -g hydra:head client" diff --git a/hydra-core/lib/generators/hydra/templates/ability.rb b/hydra-core/lib/generators/hydra/templates/ability.rb index 220539b6f..aa4d20ef2 100644 --- a/hydra-core/lib/generators/hydra/templates/ability.rb +++ b/hydra-core/lib/generators/hydra/templates/ability.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + class Ability include Hydra::Ability - + # Define any customized permissions here. def custom_permissions # Limits deleting objects to a the admin user diff --git a/hydra-core/lib/generators/hydra/templates/catalog_controller.rb b/hydra-core/lib/generators/hydra/templates/catalog_controller.rb index 9137d3966..1ac6da717 100644 --- a/hydra-core/lib/generators/hydra/templates/catalog_controller.rb +++ b/hydra-core/lib/generators/hydra/templates/catalog_controller.rb @@ -1,8 +1,8 @@ -# -*- encoding : utf-8 -*- +# frozen_string_literal: true + require 'blacklight/catalog' class CatalogController < ApplicationController - include Hydra::Catalog # This filter applies the hydra access controls before_action :enforce_show_permissions, only: :show @@ -27,7 +27,6 @@ class CatalogController < ApplicationController config.index.title_field = 'title_tesim' config.index.display_type_field = 'has_model_ssim' - # solr fields that will be treated as facets by the blacklight application # The ordering of the field names is the order of the display # @@ -59,9 +58,8 @@ class CatalogController < ApplicationController # previously. Simply remove these lines if you'd rather use Solr request # handler defaults, or have no facets. config.default_solr_params[:'facet.field'] = config.facet_fields.keys - #use this instead if you don't want to query facets marked :show=>false - #config.default_solr_params[:'facet.field'] = config.facet_fields.select{ |k, v| v[:show] != false}.keys - + # use this instead if you don't want to query facets marked :show=>false + # config.default_solr_params[:'facet.field'] = config.facet_fields.select{ |k, v| v[:show] != false}.keys # solr fields to be displayed in the index (search results) view # The ordering of the field names is the order of the display @@ -112,7 +110,6 @@ class CatalogController < ApplicationController config.add_search_field 'all_fields', label: 'All Fields' - # Now we see how to over-ride Solr request handler defaults, in this # case for a BL "search field", which is really a dismax aggregate # of Solr search fields. @@ -159,7 +156,4 @@ class CatalogController < ApplicationController # mean") suggestion is offered. config.spell_max = 5 end - - - end diff --git a/hydra-core/lib/hydra-core.rb b/hydra-core/lib/hydra-core.rb index efe84261c..35e5d70e2 100644 --- a/hydra-core/lib/hydra-core.rb +++ b/hydra-core/lib/hydra-core.rb @@ -1,7 +1,8 @@ +# frozen_string_literal: true + require 'hydra-access-controls' require 'deprecation' module HydraHead require 'hydra-head/engine' if defined?(Rails) end - diff --git a/hydra-core/lib/hydra-head/engine.rb b/hydra-core/lib/hydra-head/engine.rb index 99d114474..63bcdee1c 100644 --- a/hydra-core/lib/hydra-head/engine.rb +++ b/hydra-core/lib/hydra-head/engine.rb @@ -1,19 +1,21 @@ -require "rails" +# frozen_string_literal: true + +require 'rails' module HydraHead class Engine < Rails::Engine # Config defaults config.mount_at = '/' - config.autoload_paths += %W( + config.autoload_paths += %W[ #{config.root}/app/controllers/concerns #{config.root}/app/models/concerns - ) - + ] + # Load rake tasks rake_tasks do - Dir.glob(File.join(File.expand_path('../', File.dirname(__FILE__)),'railties', '*.rake')).each do |railtie| + Dir.glob(File.join(File.expand_path('../', File.dirname(__FILE__)), 'railties', '*.rake')).each do |railtie| load railtie end end - end + end end diff --git a/hydra-core/lib/hydra-head/version.rb b/hydra-core/lib/hydra-head/version.rb index fa4999ed3..5f2383035 100644 --- a/hydra-core/lib/hydra-head/version.rb +++ b/hydra-core/lib/hydra-head/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module HydraHead - VERSION = "10.6.1" + VERSION = '10.6.1' end diff --git a/hydra-core/lib/railties/active-fedora.rake b/hydra-core/lib/railties/active-fedora.rake index 52c40082a..06bc83fcf 100644 --- a/hydra-core/lib/railties/active-fedora.rake +++ b/hydra-core/lib/railties/active-fedora.rake @@ -1 +1,3 @@ -require "active-fedora" # This causes active-fedora's rake tasks to be loaded \ No newline at end of file +# frozen_string_literal: true + +require 'active-fedora' # This causes active-fedora's rake tasks to be loaded diff --git a/hydra-core/lib/tasks/hydra.rake b/hydra-core/lib/tasks/hydra.rake index 40060a364..0c56b4298 100644 --- a/hydra-core/lib/tasks/hydra.rake +++ b/hydra-core/lib/tasks/hydra.rake @@ -1,14 +1,16 @@ +# frozen_string_literal: true + require 'active_fedora/rake_support' namespace :hydra do - desc "Start a solr, fedora and rails instance" + desc 'Start a solr, fedora and rails instance' task :server do with_server(ENV['RAILS_ENV'] || 'development') do puts "Fedora: #{ActiveFedora.config.credentials[:url]}" puts "Solr..: #{ActiveFedora.solr_config[:url]}" begin if ENV['SKIP_RAILS'] - puts "^C to exit" + puts '^C to exit' sleep else # If HOST specified, bind to that IP with -b @@ -20,12 +22,12 @@ namespace :hydra do end end rescue Interrupt - puts "Stopping server" + puts 'Stopping server' end end end - desc "Start solr and fedora instances for tests" + desc 'Start solr and fedora instances for tests' task :test_server do ENV['RAILS_ENV'] = 'test' ENV['SKIP_RAILS'] = 'true' diff --git a/hydra-core/spec/controllers/catalog_controller_spec.rb b/hydra-core/spec/controllers/catalog_controller_spec.rb index 47f322eb1..347d1310a 100644 --- a/hydra-core/spec/controllers/catalog_controller_spec.rb +++ b/hydra-core/spec/controllers/catalog_controller_spec.rb @@ -1,64 +1,65 @@ +# frozen_string_literal: true + require 'spec_helper' describe CatalogController do - before do - session[:user]='bob' + session[:user] = 'bob' end - it "uses the CatalogController" do + it 'uses the CatalogController' do expect(controller).to be_an_instance_of CatalogController end - describe "configuration" do + describe 'configuration' do let(:config) { CatalogController.blacklight_config } - describe "search_builder_class" do - subject {config.search_builder_class } + describe 'search_builder_class' do + subject { config.search_builder_class } it { is_expected.to eq ::SearchBuilder } end end - describe "index" do - describe "access controls" do + describe 'index' do + describe 'access controls' do before(:all) do - fq = "read_access_group_ssim:public OR edit_access_group_ssim:public OR discover_access_group_ssim:public" + fq = 'read_access_group_ssim:public OR edit_access_group_ssim:public OR discover_access_group_ssim:public' solr_opts = { fq: fq } response = ActiveFedora::SolrService.instance.conn.get('select', params: solr_opts) @public_only_results = Blacklight::Solr::Response.new(response, solr_opts) end - it "should only return public documents if role does not have permissions" do + it 'should only return public documents if role does not have permissions' do allow(controller).to receive(:current_user).and_return(nil) get :index expect(assigns(:document_list).count).to eq @public_only_results.docs.count end - it "should return documents if the group names need to be escaped" do - allow(RoleMapper).to receive(:roles).and_return(["abc/123","cde/567"]) + it 'should return documents if the group names need to be escaped' do + allow(RoleMapper).to receive(:roles).and_return(['abc/123', 'cde/567']) get :index expect(assigns(:document_list).count).to eq @public_only_results.docs.count end end end - describe "content negotiation" do - describe "show" do + describe 'content negotiation' do + describe 'show' do before do allow(controller).to receive(:enforce_show_permissions) end - context "with no asset" do - it "returns a not found response code" do - get 'show', params: { id: "test", format: :nt } + context 'with no asset' do + it 'returns a not found response code' do + get 'show', params: { id: 'test', format: :nt } expect(response).to be_not_found end end - context "with an asset" do - let(:type) { RDF::URI("http://example.org/example") } + context 'with an asset' do + let(:type) { RDF::URI('http://example.org/example') } let(:related_uri) { related.rdf_subject } let(:asset) do ActiveFedora::Base.create do |g| - g.resource << [g.rdf_subject, RDF::Vocab::DC.title, "Test Title"] + g.resource << [g.rdf_subject, RDF::Vocab::DC.title, 'Test Title'] g.resource << [g.rdf_subject, RDF.type, type] g.resource << [g.rdf_subject, RDF::Vocab::DC.isReferencedBy, related_uri] end @@ -66,24 +67,24 @@ let(:related) do ActiveFedora::Base.create end - it "is able to negotiate jsonld" do + it 'is able to negotiate jsonld' do get 'show', params: { id: asset.id, format: :jsonld } expect(response).to be_success - expect(response.headers['Content-Type']).to include("application/ld+json") + expect(response.headers['Content-Type']).to include('application/ld+json') graph = RDF::Reader.for(:jsonld).new(response.body) expect(graph.statements.to_a.length).to eq 3 end - it "is able to negotiate ttl" do + it 'is able to negotiate ttl' do get 'show', params: { id: asset.id, format: :ttl } - + expect(response).to be_success graph = RDF::Reader.for(:ttl).new(response.body) expect(graph.statements.to_a.length).to eq 3 end - it "returns an n-triples graph with just the content put in" do + it 'returns an n-triples graph with just the content put in' do get 'show', params: { id: asset.id, format: :nt } graph = RDF::Reader.for(:ntriples).new(response.body) @@ -92,13 +93,13 @@ expect(statements.first.subject).to eq asset.rdf_subject end - context "with a configured subject converter" do + context 'with a configured subject converter' do before do - Hydra.config.id_to_resource_uri = lambda { |id, _| "http://hydra.box/catalog/#{id}" } + Hydra.config.id_to_resource_uri = ->(id, _) { "http://hydra.box/catalog/#{id}" } get 'show', params: { id: asset.id, format: :nt } end - it "converts the subject using the specified converter" do + it 'converts the subject using the specified converter' do graph = RDF::Graph.new << RDF::Reader.for(:ntriples).new(response.body) title_statement = graph.query([nil, RDF::Vocab::DC.title, nil]).first related_statement = graph.query([nil, RDF::Vocab::DC.isReferencedBy, nil]).first @@ -110,9 +111,9 @@ end end - describe "filters" do - describe "show" do - it "triggers enforce_show_permissions" do + describe 'filters' do + describe 'show' do + it 'triggers enforce_show_permissions' do allow(controller).to receive(:current_user).and_return(nil) expect(controller).to receive(:enforce_show_permissions) get :show, params: { id: 'test:3' } @@ -120,21 +121,21 @@ end end - describe "enforce_show_permissions" do - let(:email_edit_access) { "edit_access@example.com" } - let(:email_read_access) { "read_access@example.com" } - let(:future_date) { 2.days.from_now.strftime("%Y-%m-%dT%H:%M:%SZ") } + describe 'enforce_show_permissions' do + let(:email_edit_access) { 'edit_access@example.com' } + let(:email_read_access) { 'read_access@example.com' } + let(:future_date) { 2.days.from_now.strftime('%Y-%m-%dT%H:%M:%SZ') } - let(:embargoed_object) { + let(:embargoed_object) do doc = SolrDocument.new(id: '123', - "edit_access_person_ssim" => [email_edit_access], - "read_access_person_ssim" => [email_read_access], - "embargo_release_date_dtsi" => future_date) + 'edit_access_person_ssim' => [email_edit_access], + 'read_access_person_ssim' => [email_read_access], + 'embargo_release_date_dtsi' => future_date) solr = Blacklight.default_index.connection solr.add(doc) solr.commit doc - } + end before do controller.params = { id: embargoed_object.id } @@ -145,9 +146,9 @@ let(:user) { User.new email: email_edit_access } it 'allows the user to view an embargoed object' do - expect { + expect do controller.send(:enforce_show_permissions, {}) - }.not_to raise_error + end.not_to raise_error end end @@ -155,11 +156,10 @@ let(:user) { User.new email: email_read_access } it 'denies access to the embargoed object' do - expect { + expect do controller.send(:enforce_show_permissions, {}) - }.to raise_error Hydra::AccessDenied, "This item is under embargo. You do not have sufficient access privileges to read this document." + end.to raise_error Hydra::AccessDenied, 'This item is under embargo. You do not have sufficient access privileges to read this document.' end end end - end diff --git a/hydra-core/spec/controllers/downloads_controller_spec.rb b/hydra-core/spec/controllers/downloads_controller_spec.rb index 8396c0d51..40e46828e 100644 --- a/hydra-core/spec/controllers/downloads_controller_spec.rb +++ b/hydra-core/spec/controllers/downloads_controller_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe DownloadsController do @@ -9,20 +11,20 @@ end end - describe "routing" do - it "routes" do - assert_recognizes({ controller: "downloads", action: "show", id: "test1" }, - "/downloads/test1?filename=my%20dog.jpg") + describe 'routing' do + it 'routes' do + assert_recognizes({ controller: 'downloads', action: 'show', id: 'test1' }, + '/downloads/test1?filename=my%20dog.jpg') end end - describe "with a file" do + describe 'with a file' do before do class ContentHolder < ActiveFedora::Base include Hydra::AccessControls::Permissions has_subresource 'thumbnail' end - @user = User.new.tap {|u| u.email = 'email@example.com'; u.password = 'password'; u.save} + @user = User.new.tap { |u| u.email = 'email@example.com'; u.password = 'password'; u.save } end let(:obj) do ContentHolder.new.tap do |obj| @@ -39,91 +41,90 @@ class ContentHolder < ActiveFedora::Base Object.send(:remove_const, :ContentHolder) end - context "when not logged in" do - - context "when a specific datastream is requested" do - it "redirects to the root path and display an error" do - get :show, params: { id: obj, file: "descMetadata" } + context 'when not logged in' do + context 'when a specific datastream is requested' do + it 'redirects to the root path and display an error' do + get :show, params: { id: obj, file: 'descMetadata' } expect(response).to redirect_to new_user_session_path - expect(flash[:alert]).to eq "You are not authorized to access this page." + expect(flash[:alert]).to eq 'You are not authorized to access this page.' end end end - context "when logged in, but without read access" do + context 'when logged in, but without read access' do let(:user) { User.create(email: 'email2@example.com', password: 'password') } before do sign_in user end - context "when a specific datastream is requested" do - it "redirects to the root path and display an error" do - get :show, params: { id: obj, file: "descMetadata" } + context 'when a specific datastream is requested' do + it 'redirects to the root path and display an error' do + get :show, params: { id: obj, file: 'descMetadata' } expect(response).to redirect_to root_path - expect(flash[:alert]).to eq "You are not authorized to access this page." + expect(flash[:alert]).to eq 'You are not authorized to access this page.' end end end - context "when logged in as reader" do + context 'when logged in as reader' do before do sign_in @user allow_any_instance_of(User).to receive(:groups).and_return([]) end - describe "#show" do - it "defaults to returning default download configured by object" do + describe '#show' do + it 'defaults to returning default download configured by object' do allow(ContentHolder).to receive(:default_file_path).and_return('buzz') get :show, params: { id: obj } expect(response).to be_successful - expect(response.headers['Content-Type']).to start_with "image/png" - expect(response.headers["Content-Disposition"]).to eq "inline; filename=\"buzz.png\"" + expect(response.headers['Content-Type']).to start_with 'image/png' + expect(response.headers['Content-Disposition']).to eq 'inline; filename="buzz.png"' expect(response.body).to eq 'fizz' end - it "defaults to returning default download configured by controller" do - expect(DownloadsController.default_file_path).to eq "content" + it 'defaults to returning default download configured by controller' do + expect(DownloadsController.default_file_path).to eq 'content' get :show, params: { id: obj } expect(response).to be_successful - expect(response.headers['Content-Type']).to start_with "image/png" - expect(response.headers["Content-Disposition"]).to eq "inline; filename=\"world.png\"" + expect(response.headers['Content-Type']).to start_with 'image/png' + expect(response.headers['Content-Disposition']).to eq 'inline; filename="world.png"' expect(response.body).to eq 'foobarfoobarfoobar' end - context "when a specific datastream is requested" do + context 'when a specific datastream is requested' do context "and it doesn't exist" do it "returns :not_found when the datastream doesn't exist" do - get :show, params: { id: obj, file: "thumbnail" } + get :show, params: { id: obj, file: 'thumbnail' } expect(response).to be_not_found end end - context "and it exists" do - it "returns it" do - get :show, params: { id: obj, file: "descMetadata" } + context 'and it exists' do + it 'returns it' do + get :show, params: { id: obj, file: 'descMetadata' } expect(response).to be_successful - expect(response.headers['Content-Type']).to start_with "text/plain" - expect(response.headers["Content-Disposition"]).to eq "inline; filename=\"metadata.xml\"" + expect(response.headers['Content-Type']).to start_with 'text/plain' + expect(response.headers['Content-Disposition']).to eq 'inline; filename="metadata.xml"' expect(response.body).to eq "It's a stream" end end end - it "supports setting disposition to inline" do - get :show, params: { id: obj, disposition: "inline" } + it 'supports setting disposition to inline' do + get :show, params: { id: obj, disposition: 'inline' } expect(response).to be_successful - expect(response.headers['Content-Type']).to start_with "image/png" - expect(response.headers["Content-Disposition"]).to eq "inline; filename=\"world.png\"" + expect(response.headers['Content-Type']).to start_with 'image/png' + expect(response.headers['Content-Disposition']).to eq 'inline; filename="world.png"' expect(response.body).to eq 'foobarfoobarfoobar' end - it "allows you to specify filename for download" do - get :show, params: { id: obj, "filename" => "my%20dog.png" } + it 'allows you to specify filename for download' do + get :show, params: { id: obj, 'filename' => 'my%20dog.png' } expect(response).to be_successful - expect(response.headers['Content-Type']).to start_with "image/png" - expect(response.headers["Content-Disposition"]).to eq "inline; filename=\"my%20dog.png\"" + expect(response.headers['Content-Type']).to start_with 'image/png' + expect(response.headers['Content-Disposition']).to eq 'inline; filename="my%20dog.png"' expect(response.body).to eq 'foobarfoobarfoobar' end end - describe "stream" do + describe 'stream' do let(:parent) { ActiveFedora::Base.new(id: '1234') } before do @@ -132,51 +133,51 @@ class ContentHolder < ActiveFedora::Base expect(controller).to receive(:authorize!).with(:download, instance_of(ActiveFedora::File)).and_return(true) end - it "head request" do - request.env["HTTP_RANGE"] = 'bytes=0-15' + it 'head request' do + request.env['HTTP_RANGE'] = 'bytes=0-15' head :show, params: { id: parent, file: 'webm' } expect(response.headers['Content-Length']).to eq 16 expect(response.headers['Accept-Ranges']).to eq 'bytes' expect(response.headers['Content-Type']).to start_with 'video/webm' end - it "sends the whole thing" do - request.env["HTTP_RANGE"] = 'bytes=0-15' + it 'sends the whole thing' do + request.env['HTTP_RANGE'] = 'bytes=0-15' get :show, params: { id: '1234', file: 'webm' } expect(response.body).to eq 'one1two2threfour' - expect(response.headers["Content-Range"]).to eq 'bytes 0-15/16' - expect(response.headers["Content-Length"]).to eq '16' + expect(response.headers['Content-Range']).to eq 'bytes 0-15/16' + expect(response.headers['Content-Length']).to eq '16' expect(response.headers['Accept-Ranges']).to eq 'bytes' - expect(response.headers['Content-Type']).to start_with "video/webm" - expect(response.headers["Content-Disposition"]).to eq "inline; filename=\"MyVideo.webm\"" + expect(response.headers['Content-Type']).to start_with 'video/webm' + expect(response.headers['Content-Disposition']).to eq 'inline; filename="MyVideo.webm"' expect(response.status).to eq 206 end - it "sends the whole thing when the range is open ended" do - request.env["HTTP_RANGE"] = 'bytes=0-' + it 'sends the whole thing when the range is open ended' do + request.env['HTTP_RANGE'] = 'bytes=0-' get :show, params: { id: '1234', file: 'webm' } expect(response.body).to eq 'one1two2threfour' end - it "gets a range not starting at the beginning" do - request.env["HTTP_RANGE"] = 'bytes=3-15' + it 'gets a range not starting at the beginning' do + request.env['HTTP_RANGE'] = 'bytes=3-15' get :show, params: { id: '1234', file: 'webm' } expect(response.body).to eq '1two2threfour' - expect(response.headers["Content-Range"]).to eq 'bytes 3-15/16' - expect(response.headers["Content-Length"]).to eq '13' + expect(response.headers['Content-Range']).to eq 'bytes 3-15/16' + expect(response.headers['Content-Length']).to eq '13' end - it "gets a range not ending at the end" do - request.env["HTTP_RANGE"] = 'bytes=4-11' + it 'gets a range not ending at the end' do + request.env['HTTP_RANGE'] = 'bytes=4-11' get :show, params: { id: '1234', file: 'webm' } expect(response.body).to eq 'two2thre' - expect(response.headers["Content-Range"]).to eq 'bytes 4-11/16' - expect(response.headers["Content-Length"]).to eq '8' + expect(response.headers['Content-Range']).to eq 'bytes 4-11/16' + expect(response.headers['Content-Length']).to eq '8' end end end - describe "overriding the default asset param key" do + describe 'overriding the default asset param key' do before do Rails.application.routes.draw do scope 'objects/:object_id' do @@ -185,7 +186,7 @@ class ContentHolder < ActiveFedora::Base end sign_in @user end - it "uses the custom param value to retrieve the asset" do + it 'uses the custom param value to retrieve the asset' do allow(controller).to receive(:asset_param_key).and_return(:object_id) get :show, params: { object_id: obj } expect(response).to be_successful diff --git a/hydra-core/spec/controllers/ip_based_ability_spec.rb b/hydra-core/spec/controllers/ip_based_ability_spec.rb index 20ecc72fc..1098eec13 100644 --- a/hydra-core/spec/controllers/ip_based_ability_spec.rb +++ b/hydra-core/spec/controllers/ip_based_ability_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'IpBasedAbilitySpec' do diff --git a/hydra-core/spec/helpers/blacklight_helper_spec.rb b/hydra-core/spec/helpers/blacklight_helper_spec.rb index e5991c127..e51ae1ca8 100644 --- a/hydra-core/spec/helpers/blacklight_helper_spec.rb +++ b/hydra-core/spec/helpers/blacklight_helper_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' describe BlacklightHelper do - describe "document_partial_name" do + describe 'document_partial_name' do let(:field_name) { 'has_model_s' } let(:config) do @@ -14,20 +16,20 @@ allow(helper).to receive(:blacklight_config).and_return(config) end - it "changes camel case to underscored lowercase" do - expect(helper.document_partial_name('has_model_s' => ["Presentation"])).to eq "presentation" - expect(helper.document_partial_name('has_model_s' => ["GenericContent"])).to eq "generic_content" + it 'changes camel case to underscored lowercase' do + expect(helper.document_partial_name('has_model_s' => ['Presentation'])).to eq 'presentation' + expect(helper.document_partial_name('has_model_s' => ['GenericContent'])).to eq 'generic_content' end - context "with a single valued field" do + context 'with a single valued field' do let(:field_name) { 'has_model_s' } - it "should support single valued fields" do - expect(helper.document_partial_name('has_model_s' => "Chicken")).to eq "chicken" + it 'should support single valued fields' do + expect(helper.document_partial_name('has_model_s' => 'Chicken')).to eq 'chicken' end end - it "handles periods" do - expect(helper.document_partial_name('has_model_s' => ["text.PDF"])).to eq "text_pdf" + it 'handles periods' do + expect(helper.document_partial_name('has_model_s' => ['text.PDF'])).to eq 'text_pdf' end end end diff --git a/hydra-core/spec/models/content_negotiation/replacing_graph_finder_spec.rb b/hydra-core/spec/models/content_negotiation/replacing_graph_finder_spec.rb index 283d4846d..70edbfb2d 100644 --- a/hydra-core/spec/models/content_negotiation/replacing_graph_finder_spec.rb +++ b/hydra-core/spec/models/content_negotiation/replacing_graph_finder_spec.rb @@ -1,18 +1,22 @@ +# frozen_string_literal: true + require 'spec_helper' RSpec.describe Hydra::ContentNegotiation::ReplacingGraphFinder do let(:graph) { double } - let(:finder) { double(graph: graph, - uri: 'http://127.0.0.1:8986/rest/test/28/01/ph/00/2801ph009', - id: '2801ph009') } + let(:finder) do + double(graph: graph, + uri: 'http://127.0.0.1:8986/rest/test/28/01/ph/00/2801ph009', + id: '2801ph009') + end let(:replacer) { double } subject { described_class.new finder, replacer } - describe "graph" do - it "has the correct base url" do + describe 'graph' do + it 'has the correct base url' do expect(Hydra::ContentNegotiation::FedoraUriReplacer).to receive(:new) - .with(ending_with("/rest/test"), graph, replacer) - .and_return(double(run: nil)) + .with(ending_with('/rest/test'), graph, replacer) + .and_return(double(run: nil)) subject.graph end diff --git a/hydra-core/spec/models/solr_document_spec.rb b/hydra-core/spec/models/solr_document_spec.rb index 59b7ee63e..aff041bbe 100644 --- a/hydra-core/spec/models/solr_document_spec.rb +++ b/hydra-core/spec/models/solr_document_spec.rb @@ -1,8 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' describe SolrDocument do - describe "#to_model" do - + describe '#to_model' do before do class SolrDocumentWithHydraOverride < SolrDocument include Hydra::Solr::Document @@ -10,9 +11,9 @@ class SolrDocumentWithHydraOverride < SolrDocument end # this isn't a great test, but... - it "should try to cast the SolrDocument to the Fedora object" do + it 'should try to cast the SolrDocument to the Fedora object' do expect(ActiveFedora::Base).to receive(:load_instance_from_solr).with('asdfg', kind_of(SolrDocument)) - SolrDocumentWithHydraOverride.new(:id => 'asdfg').to_model + SolrDocumentWithHydraOverride.new(id: 'asdfg').to_model end end end diff --git a/hydra-core/spec/models/user_spec.rb b/hydra-core/spec/models/user_spec.rb index a42778628..1f0c89fa2 100644 --- a/hydra-core/spec/models/user_spec.rb +++ b/hydra-core/spec/models/user_spec.rb @@ -1,26 +1,27 @@ +# frozen_string_literal: true + require 'spec_helper' require 'hydra/shared_spec/group_service_interface' describe User do - - describe "#user_key" do - let(:user) { User.new.tap {|u| u.email = "foo@example.com"} } + describe '#user_key' do + let(:user) { User.new.tap { |u| u.email = 'foo@example.com' } } before do allow(user).to receive(:username).and_return('foo') end subject { user.user_key } - context "by default" do - it "returns email" do + context 'by default' do + it 'returns email' do expect(subject).to eq 'foo@example.com' end end - context "when devise is configured to use the username" do + context 'when devise is configured to use the username' do before do allow(Devise).to receive(:authentication_keys).and_return([:username]) end - it "returns username" do + it 'returns username' do expect(subject).to eq 'foo' end end @@ -31,14 +32,14 @@ it_behaves_like 'a Hydra group_service interface' end - describe "#groups" do + describe '#groups' do let(:user) { described_class.new } let(:mock_service) { double } before do user.group_service = mock_service end subject { user.groups } - it "returns a list of groups" do + it 'returns a list of groups' do expect(mock_service).to receive(:fetch_groups).with(user: user).and_return(['my_group']) expect(subject).to eq ['my_group'] end diff --git a/hydra-core/spec/search_builders/search_builder_spec.rb b/hydra-core/spec/search_builders/search_builder_spec.rb index 6629053fe..791858cb1 100644 --- a/hydra-core/spec/search_builders/search_builder_spec.rb +++ b/hydra-core/spec/search_builders/search_builder_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe SearchBuilder do @@ -11,12 +13,12 @@ search_builder.new(processor_chain, context) end - it "extends classes with the necessary Hydra modules" do + it 'extends classes with the necessary Hydra modules' do expect(described_class.included_modules).to include(Hydra::AccessControlsEnforcement) end - context "when a query is generated" do - it "triggers add_access_controls_to_solr_params" do + context 'when a query is generated' do + it 'triggers add_access_controls_to_solr_params' do expect(subject).to receive(:add_access_controls_to_solr_params) subject.query end diff --git a/hydra-core/spec/spec_helper.rb b/hydra-core/spec/spec_helper.rb index 6d41f43a2..7e1e8859c 100644 --- a/hydra-core/spec/spec_helper.rb +++ b/hydra-core/spec/spec_helper.rb @@ -1,4 +1,6 @@ -ENV["RAILS_ENV"] ||= "test" +# frozen_string_literal: true + +ENV['RAILS_ENV'] ||= 'test' require 'engine_cart' path = File.expand_path(File.join('..', '..', '..', '.internal_test_app'), __FILE__) @@ -16,7 +18,7 @@ def coverage_needed? require 'simplecov' require 'coveralls' - SimpleCov.root(File.expand_path('../../../', __FILE__)) + SimpleCov.root(File.expand_path('../..', __dir__)) SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new( [ SimpleCov::Formatter::HTMLFormatter, diff --git a/hydra-core/spec/support/app/models/sample.rb b/hydra-core/spec/support/app/models/sample.rb index 49b56bccb..8c685b598 100644 --- a/hydra-core/spec/support/app/models/sample.rb +++ b/hydra-core/spec/support/app/models/sample.rb @@ -1,24 +1,26 @@ +# frozen_string_literal: true + class Sample # This is a stub model for testing. cattr_accessor :objects self.objects = {} - def self.create(params={}) + def self.create(_params = {}) obj = Sample.new obj.save obj end - def save() + def save @pid ||= "sample:#{(rand * 1000).to_i}" self.class.objects[@pid] = self end def update_attributes(attributes) attributes.each do |k, v| - instance_variable_set "@#{k.to_s}".to_sym, v - + instance_variable_set "@#{k}".to_sym, v + self.class.send :attr_accessor, k end end @@ -27,7 +29,5 @@ def self.find(pid) objects[pid] end - def pid - @pid - end + attr_reader :pid end diff --git a/hydra-core/spec/support/app/models/solr_document.rb b/hydra-core/spec/support/app/models/solr_document.rb index 28af29682..bfc14649a 100755 --- a/hydra-core/spec/support/app/models/solr_document.rb +++ b/hydra-core/spec/support/app/models/solr_document.rb @@ -1,5 +1,5 @@ -# -*- encoding : utf-8 -*- -class SolrDocument +# frozen_string_literal: true +class SolrDocument include Blacklight::Solr::Document end diff --git a/hydra-core/spec/support/db/migrate/20111101221803_create_searches.rb b/hydra-core/spec/support/db/migrate/20111101221803_create_searches.rb index 5a9467b58..4cd33fbce 100755 --- a/hydra-core/spec/support/db/migrate/20111101221803_create_searches.rb +++ b/hydra-core/spec/support/db/migrate/20111101221803_create_searches.rb @@ -1,8 +1,9 @@ -# -*- encoding : utf-8 -*- +# frozen_string_literal: true + class CreateSearches < ActiveRecord::Migration def self.up create_table :searches do |t| - t.text :query_params + t.text :query_params t.integer :user_id t.timestamps diff --git a/hydra-core/spec/support/matchers/helper_matcher.rb b/hydra-core/spec/support/matchers/helper_matcher.rb index b99d01463..fb581d897 100644 --- a/hydra-core/spec/support/matchers/helper_matcher.rb +++ b/hydra-core/spec/support/matchers/helper_matcher.rb @@ -1,7 +1,7 @@ -RSpec::Matchers.define :be_html_safe do - match do |actual| - actual.html_safe? - end +# frozen_string_literal: true + +RSpec::Matchers.define :be_html_safe do + match(&:html_safe?) failure_message_for_should do |actual| "Expected that #{actual.inspect} would be marked as html safe" end @@ -10,5 +10,3 @@ "Expected that #{actual.inspect} would not be marked as html safe" end end - - diff --git a/hydra-core/spec/support/matchers/solr_matchers.rb b/hydra-core/spec/support/matchers/solr_matchers.rb index 041b5b3b4..e0e4477c7 100644 --- a/hydra-core/spec/support/matchers/solr_matchers.rb +++ b/hydra-core/spec/support/matchers/solr_matchers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Tests whether a solr document has the expected field values set. # Should work with both Solr::Document and Hash objects # Ex. @@ -6,11 +8,11 @@ RSpec::Matchers.define :have_solr_fields do |expected| match do |actual| result = false - if actual.kind_of?(Hash) + if actual.is_a?(Hash) failures = {} expected.each_pair do |field_name, expected_value| - if actual.has_key?(field_name) - expected_values = Array(expected_value) + if actual.key?(field_name) + expected_values = Array(expected_value) if expected_values - actual[field_name] != [] failures.merge!(field_name => expected_value) end @@ -19,25 +21,25 @@ end end result = failures.empty? ? true : false - elsif actual.kind_of?(Solr::Document) + elsif actual.is_a?(Solr::Document) inspected = actual.inspect result = false expected.each_pair do |field_name, field_value| - // - result = inspected.include?("@name=\"#{field_name.to_s}\", @boost=nil, @value=\"#{field_value}\"") || \ - inspected.include?("@name=\"#{field_name.to_s}\", @value=\"#{field_value}\", @boost=nil") || \ - inspected.include?("@value=\"#{field_value}\", @boost=nil, @name=\"#{field_name.to_s}\"") || \ - inspected.include?("@value=\"#{field_value}\", @name=\"#{field_name.to_s}\", @boost=nil") || \ - inspected.include?("@boost=nil, @value=\"#{field_value}\", @name=\"#{field_name.to_s}\"") || \ - inspected.include?("@boost=nil, @name=\"#{field_name.to_s}\", @value=\"#{field_value}\"") + // + result = inspected.include?("@name=\"#{field_name}\", @boost=nil, @value=\"#{field_value}\"") || \ + inspected.include?("@name=\"#{field_name}\", @value=\"#{field_value}\", @boost=nil") || \ + inspected.include?("@value=\"#{field_value}\", @boost=nil, @name=\"#{field_name}\"") || \ + inspected.include?("@value=\"#{field_value}\", @name=\"#{field_name}\", @boost=nil") || \ + inspected.include?("@boost=nil, @value=\"#{field_value}\", @name=\"#{field_name}\"") || \ + inspected.include?("@boost=nil, @name=\"#{field_name}\", @value=\"#{field_value}\"") end end - result + result end - + failure_message_for_should do |actual| - msg = "" - if actual.kind_of?(Hash) + msg = '' + if actual.is_a?(Hash) expected.each_pair do |field_name, expected_value| msg = "expected that the #{field_name} field would contain #{expected_value.inspect}. Got #{actual[field_name].inspect}" end @@ -48,8 +50,8 @@ end failure_message_for_should_not do |actual| - msg = "" - if actual.kind_of?(Hash) + msg = '' + if actual.is_a?(Hash) expected.each_pair do |field_name, expected_value| msg << "expected that the #{field_name} field would not contain #{expected_value.inspect}. Got #{actual[field_name].inspect}" end diff --git a/hydra-core/spec/unit/hydra-head-engine_spec.rb b/hydra-core/spec/unit/hydra-head-engine_spec.rb index 38bd2e52a..d0cad0a54 100644 --- a/hydra-core/spec/unit/hydra-head-engine_spec.rb +++ b/hydra-core/spec/unit/hydra-head-engine_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' describe HydraHead::Engine do - it "should be a subclass of Rails::Engine" do + it 'should be a subclass of Rails::Engine' do expect(HydraHead::Engine.superclass).to eq Rails::Engine end end diff --git a/hydra-core/spec/unit/hydra-head_spec.rb b/hydra-core/spec/unit/hydra-head_spec.rb index a3493944c..942a49ba4 100644 --- a/hydra-core/spec/unit/hydra-head_spec.rb +++ b/hydra-core/spec/unit/hydra-head_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' describe HydraHead do - it "should be valid" do + it 'should be valid' do expect(HydraHead).to be_a(Module) end end diff --git a/hydra-head.gemspec b/hydra-head.gemspec index 81156a8da..f68ccbf31 100644 --- a/hydra-head.gemspec +++ b/hydra-head.gemspec @@ -1,13 +1,14 @@ -# -*- encoding: utf-8 -*- -version = File.read(File.expand_path("../HYDRA_VERSION",__FILE__)).strip +# frozen_string_literal: true + +version = File.read(File.expand_path('HYDRA_VERSION', __dir__)).strip Gem::Specification.new do |s| - s.name = "hydra-head" + s.name = 'hydra-head' s.version = version s.platform = Gem::Platform::RUBY - s.authors = ["Matt Zumwalt, Bess Sadler, Julie Meloni, Naomi Dushay, Jessie Keck, John Scofield, Justin Coyne & many more. See https://github.com/projecthydra/hydra-head/contributors"] - s.email = ["hydra-tech@googlegroups.com"] - s.homepage = "http://projecthydra.org" + s.authors = ['Matt Zumwalt, Bess Sadler, Julie Meloni, Naomi Dushay, Jessie Keck, John Scofield, Justin Coyne & many more. See https://github.com/projecthydra/hydra-head/contributors'] + s.email = ['hydra-tech@googlegroups.com'] + s.homepage = 'http://projecthydra.org' s.summary = 'Hydra-Head Rails Engine' s.description = 'Hydra-Head is a Rails Engine containing the core code for a Hydra application.' s.files = ['lib/hydra/head.rb'] diff --git a/lib/hydra/head.rb b/lib/hydra/head.rb index 060abf446..faef54419 100644 --- a/lib/hydra/head.rb +++ b/lib/hydra/head.rb @@ -1,4 +1,6 @@ -module HydraHead +# frozen_string_literal: true + +module HydraHead require 'hydra-core' def self.version @@ -8,5 +10,4 @@ def self.version def self.root @root ||= File.expand_path(File.dirname(File.dirname(__FILE__))) end - end diff --git a/spec/test_app_templates/app/controllers/downloads_controller.rb b/spec/test_app_templates/app/controllers/downloads_controller.rb index 00f56c88b..08dc72c44 100644 --- a/spec/test_app_templates/app/controllers/downloads_controller.rb +++ b/spec/test_app_templates/app/controllers/downloads_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class DownloadsController < ApplicationController include Hydra::Controller::DownloadBehavior end diff --git a/spec/test_app_templates/lib/generators/test_app_generator.rb b/spec/test_app_templates/lib/generators/test_app_generator.rb index 365f5785d..2aac1eea9 100644 --- a/spec/test_app_templates/lib/generators/test_app_generator.rb +++ b/spec/test_app_templates/lib/generators/test_app_generator.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + require 'rails/generators' class TestAppGenerator < Rails::Generators::Base - source_root File.expand_path("../../../../spec/test_app_templates", __FILE__) + source_root File.expand_path('../../../spec/test_app_templates', __dir__) def install_blacklight # we can skip solr because the activefedora installer will also do it (in the hydra:head generator) @@ -15,10 +17,10 @@ def install_engine end def copy_ip_config - copy_file "config/hydra_ip_range.yml" + copy_file 'config/hydra_ip_range.yml' end def copy_test_controlers - copy_file "app/controllers/downloads_controller.rb" + copy_file 'app/controllers/downloads_controller.rb' end end