Decorator for views to request an ESI Token.
    Accepts required scopes as a space-delimited string
    or list of strings of scope names.
    Can require a new token to be retrieved by SSO.
    Returns a QueryDict of Tokens.
502295
def tokens_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:
                tokens = Token.objects.filter(pk=token.pk)
                logger.debug("Returning new token.")
                return view_func(request, tokens, *args, **kwargs)

            if not new:
                # ensure user logged in to check existing tokens
                if not request.user.is_authenticated:
                    logger.debug(
                        "Session {0} is not logged in. Redirecting to login.".format(request.session.session_key[:5]))
                    from django.contrib.auth.views import redirect_to_login
                    return redirect_to_login(request.get_full_path())

                # collect tokens in db, check if still valid, return if any
                tokens = Token.objects.filter(user__pk=request.user.pk).require_scopes(scopes).require_valid()
                if tokens.exists():
                    logger.debug("Retrieved {0} tokens for {1} session {2}".format(tokens.count(), request.user,
                                                                                   request.session.session_key[:5]))
                    return view_func(request, tokens, *args, **kwargs)

            # trigger creation of new token via sso
            logger.debug("No tokens identified for {0} session {1}. Redirecting 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
628381
def scope_url
      opts  = {}
      route = route(scope)
      opts[:format] = request_format unless skip_format?

      config = Rails.application.config

      # Monkey Patch
      if config.respond_to?(:relative_url_root) && config.relative_url_root.present?
        opts[:script_name] = config.relative_url_root
      end
      # EO Monkey Patch

      router_name = Devise.mappings[scope].router_name || Devise.available_router_name
      context = send(router_name)

      if context.respond_to?(route)
        context.send(route, opts)
      elsif respond_to?(:root_url)
        root_url(opts)
      else
        "/"
      end
    end
1350996
def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None):
        # type: (str, Mapping[str, Union[str, List[str]]], str, Optional[str]) -> se_leg_op.access_token.AccessToken
        
        access_token = AccessToken(rand_str(), self.access_token_lifetime)

        scope = current_scope or granted_scope
        logger.debug('creating access token for scope=%s', scope)

        authz_info = {
            'iat': int(time.time()),
            'exp': int(time.time()) + self.access_token_lifetime,
            'sub': subject_identifier,
            'client_id': auth_req['client_id'],
            'aud': [auth_req['client_id']],
            'scope': scope,
            'granted_scope': granted_scope,
            'token_type': access_token.BEARER_TOKEN_TYPE,
            self.KEY_AUTHORIZATION_REQUEST: auth_req
        }
        self.access_tokens[access_token.value] = authz_info

        logger.debug('new access_token=%s to client_id=%s for sub=%s valid_until=%s',
                     access_token.value, auth_req['client_id'], subject_identifier, authz_info['exp'])
        return access_token
1297797
private String scopesToString(Auth.UrlCodex urlCodex) {
        if (scopes == null || scopes.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        boolean needsSeparator = false;
        for (String scope : scopes) {
            if (needsSeparator) {
                sb.append(scopeDelimiter);
            }
            needsSeparator = true;

            // Use the URL codex to encode each scope, if provided.
            sb.append(urlCodex == null ? scope : urlCodex.encode(scope));
        }
        return sb.toString();
    }
1275747
def group_required(self, group):
        

        def decorator(view):
            @functools.wraps(view)
            def decorated(*args, **kwargs):
                log.info("Trying to get access to resource: %s protected by group: %s", view.__name__, group)
                if request.method == 'POST':
                    token = request.form['token']
                    if self.development or self.group_authenticated(token, group):
                        return view(*args, **kwargs)
                    else:
                        log.warning("User has not been authorized to get access to resource: %s", view.__name__)
                else:
                    log.error("Bad request type! Expected 'POST', actual '%s'", request.method)

                return abort(403)

            return decorated
        return decorator
722889
def sso_redirect(request, scopes=list([]), return_to=None):
    
    logger.debug("Initiating redirect of {0} session {1}".format(request.user, request.session.session_key[:5]))
    if isinstance(scopes, string_types):
        scopes = list([scopes])

    # ensure only one callback redirect model per session
    CallbackRedirect.objects.filter(session_key=request.session.session_key).delete()

    # ensure session installed in database
    if not request.session.exists(request.session.session_key):
        logger.debug("Creating new session before redirect.")
        request.session.create()

    if return_to:
        url = reverse(return_to)
    else:
        url = request.get_full_path()

    oauth = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID, redirect_uri=app_settings.ESI_SSO_CALLBACK_URL, scope=scopes)
    redirect_url, state = oauth.authorization_url(app_settings.ESI_OAUTH_LOGIN_URL)

    CallbackRedirect.objects.create(session_key=request.session.session_key, state=state, url=url)
    logger.debug("Redirecting {0} session {1} to SSO. Callback will be redirected to {2}".format(request.user, request.session.session_key[:5], url))
    return redirect(redirect_url)
1042962
def _get_token_from_query_string(self, request, refresh_token):
        
        if refresh_token:
            query_string_token_name_key = "query_string_refresh_token_name"
        else:
            query_string_token_name_key = "query_string_access_token_name"
        query_string_token_name = getattr(
            self.config, query_string_token_name_key
        )
        return request.args.get(query_string_token_name(), None)
