The required scope is either a string or an iterable. If string,
        check if it is allowed for our access token otherwise, iterate through
        the required_scopes to see which scopes are allowed
190297
def check_scope(self, token, request):
        http_method = request.method
        if not hasattr(self, http_method):
            raise OAuthError("HTTP method is not recognized")
        required_scopes = getattr(self, http_method)
        # a None scope means always allowed
        if required_scopes is None:
            return True
        
        # for non iterable types
        if isinstance(required_scopes, six.string_types):
            if token.allow_scopes(required_scopes.split()):
                return [required_scopes]
            return []
        allowed_scopes = []
        try:
            for scope in required_scopes:
                if token.allow_scopes(scope.split()):
                    allowed_scopes.append(scope)
        except:
            raise Exception('Invalid required scope values')
        else:
            return allowed_scopes
742803
def clean(self):
        
        data = self.cleaned_data
        want_scope = data.get('scope') or 0
        grant = data.get('grant')
        has_scope = grant.scope if grant else 0

        # Only check if we've actually got a scope in the data
        # (read: All fields have been cleaned)
        if want_scope is not 0 and not scope.check(want_scope, has_scope):
            raise OAuthValidationError({'error': 'invalid_scope'})

        return data
774346
public int getExpiresIn(String tokenGrantType, String scope) {
        int expiresIn = Integer.MAX_VALUE;
        List<Scope> scopes = loadScopes(scope);
        boolean ccGrantType = TokenRequest.CLIENT_CREDENTIALS.equals(tokenGrantType);
        if (TokenRequest.CLIENT_CREDENTIALS.equals(tokenGrantType)) {
            for (Scope s : scopes) {
                if (s.getCcExpiresIn() < expiresIn) {
                    expiresIn = s.getCcExpiresIn();
                }
            }
        } else if (TokenRequest.PASSWORD.equals(tokenGrantType)) {
            for (Scope s : scopes) {
                if (s.getPassExpiresIn() < expiresIn) {
                    expiresIn = s.getPassExpiresIn();
                }
            }
        } else {
            // refresh_token
            for (Scope s : scopes) {
                if (s.getRefreshExpiresIn() < expiresIn) {
                    expiresIn = s.getRefreshExpiresIn();
                }
            }
        }
        if (scopes.size() == 0 || expiresIn == Integer.MAX_VALUE) {
            expiresIn = (ccGrantType) ? OAuthConfig.DEFAULT_CC_EXPIRES_IN : OAuthConfig.DEFAULT_PASSWORD_EXPIRES_IN;
        }
        return expiresIn;
    }
108094
boolean allowsValue(String str, ValidationContext vc) {
    try {
      getValue(str, vc);
      return true;
    }
    catch (DatatypeException e) {
      return false;
    }
  }
581338
def detect_possible_scope_visibility(node, context_scope):  # type: (Dict[str, Any], Scope) -> ScopeVisibilityHint
    
    node_type = NodeType(node['type'])

    if not is_analyzable_identifier(node):
        return ScopeVisibilityHint(
            ScopeVisibility.UNANALYZABLE,
            ExplicityOfScopeVisibility.UNANALYZABLE
        )

    if node_type is NodeType.IDENTIFIER:
        return _detect_possible_identifier_scope_visibility(node, context_scope)

    if node_type in GlobalLikeScopeVisibilityNodeTypes:
        return ScopeVisibilityHint(
            ScopeVisibility.GLOBAL_LIKE,
            ExplicityOfScopeVisibility.IMPLICIT_BUT_CONSTRAINED
        )

    return ScopeVisibilityHint(
        ScopeVisibility.UNANALYZABLE,
        ExplicityOfScopeVisibility.UNANALYZABLE
    )
998111
def token_required(scopes='', new=False):
    

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):

            # if we're coming back from SSO for a new token, return it
            token = _check_callback(request)
            if token and new:
                logger.debug("Got new token from {0} session {1}. Returning to view.".format(request.user, request.session.session_key[:5]))
                return view_func(request, token, *args, **kwargs)

            # if we're selecting a token, return it
            if request.method == 'POST':
                if request.POST.get("_add", False):
                    logger.debug("{0} has selected to add new token. Redirecting to SSO.".format(request.user))
                    # user has selected to add a new token
                    from esi.views import sso_redirect
                    return sso_redirect(request, scopes=scopes)

                token_pk = request.POST.get('_token', None)
                if token_pk:
                    logger.debug("{0} has selected token {1}".format(request.user, token_pk))
                    try:
                        token = Token.objects.get(pk=token_pk)
                        # ensure token belongs to this user and has required scopes
                        if ((token.user and token.user == request.user) or not token.user) and Token.objects.filter(
                                pk=token_pk).require_scopes(scopes).require_valid().exists():
                            logger.debug("Selected token fulfills requirements of view. Returning.")
                            return view_func(request, token, *args, **kwargs)
                    except Token.DoesNotExist:
                        logger.debug("Token {0} not found.".format(token_pk))
                        pass

            if not new:
                # present the user with token choices
                tokens = Token.objects.filter(user__pk=request.user.pk).require_scopes(scopes).require_valid()
                if tokens.exists():
                    logger.debug("Returning list of available tokens for {0}.".format(request.user))
                    from esi.views import select_token
                    return select_token(request, scopes=scopes, new=new)
                else:
                    logger.debug("No tokens found for {0} session {1} with scopes {2}".format(request.user, request.session.session_key[:5], scopes))

            # prompt the user to add a new token
            logger.debug("Redirecting {0} session {1} to SSO.".format(request.user, request.session.session_key[:5]))
            from esi.views import sso_redirect
            return sso_redirect(request, scopes=scopes)

        return _wrapped_view

    return decorator
