hydra-access-controls 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
18
+ *.swp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in hydra-access-controls.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2012 TODO: Write your name
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # Hydra::Access::Controls
2
+
3
+ TODO: Write a gem description
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'hydra-access-controls'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install hydra-access-controls
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Contributing
24
+
25
+ 1. Fork it
26
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
27
+ 3. Commit your changes (`git commit -am 'Added some feature'`)
28
+ 4. Push to the branch (`git push origin my-new-feature`)
29
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
3
+ require 'rspec/core/rake_task'
4
+
5
+ desc 'Default: run specs.'
6
+ task :default => :spec
7
+
8
+ desc "Run specs"
9
+ RSpec::Core::RakeTask.new do |t|
10
+ # if ENV['COVERAGE'] and RUBY_VERSION =~ /^1.8/
11
+ # t.rcov = true
12
+ # t.rcov_opts = %w{--exclude spec\/*,gems\/*,ruby\/* --aggregate coverage.data}
13
+ # end
14
+ end
15
+
16
+
@@ -0,0 +1,25 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/hydra-access-controls/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Justin Coyne"]
6
+ gem.email = ["justin.coyne@yourmediashelf.com"]
7
+ gem.description = %q{Access controls for project hydra}
8
+ gem.summary = %q{Access controls for project hydra}
9
+ gem.homepage = ""
10
+
11
+ gem.files = `git ls-files`.split($\)
12
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
13
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
14
+ gem.name = "hydra-access-controls"
15
+ gem.require_paths = ["lib"]
16
+ gem.version = Hydra::Access::Controls::VERSION
17
+
18
+ gem.add_dependency 'activesupport'
19
+ gem.add_dependency 'active-fedora'
20
+ gem.add_dependency 'cancan'
21
+ gem.add_dependency 'deprecation'
22
+
23
+ gem.add_development_dependency 'rspec'
24
+
25
+ end
data/lib/ability.rb ADDED
@@ -0,0 +1,6 @@
1
+ # Allows you to use CanCan to control access to Models
2
+ require 'cancan'
3
+ class Ability
4
+ include CanCan::Ability
5
+ include Hydra::Ability
6
+ end
@@ -0,0 +1,17 @@
1
+ require 'active_support'
2
+ require 'active-fedora'
3
+ require 'deprecation'
4
+ require "hydra-access-controls/version"
5
+ require 'hydra/model_mixins'
6
+ require 'hydra/datastream'
7
+
8
+ module Hydra
9
+ extend ActiveSupport::Autoload
10
+ autoload :AccessControlsEnforcement
11
+ autoload :AccessControlsEvaluation
12
+ autoload :Ability
13
+ autoload :RoleMapperBehavior
14
+ end
15
+ require 'ability'
16
+ require 'role_mapper'
17
+
@@ -0,0 +1,7 @@
1
+ module Hydra
2
+ module Access
3
+ module Controls
4
+ VERSION = "0.0.1"
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,137 @@
1
+ # this code will move to lib/hydra/access_controls/ability.rb (with the appropriate namespace changes) in Hydra 5.0
2
+ # Code for CanCan access to Hydra models
3
+ module Hydra::Ability
4
+ include Hydra::AccessControlsEnforcement
5
+
6
+ def initialize(user, session=nil)
7
+ user ||= User.new # guest user (not logged in)
8
+ hydra_default_permissions(user, session)
9
+ end
10
+
11
+ ## You can override this method if you are using a different AuthZ (such as LDAP)
12
+ def user_groups(user, session)
13
+ return @user_groups if @user_groups
14
+ @user_groups = RoleMapper.roles(user_key(user)) + default_user_groups
15
+ @user_groups << 'registered' unless user.new_record?
16
+ @user_groups
17
+ end
18
+
19
+ def default_user_groups
20
+ # # everyone is automatically a member of the group 'public'
21
+ ['public']
22
+ end
23
+
24
+
25
+ def hydra_default_permissions(user, session)
26
+ logger.debug("Usergroups are " + user_groups(user, session).inspect)
27
+ if Deprecation.silence(Hydra::SuperuserAttributes) { user.is_being_superuser?(session) }
28
+ can :manage, :all
29
+ else
30
+ edit_permissions(user, session)
31
+ read_permissions(user, session)
32
+ custom_permissions(user, session)
33
+ end
34
+ end
35
+
36
+ def edit_permissions(user, session)
37
+ can :edit, String do |pid|
38
+ test_edit(pid, user, session)
39
+ end
40
+
41
+ can :edit, ActiveFedora::Base do |obj|
42
+ test_edit(obj.pid, user, session)
43
+ end
44
+
45
+ can :edit, SolrDocument do |obj|
46
+ @permissions_solr_document = obj
47
+ test_edit(obj.id, user, session)
48
+ end
49
+
50
+ end
51
+
52
+ def read_permissions(user, session)
53
+ can :read, String do |pid|
54
+ test_read(pid, user, session)
55
+ end
56
+
57
+ can :read, ActiveFedora::Base do |obj|
58
+ test_read(obj.pid, user, session)
59
+ end
60
+
61
+ can :read, SolrDocument do |obj|
62
+ @permissions_solr_document = obj
63
+ test_read(obj.id, user, session)
64
+ end
65
+ end
66
+
67
+
68
+ ## Override custom permissions in your own app to add more permissions beyond what is defined by default.
69
+ def custom_permissions(user, session)
70
+ end
71
+
72
+ protected
73
+
74
+ def permissions_doc(pid)
75
+ return @permissions_solr_document if @permissions_solr_document
76
+ response, @permissions_solr_document = get_permissions_solr_response_for_doc_id(pid)
77
+ @permissions_solr_document
78
+ end
79
+
80
+
81
+ def test_edit(pid, user, session)
82
+ permissions_doc(pid)
83
+ logger.debug("CANCAN Checking edit permissions for user: #{user}")
84
+ group_intersection = user_groups(user, session) & edit_groups
85
+ result = !group_intersection.empty? || edit_persons.include?(user_key(user))
86
+ logger.debug("CANCAN decision: #{result}")
87
+ result
88
+ end
89
+
90
+ def test_read(pid, user, session)
91
+ permissions_doc(pid)
92
+ logger.debug("CANCAN Checking edit permissions for user: #{user}")
93
+ group_intersection = user_groups(user, session) & read_groups
94
+ result = !group_intersection.empty? || read_persons.include?(user_key(user))
95
+ logger.debug("CANCAN decision: #{result}")
96
+ result
97
+ end
98
+
99
+ def edit_groups
100
+ edit_group_field = Hydra.config[:permissions][:edit][:group]
101
+ eg = ((@permissions_solr_document == nil || @permissions_solr_document.fetch(edit_group_field,nil) == nil) ? [] : @permissions_solr_document.fetch(edit_group_field,nil))
102
+ logger.debug("edit_groups: #{eg.inspect}")
103
+ return eg
104
+ end
105
+
106
+ # edit implies read, so read_groups is the union of edit and read groups
107
+ def read_groups
108
+ read_group_field = Hydra.config[:permissions][:read][:group]
109
+ rg = edit_groups | ((@permissions_solr_document == nil || @permissions_solr_document.fetch(read_group_field,nil) == nil) ? [] : @permissions_solr_document.fetch(read_group_field,nil))
110
+ logger.debug("read_groups: #{rg.inspect}")
111
+ return rg
112
+ end
113
+
114
+ def edit_persons
115
+ edit_person_field = Hydra.config[:permissions][:edit][:individual]
116
+ ep = ((@permissions_solr_document == nil || @permissions_solr_document.fetch(edit_person_field,nil) == nil) ? [] : @permissions_solr_document.fetch(edit_person_field,nil))
117
+ logger.debug("edit_persons: #{ep.inspect}")
118
+ return ep
119
+ end
120
+
121
+ # edit implies read, so read_persons is the union of edit and read persons
122
+ def read_persons
123
+ read_individual_field = Hydra.config[:permissions][:read][:individual]
124
+ rp = edit_persons | ((@permissions_solr_document == nil || @permissions_solr_document.fetch(read_individual_field,nil) == nil) ? [] : @permissions_solr_document.fetch(read_individual_field,nil))
125
+ logger.debug("read_persons: #{rp.inspect}")
126
+ return rp
127
+ end
128
+
129
+
130
+ # get the currently configured user identifier. Can be overridden to return whatever (ie. login, email, etc)
131
+ # defaults to using whatever you have set as the Devise authentication_key
132
+ def user_key(user)
133
+ user.send(Devise.authentication_keys.first)
134
+ end
135
+
136
+
137
+ end
@@ -0,0 +1,234 @@
1
+ # will move to lib/hydra/access_control folder/namespace in release 5.x
2
+ module Hydra::AccessControlsEnforcement
3
+
4
+ def self.included(klass)
5
+ klass.send(:include, Hydra::AccessControlsEvaluation)
6
+ end
7
+
8
+ #
9
+ # Access Controls Enforcement Filters
10
+ #
11
+
12
+ # Controller "before" filter that delegates enforcement based on the controller action
13
+ # Action-specific implementations are enforce_index_permissions, enforce_show_permissions, etc.
14
+ # @param [Hash] opts (optional, not currently used)
15
+ #
16
+ # @example
17
+ # class CatalogController < ApplicationController
18
+ # before_filter :enforce_access_controls
19
+ # end
20
+ def enforce_access_controls(opts={})
21
+ controller_action = params[:action].to_s
22
+ controller_action = "edit" if params[:action] == "destroy"
23
+ delegate_method = "enforce_#{controller_action}_permissions"
24
+ if self.respond_to?(delegate_method.to_sym, true)
25
+ self.send(delegate_method.to_sym)
26
+ else
27
+ true
28
+ end
29
+ end
30
+
31
+
32
+ #
33
+ # Solr integration
34
+ #
35
+
36
+ # returns a params hash with the permissions info for a single solr document
37
+ # If the id arg is nil, then the value is fetched from params[:id]
38
+ # This method is primary called by the get_permissions_solr_response_for_doc_id method.
39
+ # Modeled on Blacklight::SolrHelper.solr_doc_params
40
+ # @param [String] id of the documetn to retrieve
41
+ def permissions_solr_doc_params(id=nil)
42
+ id ||= params[:id]
43
+ # just to be consistent with the other solr param methods:
44
+ {
45
+ :qt => :permissions,
46
+ :id => id # this assumes the document request handler will map the 'id' param to the unique key field
47
+ }
48
+ end
49
+
50
+ # a solr query method
51
+ # retrieve a solr document, given the doc id
52
+ # Modeled on Blacklight::SolrHelper.get_permissions_solr_response_for_doc_id
53
+ # @param [String] id of the documetn to retrieve
54
+ # @param [Hash] extra_controller_params (optional)
55
+ def get_permissions_solr_response_for_doc_id(id=nil, extra_controller_params={})
56
+ raise Blacklight::Exceptions::InvalidSolrID.new("The application is trying to retrieve permissions without specifying an asset id") if id.nil?
57
+ solr_response = Blacklight.solr.find permissions_solr_doc_params(id).merge(extra_controller_params)
58
+ raise Blacklight::Exceptions::InvalidSolrID.new("The solr permissions search handler didn't return anything for id \"#{id}\"") if solr_response.docs.empty?
59
+ document = SolrDocument.new(solr_response.docs.first, solr_response)
60
+ [solr_response, document]
61
+ end
62
+
63
+ # Loads permissions info into @permissions_solr_response and @permissions_solr_document
64
+ def load_permissions_from_solr(id=params[:id], extra_controller_params={})
65
+ unless !@permissions_solr_document.nil? && !@permissions_solr_response.nil?
66
+ @permissions_solr_response, @permissions_solr_document = get_permissions_solr_response_for_doc_id(id, extra_controller_params)
67
+ end
68
+ end
69
+
70
+ private
71
+
72
+ # If someone hits the show action while their session's viewing_context is in edit mode,
73
+ # this will redirect them to the edit action.
74
+ # If they do not have sufficient privileges to edit documents, it will silently switch their session to browse mode.
75
+ def enforce_viewing_context_for_show_requests
76
+ if params[:viewing_context] == "browse"
77
+ session[:viewing_context] = params[:viewing_context]
78
+ elsif session[:viewing_context] == "edit"
79
+ if can? :edit, params[:id]
80
+ logger.debug("enforce_viewing_context_for_show_requests redirecting to edit")
81
+ if params[:files]
82
+ redirect_to :action=>:edit, :files=>true
83
+ else
84
+ redirect_to :action=>:edit
85
+ end
86
+ else
87
+ session[:viewing_context] = "browse"
88
+ end
89
+ end
90
+ end
91
+
92
+ #
93
+ # Action-specific enforcement
94
+ #
95
+
96
+ # Controller "before" filter for enforcing access controls on show actions
97
+ # @param [Hash] opts (optional, not currently used)
98
+ def enforce_show_permissions(opts={})
99
+ load_permissions_from_solr
100
+ unless @permissions_solr_document['access_t'] && (@permissions_solr_document['access_t'].first == "public" || @permissions_solr_document['access_t'].first == "Public")
101
+ if @permissions_solr_document["embargo_release_date_dt"]
102
+ embargo_date = Date.parse(@permissions_solr_document["embargo_release_date_dt"].split(/T/)[0])
103
+ if embargo_date > Date.parse(Time.now.to_s)
104
+ ### Assuming we're using devise and have only one authentication key
105
+ unless current_user && can?(:edit, params[:id])
106
+ raise Hydra::AccessDenied.new("This item is under embargo. You do not have sufficient access privileges to read this document.", :edit, params[:id])
107
+ end
108
+ end
109
+ end
110
+ unless can? :read, params[:id]
111
+ raise Hydra::AccessDenied.new("You do not have sufficient access privileges to read this document, which has been marked private.", :read, params[:id])
112
+ end
113
+ end
114
+ end
115
+
116
+ # Controller "before" filter for enforcing access controls on edit actions
117
+ # @param [Hash] opts (optional, not currently used)
118
+ def enforce_edit_permissions(opts={})
119
+ logger.debug("Enforcing edit permissions")
120
+ load_permissions_from_solr
121
+ if !can? :edit, params[:id]
122
+ session[:viewing_context] = "browse"
123
+ raise Hydra::AccessDenied.new("You do not have sufficient privileges to edit this document. You have been redirected to the read-only view.", :edit, params[:id])
124
+ else
125
+ session[:viewing_context] = "edit"
126
+ end
127
+ end
128
+
129
+ ## proxies to enforce_edit_permssions. This method is here for you to override
130
+ def enforce_update_permissions(opts={})
131
+ enforce_edit_permissions(opts)
132
+ end
133
+
134
+ ## proxies to enforce_edit_permssions. This method is here for you to override
135
+ def enforce_delete_permissions(opts={})
136
+ enforce_edit_permissions(opts)
137
+ end
138
+
139
+ # Controller "before" filter for enforcing access controls on index actions
140
+ # Currently does nothing, instead relies on
141
+ # @param [Hash] opts (optional, not currently used)
142
+ def enforce_index_permissions(opts={})
143
+ # Do nothing. Relies on enforce_search_permissions being included in the Controller's solr_search_params_logic
144
+ return true
145
+ end
146
+
147
+ #
148
+ # Solr query modifications
149
+ #
150
+
151
+ # Set solr_parameters to enforce appropriate permissions
152
+ # * Applies a lucene query to the solr :q parameter for gated discovery
153
+ # * Uses public_qt search handler if user does not have "read" permissions
154
+ # @param solr_parameters the current solr parameters
155
+ # @param user_parameters the current user-subitted parameters
156
+ #
157
+ # @example This method should be added to your Catalog Controller's solr_search_params_logic
158
+ # class CatalogController < ApplicationController
159
+ # include Hydra::Catalog
160
+ # CatalogController.solr_search_params_logic << :add_access_controls_to_solr_params
161
+ # end
162
+ def add_access_controls_to_solr_params(solr_parameters, user_parameters)
163
+ apply_gated_discovery(solr_parameters, user_parameters)
164
+ end
165
+
166
+
167
+ # Which permission levels (logical OR) will grant you the ability to discover documents in a search.
168
+ # Override this method if you want it to be something other than the default
169
+ def discovery_permissions
170
+ ["edit","discover","read"]
171
+ end
172
+
173
+ # Contrller before filter that sets up access-controlled lucene query in order to provide gated discovery behavior
174
+ # @param solr_parameters the current solr parameters
175
+ # @param user_parameters the current user-subitted parameters
176
+ def apply_gated_discovery(solr_parameters, user_parameters)
177
+ solr_parameters[:fq] ||= []
178
+ # Grant access to public content
179
+ permission_types = discovery_permissions
180
+ user_access_filters = []
181
+
182
+ permission_types.each do |type|
183
+ user_access_filters << "#{type}_access_group_t:public"
184
+ end
185
+
186
+ # Grant access based on user id & role
187
+ unless current_user.nil?
188
+ # for roles
189
+ ::RoleMapper.roles(user_key).each_with_index do |role, i|
190
+ permission_types.each do |type|
191
+ user_access_filters << "#{type}_access_group_t:#{role}"
192
+ end
193
+ end
194
+ # for individual person access
195
+ permission_types.each do |type|
196
+ user_access_filters << "#{type}_access_person_t:#{user_key}"
197
+ end
198
+ if Deprecation.silence(Hydra::SuperuserAttributes) { current_user.is_being_superuser?(session) }
199
+ permission_types.each do |type|
200
+ user_access_filters << "#{type}_access_person_t:[* TO *]"
201
+ end
202
+ end
203
+
204
+ # Enforcing Embargo at Query time has been disabled.
205
+ # If you want to do this, set up your own solr_search_params before_filter that injects the appropriate :fq constraints for a field that expresses your objects' embargo status.
206
+ #
207
+ # include docs in results if the embargo date is NOT in the future OR if the current user is depositor
208
+ # embargo_query = "(NOT embargo_release_date_dt:[NOW TO *]) OR depositor_t:#{user_key}"
209
+ # embargo_query = "(NOT embargo_release_date_dt:[NOW TO *]) OR (embargo_release_date_dt:[NOW TO *] AND depositor_t:#{user_key}) AND NOT (NOT depositor_t:#{user_key} AND embargo_release_date_dt:[NOW TO *])"
210
+ # solr_parameters[:fq] << embargo_query
211
+ end
212
+ solr_parameters[:fq] << user_access_filters.join(" OR ")
213
+ logger.debug("Solr parameters: #{ solr_parameters.inspect }")
214
+ end
215
+
216
+
217
+ # proxy for {enforce_index_permissions}
218
+ def enforce_search_permissions
219
+ enforce_index_permissions
220
+ end
221
+
222
+ # proxy for {enforce_show_permissions}
223
+ def enforce_read_permissions
224
+ enforce_show_permissions
225
+ end
226
+
227
+ # This filters out objects that you want to exclude from search results. By default it only excludes FileAssets
228
+ # @param solr_parameters the current solr parameters
229
+ # @param user_parameters the current user-subitted parameters
230
+ def exclude_unwanted_models(solr_parameters, user_parameters)
231
+ solr_parameters[:fq] ||= []
232
+ solr_parameters[:fq] << "-has_model_s:\"info:fedora/afmodel:FileAsset\""
233
+ end
234
+ end