1065113
def create_access_token(self, authorization_request, subject_identifier, scope=None):
        # type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> se_leg_op.access_token.AccessToken
        
        if not self._is_valid_subject_identifier(subject_identifier):
            raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))

        scope = scope or authorization_request['scope']

        return self._create_access_token(subject_identifier, authorization_request.to_dict(), ' '.join(scope))
660113
def view_func(self):
        
        if request is None:
            raise RuntimeError('view_func need Flask be installed')

        signature = request.args.get('signature')
        timestamp = request.args.get('timestamp')
        nonce = request.args.get('nonce')
        if not self.validate(signature, timestamp, nonce):
            return 'signature failed', 400

        if request.method == 'GET':
            echostr = request.args.get('echostr', '')
            return echostr

        try:
            ret = self.parse(request.data)
        except ValueError:
            return 'invalid', 400

        if 'type' not in ret:
            # not a valid message
            return 'invalid', 400

        if ret['type'] == 'text' and ret['content'] in self._registry:
            func = self._registry[ret['content']]
        else:
            ret_set = frozenset(ret.items())
            matched_rules = (
                _func for _func, _limitation in self._registry_without_key
                if _limitation.issubset(ret_set))
            func = next(matched_rules, None)  # first matched rule

        if func is None:
            if '*' in self._registry:
                func = self._registry['*']
            else:
                func = 'failed'

        if callable(func):
            text = func(**ret)
        else:
            # plain text
            text = self.reply(
                username=ret['sender'],
                sender=ret['receiver'],
                content=func,
            )

        return Response(text, content_type='text/xml; charset=utf-8')
1287652
def get_scope_by_id(self, scope_id):
        
        route_values = {}
        if scope_id is not None:
            route_values['scopeId'] = self._serialize.url('scope_id', scope_id, 'str')
        response = self._send(http_method='GET',
                              location_id='4e11e2bf-1e79-4eb5-8f34-a6337bd0de38',
                              version='5.0-preview.2',
                              route_values=route_values)
        return self._deserialize('IdentityScope', response)
392645
def token_view(token):
    """"""
    if request.method == "POST" and 'delete' in request.form:
        db.session.delete(token)
        db.session.commit()
        return redirect(url_for('.index'))

    show_token = session.pop('show_personal_access_token', False)

    form = TokenForm(request.form, name=token.client.name, scopes=token.scopes)
    form.scopes.choices = current_oauth2server.scope_choices()

    if form.validate_on_submit():
        token.client.name = form.data['name']
        token.scopes = form.data['scopes']
        db.session.commit()

    if len(current_oauth2server.scope_choices()) == 0:
        del(form.scopes)

    return render_template(
        "invenio_oauth2server/settings/token_view.html",
        token=token,
        form=form,
        show_token=show_token,
    )
139329
def get_visible_scopes(self):
        
        return [k for k, s in current_oauth2server.scope_choices()
                if k in self.scopes]
1284510
def get_scopes(self):
        
        if not self.authenticated:
            raise ValueError("Must authenticate() as a client first.")

        scope = self.client['scope']
        return scope.split()
691885
def check_auth(access_token):
    
    if not access_token:
      current_app.logger.error('No access token.')
      return deny('No access token found.')
    request = Request(
      current_app.config['TOKEN_ENDPOINT'],
      headers={"Authorization" : ("Bearer %s" % access_token)}
    )
    contents = urlopen(request).read().decode('utf-8')
    token_data = parse_qs(contents)
    me = token_data['me'][0]
    client_id = token_data['client_id'][0]
    if me is None or client_id is None:
        current_app.logger.error("Invalid token [%s]" % contents)
        return deny('Invalid token')

    me, me_error = check_me(me)
    if me is None:
        current_app.logger.error("Invalid `me` value [%s]" % me_error)
        return deny(me_error)

    scope = token_data['scope']
    if not isinstance(scope, str):
        scope = scope[0]
    valid_scopes = ('post','create', )
    scope_ = scope.split()
    scope_valid = any((val in scope_) for val in valid_scopes)

    if not scope_valid:
        current_app.logger.error("Scope '%s' does not contain 'post' or 'create'." % scope)
        return deny("Scope '%s' does not contain 'post' or 'create'." % scope)

    g.user = {
      'me': me,
      'client_id': client_id,
      'scope': scope,
      'access_token': access_token
    }
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
875401
def get_directives(self, token: dict = None, prot: str = "https") -> dict:
        
        # search request
        req_url = "{}://v1.{}.isogeo.com/directives".format(prot, self.api_url)

        req = self.get(
            req_url, headers=self.header, proxies=self.proxies, verify=self.ssl
        )

        # checking response
        checker.check_api_response(req)

        # end of method
        return req.json()
299366
def token_permission_view(token):
    """"""
    scopes = [current_oauth2server.scopes[x] for x in token.scopes]
    return render_template(
        "invenio_oauth2server/settings/token_permission_view.html",
        token=token,
        scopes=scopes,
    )