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