Read about our upcoming Code of Conduct on this issue

This instance will be upgraded to Heptapod 0.28.1 on 2022-01-26 at 16:00 UTC+1 (a few minutes of down time)

deploy_token.rb 1.25 KB
Newer Older
1
2
3
4
5
class DeployToken < ActiveRecord::Base
  include Expirable
  include TokenAuthenticatable
  add_authentication_token_field :token

Mayra Cabrera's avatar
Mayra Cabrera committed
6
  AVAILABLE_SCOPES = %i(read_repository read_registry).freeze
7

Mayra Cabrera's avatar
Mayra Cabrera committed
8
9
  has_many :project_deploy_tokens, inverse_of: :deploy_token
  has_many :projects, through: :project_deploy_tokens
10

Mayra Cabrera's avatar
Mayra Cabrera committed
11
  validate :ensure_at_least_one_scope
12
13
  before_save :ensure_token

Mayra Cabrera's avatar
Mayra Cabrera committed
14
15
  accepts_nested_attributes_for :project_deploy_tokens

16
  scope :active, -> { where("revoked = false AND (expires_at >= NOW() OR expires_at IS NULL)") }
Mayra Cabrera's avatar
Mayra Cabrera committed
17
18
  scope :read_repository, -> { where(read_repository: true) }
  scope :read_registry, -> { where(read_registry: true) }
19

Mayra Cabrera's avatar
Mayra Cabrera committed
20
21
  def self.redis_shared_state_key(user_id)
    "gitlab:deploy_token:user_#{user_id}"
22
23
  end

Mayra Cabrera's avatar
Mayra Cabrera committed
24
25
  def revoke!
    update!(revoked: true)
26
  end
27
28
29
30
31

  def active?
    !revoked
  end

Mayra Cabrera's avatar
Mayra Cabrera committed
32
33
34
35
  def scopes
    AVAILABLE_SCOPES.select { |token_scope| send("#{token_scope}") }  # rubocop:disable GitlabSecurity/PublicSend
  end

36
  def username
37
38
39
    "gitlab+deploy-token-#{id}"
  end

Mayra Cabrera's avatar
Mayra Cabrera committed
40
41
42
43
44
45
46
47
48
49
50
51
  def has_access_to?(requested_project)
    self.projects.first == requested_project
  end

  def project
    projects.first
  end

  private

  def ensure_at_least_one_scope
    errors.add(:base, "Scopes can't be blank") unless read_repository || read_registry
52
  end
53
end