20300: Bypass query cache when re-fetching record for race check.
[arvados.git] / services / api / app / models / authorized_key.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 class AuthorizedKey < ArvadosModel
6   include HasUuid
7   include KindAndEtag
8   include CommonApiTemplate
9   before_create :permission_to_set_authorized_user_uuid
10   before_update :permission_to_set_authorized_user_uuid
11
12   belongs_to :authorized_user, {
13                foreign_key: 'authorized_user_uuid',
14                class_name: 'User',
15                primary_key: 'uuid',
16                optional: true,
17              }
18
19   validate :public_key_must_be_unique
20
21   api_accessible :user, extend: :common do |t|
22     t.add :name
23     t.add :key_type
24     t.add :authorized_user_uuid
25     t.add :public_key
26     t.add :expires_at
27   end
28
29   def permission_to_set_authorized_user_uuid
30     # Anonymous users cannot do anything here
31     return false if !current_user
32
33     # Administrators can attach a key to any user account
34     return true if current_user.is_admin
35
36     # All users can attach keys to their own accounts
37     return true if current_user.uuid == authorized_user_uuid
38
39     # Default = deny.
40     false
41   end
42
43   def public_key_must_be_unique
44     if self.public_key
45       # Valid if no other rows have this public key
46       if self.class.where('uuid != ? and public_key like ?',
47                           uuid || '', "%#{self.public_key}%").any?
48         errors.add(:public_key, "already exists in the database, use a different key.")
49         return false
50       end
51     end
52     return true
53   end
54 end