18874: Merge branch 'main' from arvados-workbench2.git
[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   validate :public_key_must_be_unique
19
20   api_accessible :user, extend: :common do |t|
21     t.add :name
22     t.add :key_type
23     t.add :authorized_user_uuid
24     t.add :public_key
25     t.add :expires_at
26   end
27
28   def permission_to_set_authorized_user_uuid
29     # Anonymous users cannot do anything here
30     return false if !current_user
31
32     # Administrators can attach a key to any user account
33     return true if current_user.is_admin
34
35     # All users can attach keys to their own accounts
36     return true if current_user.uuid == authorized_user_uuid
37
38     # Default = deny.
39     false
40   end
41
42   def public_key_must_be_unique
43     if self.public_key
44       # Valid if no other rows have this public key
45       if self.class.where('uuid != ? and public_key like ?',
46                           uuid || '', "%#{self.public_key}%").any?
47         errors.add(:public_key, "already exists in the database, use a different key.")
48         return false
49       end
50     end
51     return true
52   end
53 end