2018-11-18 11:00:15 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
class AccessTokenValidationService
|
|
|
|
# Results:
|
|
|
|
VALID = :valid
|
|
|
|
EXPIRED = :expired
|
|
|
|
REVOKED = :revoked
|
|
|
|
INSUFFICIENT_SCOPE = :insufficient_scope
|
2018-12-23 12:14:25 +05:30
|
|
|
IMPERSONATION_DISABLED = :impersonation_disabled
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
attr_reader :token, :request
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
def initialize(token, request: nil)
|
2017-08-17 22:00:37 +05:30
|
|
|
@token = token
|
2017-09-10 17:25:29 +05:30
|
|
|
@request = request
|
2017-08-17 22:00:37 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
def validate(scopes: [])
|
|
|
|
if token.expired?
|
|
|
|
return EXPIRED
|
|
|
|
|
|
|
|
elsif token.revoked?
|
|
|
|
return REVOKED
|
|
|
|
|
|
|
|
elsif !self.include_any_scope?(scopes)
|
|
|
|
return INSUFFICIENT_SCOPE
|
|
|
|
|
2018-12-23 12:14:25 +05:30
|
|
|
elsif token.respond_to?(:impersonation) &&
|
|
|
|
token.impersonation &&
|
|
|
|
!Gitlab.config.gitlab.impersonation_enabled
|
|
|
|
return IMPERSONATION_DISABLED
|
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
else
|
|
|
|
return VALID
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# True if the token's scope contains any of the passed scopes.
|
2017-09-10 17:25:29 +05:30
|
|
|
def include_any_scope?(required_scopes)
|
|
|
|
if required_scopes.blank?
|
2017-08-17 22:00:37 +05:30
|
|
|
true
|
|
|
|
else
|
2017-09-10 17:25:29 +05:30
|
|
|
# We're comparing each required_scope against all token scopes, which would
|
|
|
|
# take quadratic time. This consideration is irrelevant here because of the
|
|
|
|
# small number of records involved.
|
|
|
|
# https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/12300/#note_33689006
|
|
|
|
token_scopes = token.scopes.map(&:to_sym)
|
|
|
|
|
|
|
|
required_scopes.any? do |scope|
|
2018-03-17 18:26:18 +05:30
|
|
|
scope = API::Scope.new(scope) unless scope.is_a?(API::Scope)
|
|
|
|
scope.sufficient?(token_scopes, request)
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|
2017-08-17 22:00:37 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|