Adds checking for request body options that are both valid JSON and readable files
[arvados.git] / services / api / app / models / api_client_authorization.rb
1 class ApiClientAuthorization < ArvadosModel
2   include HasUuid
3   include KindAndEtag
4   include CommonApiTemplate
5
6   belongs_to :api_client
7   belongs_to :user
8   after_initialize :assign_random_api_token
9   serialize :scopes, Array
10
11   api_accessible :user, extend: :common do |t|
12     t.add :owner_uuid
13     t.add :user_id
14     t.add :api_client_id
15     t.add :api_token
16     t.add :created_by_ip_address
17     t.add :default_owner_uuid
18     t.add :expires_at
19     t.add :last_used_at
20     t.add :last_used_by_ip_address
21     t.add :scopes
22   end
23
24   UNLOGGED_CHANGES = ['last_used_at', 'last_used_by_ip_address', 'updated_at']
25
26   def assign_random_api_token
27     self.api_token ||= rand(2**256).to_s(36)
28   end
29
30   def owner_uuid
31     self.user.andand.uuid
32   end
33   def owner_uuid_was
34     self.user_id_changed? ? User.where(id: self.user_id_was).first.andand.uuid : self.user.andand.uuid
35   end
36   def owner_uuid_changed?
37     self.user_id_changed?
38   end
39
40   def modified_by_client_uuid
41     nil
42   end
43   def modified_by_client_uuid=(x) end
44
45   def modified_by_user_uuid
46     nil
47   end
48   def modified_by_user_uuid=(x) end
49
50   def modified_at
51     nil
52   end
53   def modified_at=(x) end
54
55   def scopes_allow?(req_s)
56     scopes.each do |scope|
57       return true if (scope == 'all') or (scope == req_s) or
58         ((scope.end_with? '/') and (req_s.start_with? scope))
59     end
60     false
61   end
62
63   def scopes_allow_request?(request)
64     scopes_allow? [request.request_method, request.path].join(' ')
65   end
66
67   def logged_attributes
68     attrs = attributes.dup
69     attrs.delete('api_token')
70     attrs
71   end
72
73   def self.default_orders
74     ["#{table_name}.id desc"]
75   end
76
77   protected
78
79   def permission_to_create
80     current_user.andand.is_admin or (current_user.andand.id == self.user_id)
81   end
82
83   def permission_to_update
84     (permission_to_create and
85      not self.user_id_changed? and
86      not self.owner_uuid_changed?)
87   end
88
89   def log_update
90     super unless (changed - UNLOGGED_CHANGES).empty?
91   end
92 end