personal_access_token.rb 932 Bytes
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 18
  validates :scopes, presence: true
  validate :validate_api_scopes
19

20 21 22 23
  def revoke!
    self.revoked = true
    self.save
  end
24 25 26 27

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

29 30
  protected

31 32
  def validate_api_scopes
    unless scopes.all? { |scope| Gitlab::Auth::API_SCOPES.include?(scope.to_sym) }
33 34 35
      errors.add :scopes, "can only contain API scopes"
    end
  end
36
end