2017-02-28 07:34:06 -05:00
|
|
|
class AccessTokenValidationService
|
2016-11-22 04:04:23 -05:00
|
|
|
# Results:
|
|
|
|
VALID = :valid
|
|
|
|
EXPIRED = :expired
|
|
|
|
REVOKED = :revoked
|
|
|
|
INSUFFICIENT_SCOPE = :insufficient_scope
|
|
|
|
|
2017-06-20 04:27:45 -04:00
|
|
|
attr_reader :token, :request
|
2017-02-28 07:34:06 -05:00
|
|
|
|
2017-06-21 05:22:39 -04:00
|
|
|
def initialize(token, request: nil)
|
2017-02-28 07:34:06 -05:00
|
|
|
@token = token
|
2017-06-20 04:27:45 -04:00
|
|
|
@request = request
|
2017-02-28 07:34:06 -05:00
|
|
|
end
|
|
|
|
|
2016-12-05 12:25:53 -05:00
|
|
|
def validate(scopes: [])
|
|
|
|
if token.expired?
|
|
|
|
return EXPIRED
|
2016-11-22 04:04:23 -05:00
|
|
|
|
2016-12-05 12:25:53 -05:00
|
|
|
elsif token.revoked?
|
|
|
|
return REVOKED
|
2016-11-22 04:04:23 -05:00
|
|
|
|
2016-12-05 12:25:53 -05:00
|
|
|
elsif !self.include_any_scope?(scopes)
|
|
|
|
return INSUFFICIENT_SCOPE
|
2016-11-22 04:04:23 -05:00
|
|
|
|
2016-12-05 12:25:53 -05:00
|
|
|
else
|
|
|
|
return VALID
|
2016-11-22 04:04:23 -05:00
|
|
|
end
|
2016-12-05 12:25:53 -05:00
|
|
|
end
|
2016-11-22 04:04:23 -05:00
|
|
|
|
2016-12-05 12:25:53 -05:00
|
|
|
# True if the token's scope contains any of the passed scopes.
|
2017-06-28 03:12:23 -04:00
|
|
|
def include_any_scope?(required_scopes)
|
|
|
|
if required_scopes.blank?
|
2016-12-05 12:25:53 -05:00
|
|
|
true
|
|
|
|
else
|
2017-06-28 03:12:23 -04:00
|
|
|
# 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)
|
2017-06-30 03:32:25 -04:00
|
|
|
|
|
|
|
required_scopes.any? do |scope|
|
2017-10-12 08:38:39 -04:00
|
|
|
scope = API::Scope.new(scope) unless scope.is_a?(API::Scope)
|
|
|
|
scope.sufficient?(token_scopes, request)
|
2017-06-30 03:32:25 -04:00
|
|
|
end
|
2016-11-22 04:04:23 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|