deploy_token.rb 1.77 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5
class DeployToken < ActiveRecord::Base
  include Expirable
  include TokenAuthenticatable
6
  include PolicyActor
7
  include Gitlab::Utils::StrongMemoize
8 9
  add_authentication_token_field :token

10
  AVAILABLE_SCOPES = %i(read_repository read_registry).freeze
11
  GITLAB_DEPLOY_TOKEN_NAME = 'gitlab-deploy-token'.freeze
12

13
  default_value_for(:expires_at) { Forever.date }
14

15
  has_many :project_deploy_tokens, inverse_of: :deploy_token
16
  has_many :projects, through: :project_deploy_tokens
17

18
  validate :ensure_at_least_one_scope
19 20
  before_save :ensure_token

21 22
  accepts_nested_attributes_for :project_deploy_tokens

23
  scope :active, -> { where("revoked = false AND expires_at >= NOW()") }
24

25 26 27 28
  def self.gitlab_deploy_token
    active.find_by(name: GITLAB_DEPLOY_TOKEN_NAME)
  end

29 30
  def revoke!
    update!(revoked: true)
31
  end
32 33

  def active?
34
    !revoked && !expired?
35 36
  end

37
  def scopes
38
    AVAILABLE_SCOPES.select { |token_scope| read_attribute(token_scope) }
39 40
  end

41
  def username
42 43 44
    "gitlab+deploy-token-#{id}"
  end

45
  def has_access_to?(requested_project)
46
    active? && project == requested_project
47 48
  end

49 50 51
  # This is temporal. Currently we limit DeployToken
  # to a single project, later we're going to extend
  # that to be for multiple projects and namespaces.
52
  def project
53 54 55
    strong_memoize(:project) do
      projects.first
    end
56 57
  end

58 59 60 61 62 63 64 65 66
  def expires_at
    expires_at = read_attribute(:expires_at)
    expires_at != Forever.date ? expires_at : nil
  end

  def expires_at=(value)
    write_attribute(:expires_at, value.presence || Forever.date)
  end

67 68
  private

69 70 71 72 73 74
  def expired?
    return false unless expires_at

    expires_at < Date.today
  end

75 76
  def ensure_at_least_one_scope
    errors.add(:base, "Scopes can't be blank") unless read_repository || read_registry
77
  end
78
end