Fix 2.4.2 upgrade notes formatting refs #19330
[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_key = SSHKey.valid_ssh_public_key? self.public_key
41
42       if not valid_key
43         errors.add(:public_key, "does not appear to be a valid ssh-rsa or dsa public key")
44       else
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     end
53     return true
54   end
55 end