summaryrefslogtreecommitdiff
path: root/app/models/personal_access_token.rb
blob: e8b000ddad6247f05dbf31885fee025eadfffaf2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class PersonalAccessToken < ActiveRecord::Base
  include Expirable
  include TokenAuthenticatable
  add_authentication_token_field :token

  serialize :scopes, Array

  belongs_to :user

  before_save :ensure_token

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

  validates :scopes, presence: true
  validate :validate_api_scopes

  def revoke!
    self.revoked = true
    self.save
  end

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

  protected

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