32059
def is_reading_in_require_or_assert(self, variable):
        
        variables_read = [n.variables_read for n in self.nodes if n.contains_require_or_assert()]
        variables_read = [item for sublist in variables_read for item in sublist]
        return variable in variables_read
378067
def assert_has_permission(self, scope_required):
        
        if not self.authenticated:
            raise ValueError("Must first authenticate()")

        if scope_required not in self.get_scopes():
            logging.warning("Authenticated as %s" % (self.client['id']))
            logging.warning("Have scopes: %s" % (str.join(',', self.get_scopes())))
            logging.warning("Insufficient scope %s for operation" % (scope_required))

            raise ValueError("Client does not have permission.")

        return True
1263284
def without_global_scope(self, scope):
        
        if isinstance(scope, basestring):
            del self._scopes[scope]

            return self

        keys = []
        for key, value in self._scopes.items():
            if scope == value.__class__ or isinstance(scope, value.__class__):
                keys.append(key)

        for key in keys:
            del self._scopes[key]

        return self
372382
function coerce(scopes) {
  if (scopes instanceof ScopeSet) {
    return scopes;
  }
  // If we receive a string, assume it's a single scope.
  // We deliberately do not attempt to split the string on whitespace here,
  // because we want to force callers to explicitly choose between
  // exports.fromString() or exports.fromURLEncodedString depending on
  // what encoding they expect to have received the string in.
  if (typeof scopes === 'string') {
    return new ScopeSet([scopes]);
  }
  return new ScopeSet(scopes);
}
349316
def select_token(request, scopes='', new=False):
    

    @tokens_required(scopes=scopes, new=new)
    def _token_list(r, tokens):
        context = {
            'tokens': tokens,
            'base_template': app_settings.ESI_BASE_TEMPLATE,
        }
        return render(r, 'esi/select_token.html', context=context)

    return _token_list(request)
451262
def _call_scope(self, scope, *args, **kwargs):
        
        result = getattr(self._model, scope)(self, *args, **kwargs)

        return result or self
1143553
def encode_scopes(scopes, use_quote=False):
    
    scopes_as_string = Scope.separator.join(scopes)

    if use_quote:
        return quote(scopes_as_string)
    return scopes_as_string
1031544
def list_to_scope(scope):
    """"""
    if isinstance(scope, unicode_type) or scope is None:
        return scope
    elif isinstance(scope, (set, tuple, list)):
        return " ".join([unicode_type(s) for s in scope])
    else:
        raise ValueError("Invalid scope (%s), must be string, tuple, set, or list." % scope)
163326
def check_read_httpauth_access(func):
    

    def wrapper(request, *args, **kwargs):
        database_name = kwargs.get('database_name', "")
        collection_name = kwargs.get('collection_name', "")
        if not database_name or not collection_name:
            return HttpResponse(unauthorized_json_response(),
                                content_type="application/json")

        try:
            # Check to see if we have a matching record in DB access.
            dac = HTTPAuthReadAPI.objects.get(
                database_name=database_name, collection_name=collection_name)
        except HTTPAuthReadAPI.DoesNotExist:
            return HttpResponse(unauthorized_json_response(),
                                content_type="application/json")

        dac_groups = dac.groups.all()
        user_groups = request.user.groups.all()

       # allowedgroups
        in_group = False
        group = None
        for dg in dac_groups:
            if dg in user_groups:
                in_group = True
                group = dg

        if not in_group:
            message = "NOT-IN-GROUP: You do not have access to this collection. Please see your system administrator."

            body = {"code": 400,
                    "message": message,
                    "errors": [message, ]}
            return HttpResponse(json.dumps(body, indent=4, ),
                                content_type="application/json")

        # If search keys have been limitied...
        if dac.search_keys:
            search_key_list = shlex.split(dac.search_keys)
            keys = []
            for k in request.GET.keys():

                if k not in search_key_list:
                    message = "Search key %s  is not allowed." % (k)

                    body = {"code": 400,
                            "message": k,
                            "errors": [message, ]}

                    return HttpResponse(json.dumps(body, indent=4, ),
                                        content_type="application/json")

        return func(request, *args, **kwargs)

    return update_wrapper(wrapper, func)
566479
def check_scope(scope = nil)
      # If no scope is requested or the change has no scope include this change unchanged
      return self unless scope
      change_scope = /^\s*\[\w+\]/.match(@note)
      return self unless change_scope

      # change_scope is a string of format `[scope]`, need to strip the `[]` to compare the scope
      if change_scope[0][1..-2] == scope
        #  Change has the scope that is requested, strip the whole scope scope from the change note
        @note = change_scope.post_match.strip
        return self
      else
        #  Change has a different scope than requested
        return nil
      end
    end
688114
public boolean isValid() {
        // to be valid a scope must have a type set other than undefined and its name will be set
        return (type != null && !type.equals(ScopeType.UNDEFINED) && (name != null && !("").equals(name)));
    }