8784: Fix test for latest firefox.
[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     method = request.request_method
65     if method == 'HEAD'
66       (scopes_allow?(['HEAD', request.path].join(' ')) ||
67        scopes_allow?(['GET', request.path].join(' ')))
68     else
69       scopes_allow?([method, request.path].join(' '))
70     end
71   end
72
73   def logged_attributes
74     super.except 'api_token'
75   end
76
77   def self.default_orders
78     ["#{table_name}.id desc"]
79   end
80
81   protected
82
83   def permission_to_create
84     current_user.andand.is_admin or (current_user.andand.id == self.user_id)
85   end
86
87   def permission_to_update
88     (permission_to_create and
89      not uuid_changed? and
90      not user_id_changed? and
91      not owner_uuid_changed?)
92   end
93
94   def log_update
95     super unless (changed - UNLOGGED_CHANGES).empty?
96   end
97 end