personal_access_token.rb 936 字节
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
  def revoke!
21
    update!(revoked: true)
22
  end
23 24 25 26

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

28 29
  protected

30
  def validate_scopes
31
    unless revoked || scopes.all? { |scope| Gitlab::Auth::AVAILABLE_SCOPES.include?(scope.to_sym) }
32
      errors.add :scopes, "can only contain available scopes"
33 34
    end
  end
35
end