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