2017-02-28 12:34:06 +00:00
|
|
|
class AccessTokenValidationService
|
2016-11-22 09:04:23 +00:00
|
|
|
# Results:
|
|
|
|
VALID = :valid
|
|
|
|
EXPIRED = :expired
|
|
|
|
REVOKED = :revoked
|
|
|
|
INSUFFICIENT_SCOPE = :insufficient_scope
|
|
|
|
|
2017-06-20 08:27:45 +00:00
|
|
|
attr_reader :token, :request
|
2017-02-28 12:34:06 +00:00
|
|
|
|
2017-06-21 09:22:39 +00:00
|
|
|
def initialize(token, request: nil)
|
2017-02-28 12:34:06 +00:00
|
|
|
@token = token
|
2017-06-20 08:27:45 +00:00
|
|
|
@request = request
|
2017-02-28 12:34:06 +00:00
|
|
|
end
|
|
|
|
|
2016-12-05 17:25:53 +00:00
|
|
|
def validate(scopes: [])
|
|
|
|
if token.expired?
|
|
|
|
return EXPIRED
|
2016-11-22 09:04:23 +00:00
|
|
|
|
2016-12-05 17:25:53 +00:00
|
|
|
elsif token.revoked?
|
|
|
|
return REVOKED
|
2016-11-22 09:04:23 +00:00
|
|
|
|
2016-12-05 17:25:53 +00:00
|
|
|
elsif !self.include_any_scope?(scopes)
|
|
|
|
return INSUFFICIENT_SCOPE
|
2016-11-22 09:04:23 +00:00
|
|
|
|
2016-12-05 17:25:53 +00:00
|
|
|
else
|
|
|
|
return VALID
|
2016-11-22 09:04:23 +00:00
|
|
|
end
|
2016-12-05 17:25:53 +00:00
|
|
|
end
|
2016-11-22 09:04:23 +00:00
|
|
|
|
2016-12-05 17:25:53 +00:00
|
|
|
# True if the token's scope contains any of the passed scopes.
|
|
|
|
def include_any_scope?(scopes)
|
|
|
|
if scopes.blank?
|
|
|
|
true
|
|
|
|
else
|
2017-06-20 08:27:45 +00:00
|
|
|
# Remove any scopes whose `if` condition does not return `true`
|
|
|
|
scopes = scopes.reject { |scope| scope[:if].presence && !scope[:if].call(request) }
|
2017-06-20 07:40:24 +00:00
|
|
|
|
2017-06-20 08:27:45 +00:00
|
|
|
# Check whether the token is allowed access to any of the required scopes.
|
|
|
|
passed_scope_names = scopes.map { |scope| scope[:name].to_sym }
|
|
|
|
token_scope_names = token.scopes.map(&:to_sym)
|
|
|
|
Set.new(passed_scope_names).intersection(Set.new(token_scope_names)).present?
|
2016-11-22 09:04:23 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|