2016-06-22 15:30:34 +05:30
|
|
|
class PersonalAccessToken < ActiveRecord::Base
|
2017-08-17 22:00:37 +05:30
|
|
|
include Expirable
|
2016-06-22 15:30:34 +05:30
|
|
|
include TokenAuthenticatable
|
|
|
|
add_authentication_token_field :token
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
REDIS_EXPIRY_TIME = 3.minutes
|
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
serialize :scopes, Array # rubocop:disable Cop/ActiveRecordSerialize
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2016-06-22 15:30:34 +05:30
|
|
|
belongs_to :user
|
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
before_save :ensure_token
|
|
|
|
|
|
|
|
scope :active, -> { where("revoked = false AND (expires_at >= NOW() OR expires_at IS NULL)") }
|
2016-06-22 15:30:34 +05:30
|
|
|
scope :inactive, -> { where("revoked = true OR expires_at < NOW()") }
|
2017-08-17 22:00:37 +05:30
|
|
|
scope :with_impersonation, -> { where(impersonation: true) }
|
|
|
|
scope :without_impersonation, -> { where(impersonation: false) }
|
2016-06-22 15:30:34 +05:30
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
validates :scopes, presence: true
|
2017-09-10 17:25:29 +05:30
|
|
|
validate :validate_scopes
|
2016-06-22 15:30:34 +05:30
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
after_initialize :set_default_scopes, if: :persisted?
|
|
|
|
|
2016-06-22 15:30:34 +05:30
|
|
|
def revoke!
|
2017-09-10 17:25:29 +05:30
|
|
|
update!(revoked: true)
|
2016-06-22 15:30:34 +05:30
|
|
|
end
|
2017-08-17 22:00:37 +05:30
|
|
|
|
|
|
|
def active?
|
|
|
|
!revoked? && !expired?
|
|
|
|
end
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
def self.redis_getdel(user_id)
|
|
|
|
Gitlab::Redis::SharedState.with do |redis|
|
|
|
|
token = redis.get(redis_shared_state_key(user_id))
|
|
|
|
redis.del(redis_shared_state_key(user_id))
|
|
|
|
token
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.redis_store!(user_id, token)
|
|
|
|
Gitlab::Redis::SharedState.with do |redis|
|
|
|
|
redis.set(redis_shared_state_key(user_id), token, ex: REDIS_EXPIRY_TIME)
|
|
|
|
token
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
protected
|
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
def validate_scopes
|
2018-03-17 18:26:18 +05:30
|
|
|
unless revoked || scopes.all? { |scope| Gitlab::Auth.available_scopes.include?(scope.to_sym) }
|
2017-09-10 17:25:29 +05:30
|
|
|
errors.add :scopes, "can only contain available scopes"
|
2017-08-17 22:00:37 +05:30
|
|
|
end
|
|
|
|
end
|
2018-03-17 18:26:18 +05:30
|
|
|
|
|
|
|
def set_default_scopes
|
|
|
|
self.scopes = Gitlab::Auth::DEFAULT_SCOPES if self.scopes.empty?
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.redis_shared_state_key(user_id)
|
|
|
|
"gitlab:personal_access_token:#{user_id}"
|
|
|
|
end
|
2016-06-22 15:30:34 +05:30
|
|
|
end
|