BigW Consortium Gitlab

personal_access_token.rb 1.07 KB
Newer Older
1
class PersonalAccessToken < ActiveRecord::Base
2
  include Expirable
3 4 5
  include TokenAuthenticatable
  add_authentication_token_field :token

6
  serialize :scopes, Array # rubocop:disable Cop/ActiveRecordSerialize
7

8 9
  belongs_to :user

10 11
  before_save :ensure_token

12
  scope :active, -> { where("revoked = false AND (expires_at >= NOW() OR expires_at IS NULL)") }
13
  scope :inactive, -> { where("revoked = true OR expires_at < NOW()") }
14 15
  scope :with_impersonation, -> { where(impersonation: true) }
  scope :without_impersonation, -> { where(impersonation: false) }
16

17
  validates :scopes, presence: true
18
  validate :validate_scopes
19

20 21
  after_initialize :set_default_scopes, if: :persisted?

22
  def revoke!
23
    update!(revoked: true)
24
  end
25 26 27 28

  def active?
    !revoked? && !expired?
  end
29

30 31
  protected

32
  def validate_scopes
33
    unless revoked || scopes.all? { |scope| Gitlab::Auth.available_scopes.include?(scope.to_sym) }
34
      errors.add :scopes, "can only contain available scopes"
35 36
    end
  end
37 38 39 40

  def set_default_scopes
    self.scopes = Gitlab::Auth::DEFAULT_SCOPES if self.scopes.empty?
  end
41
end