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