summaryrefslogtreecommitdiff
path: root/app/services/access_token_validation_service.rb
blob: 9c00ea789ec437202334ec7a494c2f4cc410c6fe (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
42
43
44
45
46
47
48
49
50
class AccessTokenValidationService
  # Results:
  VALID = :valid
  EXPIRED = :expired
  REVOKED = :revoked
  INSUFFICIENT_SCOPE = :insufficient_scope

  attr_reader :token, :request

  def initialize(token, request: nil)
    @token = token
    @request = request
  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?(required_scopes)
    if required_scopes.blank?
      true
    else
      # 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)

      required_scopes.any? do |scope|
        if scope.respond_to?(:sufficient?)
          scope.sufficient?(token_scopes, request)
        else
          API::Scope.new(scope).sufficient?(token_scopes, request)
        end
      end
    end
  end
end