personal_access_token.rb 1.99 KB
Newer Older
1 2
# frozen_string_literal: true

3
class PersonalAccessToken < ActiveRecord::Base
4
  include Expirable
5
  include IgnorableColumn
6
  include TokenAuthenticatable
7 8 9

  add_authentication_token_field :token, digest: true
  ignore_column :token
10

11 12
  REDIS_EXPIRY_TIME = 3.minutes

13
  serialize :scopes, Array # rubocop:disable Cop/ActiveRecordSerialize
14

15 16
  belongs_to :user

17 18
  before_save :ensure_token

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

24
  validates :scopes, presence: true
25
  validate :validate_scopes
26

27 28
  after_initialize :set_default_scopes, if: :persisted?

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

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

37 38
  def self.redis_getdel(user_id)
    Gitlab::Redis::SharedState.with do |redis|
39
      encrypted_token = redis.get(redis_shared_state_key(user_id))
40
      redis.del(redis_shared_state_key(user_id))
41 42 43 44 45 46
      begin
        Gitlab::CryptoHelper.aes256_gcm_decrypt(encrypted_token)
      rescue => ex
        logger.warn "Failed to decrypt PersonalAccessToken value stored in Redis for User ##{user_id}: #{ex.class}"
        encrypted_token
      end
47 48 49 50
    end
  end

  def self.redis_store!(user_id, token)
51 52
    encrypted_token = Gitlab::CryptoHelper.aes256_gcm_encrypt(token)

53
    Gitlab::Redis::SharedState.with do |redis|
54
      redis.set(redis_shared_state_key(user_id), encrypted_token, ex: REDIS_EXPIRY_TIME)
55 56 57
    end
  end

58 59
  protected

60
  def validate_scopes
61
    unless revoked || scopes.all? { |scope| Gitlab::Auth.available_scopes.include?(scope.to_sym) }
62
      errors.add :scopes, "can only contain available scopes"
63 64
    end
  end
65 66 67 68

  def set_default_scopes
    self.scopes = Gitlab::Auth::DEFAULT_SCOPES if self.scopes.empty?
  end
69 70 71 72

  def self.redis_shared_state_key(user_id)
    "gitlab:personal_access_token:#{user_id}"
  end
73
end