summaryrefslogtreecommitdiff
path: root/app/services/oauth2/access_token_validation_service.rb
blob: 6194f6ce91eb334c30a14e9beba31cd63e4060ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
module Oauth2::AccessTokenValidationService
  # Results:
  VALID = :valid
  EXPIRED = :expired
  REVOKED = :revoked
  INSUFFICIENT_SCOPE = :insufficient_scope

  class << self
    def validate(token, scopes: [])
      if token.expired?
        return EXPIRED

      elsif token.revoked?
        return REVOKED

      elsif !self.sufficient_scope?(token, scopes)
        return INSUFFICIENT_SCOPE

      else
        return VALID
      end
    end

    protected
    # True if the token's scope is a superset of required scopes,
    # or the required scopes is empty.
    def sufficient_scope?(token, scopes)
      if scopes.blank?
        # if no any scopes required, the scopes of token is sufficient.
        return true
      else
        # If there are scopes required, then check whether
        # the set of authorized scopes is a superset of the set of required scopes
        required_scopes = Set.new(scopes)
        authorized_scopes = Set.new(token.scopes)

        return authorized_scopes >= required_scopes
      end
    end
  end
end