debian-mirror-gitlab/app/services/access_token_validation_service.rb

56 lines
1.4 KiB
Ruby
Raw Normal View History

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
2019-02-15 15:39:39 +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?
2020-07-28 23:09:34 +05:30
EXPIRED
2017-08-17 22:00:37 +05:30
elsif token.revoked?
2020-07-28 23:09:34 +05:30
REVOKED
2017-08-17 22:00:37 +05:30
elsif !self.include_any_scope?(scopes)
2020-07-28 23:09:34 +05:30
INSUFFICIENT_SCOPE
2017-08-17 22:00:37 +05:30
2019-02-15 15:39:39 +05:30
elsif token.respond_to?(:impersonation) &&
token.impersonation &&
!Gitlab.config.gitlab.impersonation_enabled
2020-07-28 23:09:34 +05:30
IMPERSONATION_DISABLED
2019-02-15 15:39:39 +05:30
2017-08-17 22:00:37 +05:30
else
2020-07-28 23:09:34 +05:30
VALID
2017-08-17 22:00:37 +05:30
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.
2019-12-04 20:38:33 +05:30
# https://gitlab.com/gitlab-org/gitlab-foss/merge_requests/12300/#note_33689006
2017-09-10 17:25:29 +05:30
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