6f1922500b
- Declaring an endpoint's scopes in a `before` block has proved to be unreliable. For example, if we're accessing the `API::Users` endpoint - code in a `before` block in `API::API` wouldn't be able to see the scopes set in `API::Users` since the `API::API` `before` block runs first. - This commit moves these declarations to the class level, since they don't need to change once set.
41 lines
923 B
Ruby
41 lines
923 B
Ruby
class AccessTokenValidationService
|
|
# Results:
|
|
VALID = :valid
|
|
EXPIRED = :expired
|
|
REVOKED = :revoked
|
|
INSUFFICIENT_SCOPE = :insufficient_scope
|
|
|
|
attr_reader :token
|
|
|
|
def initialize(token)
|
|
@token = token
|
|
end
|
|
|
|
def validate(scopes: [])
|
|
if token.expired?
|
|
return EXPIRED
|
|
|
|
elsif token.revoked?
|
|
return REVOKED
|
|
|
|
elsif !self.include_any_scope?(scopes)
|
|
return INSUFFICIENT_SCOPE
|
|
|
|
else
|
|
return VALID
|
|
end
|
|
end
|
|
|
|
# True if the token's scope contains any of the passed scopes.
|
|
def include_any_scope?(scopes)
|
|
if scopes.blank?
|
|
true
|
|
else
|
|
#scopes = scopes.reject { |scope| scope[:if].presence && !scope[:if].call(request) }
|
|
# Check whether the token is allowed access to any of the required scopes.
|
|
|
|
scope_names = scopes.map { |scope| scope[:name].to_s }
|
|
Set.new(scope_names).intersection(Set.new(token.scopes)).present?
|
|
end
|
|
end
|
|
end
|