예제 #1
0
def redirect(
    where: Optional[str] = None,
    default: Optional[str] = None,
    override: Optional[str] = None,
    _anchor: Optional[str] = None,
    _cls: Optional[Union[object, type]] = None,
    _external: Optional[bool] = False,
    _external_host: Optional[str] = None,
    _method: Optional[str] = None,
    _scheme: Optional[str] = None,
    **values,
) -> Response:
    """
    An improved version of flask's redirect function

    :param where: A URL, endpoint, or config key name to redirect to
    :param default: A URL, endpoint, or config key name to redirect to if
      ``where`` is invalid
    :param override: explicitly redirect to a URL, endpoint, or config key name
      (takes precedence over the ``next`` value in query strings or forms)
    :param values: the variable arguments of the URL rule
    :param _anchor: if provided this is added as anchor to the URL.
    :param _cls: if specified, allows a method name to be passed to where,
      default, and/or override
    :param _external: if set to ``True``, an absolute URL is generated. Server
      address can be changed via ``SERVER_NAME`` configuration variable which
      defaults to `localhost`.
    :param _external_host: if specified, the host of an external server to
      generate urls for (eg https://example.com or localhost:8888)
    :param _method: if provided this explicitly specifies an HTTP method.
    :param _scheme: a string specifying the desired URL scheme. The `_external`
      parameter must be set to ``True`` or a :exc:`ValueError` is raised. The
      default behavior uses the same scheme as the current request, or
      ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no
      request context is available. As of Werkzeug 0.10, this also can be set
      to an empty string to build protocol-relative URLs.
    """
    flask_url_for_kwargs = dict(_anchor=_anchor,
                                _external=_external,
                                _external_host=_external_host,
                                _method=_method,
                                _scheme=_scheme,
                                **values)

    urls = [
        url_for(request.args.get('next'), **flask_url_for_kwargs),
        url_for(request.form.get('next'), **flask_url_for_kwargs)
    ]
    if where:
        urls.append(url_for(where, _cls=_cls, **flask_url_for_kwargs))
    if default:
        urls.append(url_for(default, _cls=_cls, **flask_url_for_kwargs))
    if override:
        urls.insert(0, url_for(override, _cls=_cls, **flask_url_for_kwargs))

    for url in urls:
        if _validate_redirect_url(url, _external_host):
            return flask_redirect(url)
    return flask_redirect('/')
예제 #2
0
파일: negotiation.py 프로젝트: jmesa/fame-1
def validation_error(path=None):
    if choose_media_type(acceptable_media_types(request), [html]):
        if path:
            return flask_redirect(path)
        else:
            return flask_redirect(request.referrer)
    else:
        return render_json({'errors': get_flashed_messages()})
예제 #3
0
def validation_error(path=None):
    if should_render_as_html():
        if path:
            return flask_redirect(path)

        return flask_redirect(request.referrer)

    return render_json({'errors': get_flashed_messages()})
예제 #4
0
def add_system():
    # We accept JSON or form-encoded for convenience
    if request.json:
        if 'fqdn' not in request.json:
            raise BadRequest400('Missing fqdn key')
        new_fqdn = request.json['fqdn']
    elif request.form:
        if 'fqdn' not in request.form:
            raise BadRequest400('Missing fqdn parameter')
        new_fqdn = request.form['fqdn']
    else:
        raise UnsupportedMediaType415
    with convert_internal_errors():
        if System.query.filter(System.fqdn == new_fqdn).count() != 0:
            raise Conflict409('System with fqdn %r already exists' % new_fqdn)
        system = System(fqdn=new_fqdn, owner=identity.current.user)
        session.add(system)
        # new systems are visible to everybody by default
        system.custom_access_policy = SystemAccessPolicy()
        system.custom_access_policy.add_rule(SystemPermission.view,
                                             everybody=True)
    # XXX this should be 201 with Location: /systems/FQDN/ but 302 is more
    # convenient because it lets us use a traditional browser form without AJAX
    # handling, and for now we're redirecting to /view/FQDN until that is moved
    # to /systems/FQDN/
    return flask_redirect(url(u'/view/%s#essentials' % system.fqdn))
예제 #5
0
def search(query):
    if g.user is not None and is_email(query):
        g.user.set_hide_search_hint()
        return flask_redirect(url_for("page", title=query))
    title = name_to_title(query)
    can_create = False
    try:
        Page.find(title)
    except PageNotFound:
        can_create = g.user is not None and g.user.can_create
    if g.user is not None:
        bookmarks_pages = BookmarksPage.search(query)
        search_pages = [
            page for page in Page.search(query) if page not in bookmarks_pages
        ]
        pages = bookmarks_pages + search_pages
    else:
        pages = Page.search(query)
    return render_template(
        "search.html",
        pages=pages,
        query=query,
        can_create=can_create,
        title_to_create=title,
    )
예제 #6
0
        def skip_interstitial(url, *args, **kwargs):

            if url == url_for('main.to_idp'):
                idp = session.get('suggested_idp')
                url = url_for('broker.auth', idp_hint=idp)

            return flask_redirect(url, *args, **kwargs)
예제 #7
0
def add_system():
    # We accept JSON or form-encoded for convenience
    if request.json:
        if 'fqdn' not in request.json:
            raise BadRequest400('Missing fqdn key')
        new_fqdn = request.json['fqdn']
    elif request.form:
        if 'fqdn' not in request.form:
            raise BadRequest400('Missing fqdn parameter')
        new_fqdn = request.form['fqdn']
    else:
        raise UnsupportedMediaType415
    with convert_internal_errors():
        if System.query.filter(System.fqdn == new_fqdn).count() != 0:
            raise Conflict409('System with fqdn %r already exists' % new_fqdn)
        system = System(fqdn=new_fqdn, owner=identity.current.user)
        session.add(system)
        # new systems are visible to everybody by default
        system.custom_access_policy = SystemAccessPolicy()
        system.custom_access_policy.add_rule(SystemPermission.view,
                everybody=True)
    # XXX this should be 201 with Location: /systems/FQDN/ but 302 is more 
    # convenient because it lets us use a traditional browser form without AJAX 
    # handling, and for now we're redirecting to /view/FQDN until that is moved 
    # to /systems/FQDN/
    return flask_redirect(url(u'/view/%s#essentials' % system.fqdn))
예제 #8
0
 def redirects_middleware():
     from_url = RedirectModel.normalize_url(request.url)
     redirect = RedirectModel.query.filter_by(
         from_url=from_url).one_or_none()
     if redirect is not None:
         status = 301 if redirect.permanent else 307
         return flask_redirect(redirect.url, code=status)
예제 #9
0
파일: group.py 프로젝트: joyxu/beaker
def groups_mine():
    """
    Redirect for compatibility.
    """
    return flask_redirect(
        absolute_url('/groups/',
                     q='member.user_name:%s' %
                     identity.current.user.user_name))
예제 #10
0
파일: client.py 프로젝트: gromgull/palisade
        def d1(*args, **kwargs):
            if session.get(logged_in_key) is None:
                return flask_redirect(url_for(redirect_endpoint, **redirect_kwargs))

            if datetime.now()>session['oauth_token_expires']:
                prov = PROVIDERS[session['oauth_provider']]
                prov.refresh()

            return fn(*args, **kwargs)
예제 #11
0
def redirect(url, status_code=302, output_format=None, data_structure=None):
    if not output_format:
        output_format = _desired_format()

    if output_format == "json":
        data = {"next_page": url}
        data.update(data_structure)
        return render_response(None, data, output_format="json")

    return flask_redirect(url, code=status_code)
예제 #12
0
 def wrapped_fun(*args, **kwargs):
     try:
         return fun(*args, **kwargs)
     except Malformed as e:
         abort(400)
     except NotAllowed:
         # abort(401)
         return flask_redirect(url_for("recent"))
     except PageNotFound:
         abort(404)
예제 #13
0
파일: rendering.py 프로젝트: meZee/pyaspora
def redirect(url, status_code=302, output_format=None, data_structure=None):
    if not output_format:
        output_format = _desired_format()

    if output_format == 'json':
        data = {'next_page': url}
        data.update(data_structure)
        return render_response(None, data, output_format='json')

    return flask_redirect(url, code=status_code)
예제 #14
0
def redirect(autoimage_slug: ObjectId, method: str):
    """only for public images (user not forwarded)"""

    if method not in ["http", "torrent", "magnet"]:
        raise errors.NotFound()

    response = json_document(autoimage_slug)
    if response.status_code != 200:
        return response

    return flask_redirect(location=response.get_json()[f"{method}_url"], code=302)
예제 #15
0
def authorize(apikey, provider, return_url, code, redirect):
    server_api_key = os.getenv("API_KEY", "")
    # print("server api key:", server_api_key, ", request api key:", apikey, flush=True)
    if apikey != server_api_key:
        return "Unauthorized", 401
    providers = os.getenv("PROVIDERS", "")
    if not providers:
        return "No provider is supported", 500
    providers = json.loads(providers)
    if provider not in providers.keys():
        return "requested provider is not supported", 500
    auth_url = providers[provider]['AUTH_URL']
    if not code and 'LOGIN_URL' not in providers[provider]:
        return "Fail to authenticate: no token code is provided for the provider", 400
    q_auth_url = f"{auth_url}?code={code}"
    r = requests.get(q_auth_url)
    if return_url.endswith('/'):
        return_url = return_url[:-1]
    if r.status_code == 200:
        r_json = r.json()
        # print(r_json, flush=True)
        if redirect:
            key_val_str = ''
            for key, val in r.json().items():
                key_val_str = f"{key_val_str}&{key}={val}"
            redirect_url = f"{return_url}?status=success{key_val_str}"
            #return redirect_url, 200
            return flask_redirect(redirect_url)
        else:
            return r_json
    else:
        r_json = {'content': str(r.content), 'status_code': r.status_code}
        # print(r_json, flush=True)
        if redirect:
            # print(r.status_code, r.content, flush=True)
            status_code = r.status_code
            redirect_url = f"{return_url}?status=failure&status_code={status_code}"
            # return redirect_url, status_code
            return flask_redirect(redirect_url)
        else:
            return r_json, r.status_code
예제 #16
0
def get_recipe_log(id, path):
    """
    Redirects to the actual storage location for the requested recipe log.

    :param id: Recipe's id.
    :param path: Log path.
    """
    recipe = _get_recipe_by_id(id)
    for log in recipe.logs:
        if log.combined_path == path:
            return flask_redirect(log.absolute_url, code=307)
    return NotFound404('Recipe log %s for recipe %s not found' % (path, id))
예제 #17
0
def get_recipe_log(id, path):
    """
    Redirects to the actual storage location for the requested recipe log.

    :param id: Recipe's id.
    :param path: Log path.
    """
    recipe = _get_recipe_by_id(id)
    for log in recipe.logs:
        if log.combined_path == path:
            return flask_redirect(log.absolute_url, code=307)
    return NotFound404('Recipe log %s for recipe %s not found' % (path, id))
예제 #18
0
def get_group_by_id_or_name():
    """
    Created for backwards compatibility. Will redirect to /groups/<group_name>.

    :queryparam group_id: Group's id.
    :queryparam group_name: Group's name.
    """
    if 'group_id' in request.args:
        with convert_internal_errors():
            group = Group.by_id(request.args['group_id'])
    elif 'group_name' in request.args:
        group = _get_group_by_name(request.args['group_name'])
    else:
        raise NotFound404
    return flask_redirect(absolute_url(group.href))
예제 #19
0
파일: group.py 프로젝트: joyxu/beaker
def get_group_by_id_or_name():
    """
    Created for backwards compatibility. Will redirect to /groups/<group_name>.

    :queryparam group_id: Group's id.
    :queryparam group_name: Group's name.
    """
    if 'group_id' in request.args:
        with convert_internal_errors():
            group = Group.by_id(request.args['group_id'])
    elif 'group_name' in request.args:
        group = _get_group_by_name(request.args['group_name'])
    else:
        raise NotFound404
    return flask_redirect(absolute_url(group.href))
예제 #20
0
def redirect(location, code=302):
    """Redirect the client to a desired location. Behaves the same
    as Flask's :func:`flask.redirect` function with an awareness of
    OSF view-only links.

    IMPORTANT: This function should always be used instead of
    flask.redirect to ensure the correct behavior of view-only
    links.
    """
    view_only = request.args.get('view_only', '')
    if view_only:
        url = furl.furl(location)
        url.args['view_only'] = view_only
        location = url.url
    return flask_redirect(location, code=code)
예제 #21
0
def redirect(location, code=302):
    """Redirect the client to a desired location. Behaves the same
    as Flask's :func:`flask.redirect` function with an awareness of
    OSF view-only links.

    IMPORTANT: This function should always be used instead of
    flask.redirect to ensure the correct behavior of view-only
    links.
    """
    view_only = request.args.get('view_only', '')
    if view_only:
        url = furl.furl(location)
        url.args['view_only'] = view_only
        location = url.url
    return flask_redirect(location, code=code)
예제 #22
0
파일: client.py 프로젝트: gromgull/palisade
def init_login(verify_endpoint, redirect=False, *args):
    def d0(fn):
        @wraps(fn)
        def d1(provider):
            # get any extra arguments on the query path
            _args = dict([(a, request.args[a]) for a in args if a in request.args])
            callback = url_for(verify_endpoint, provider=provider, _external=True, **_args)
            redirect_url = api.init_login(provider, callback)
            # abort should stop us from getting here if we won't have a 'redirect' key
            return fn(redirect_url)
        return d1
    # if redirect is True, then return an instance of the decorator
    # that automatically does the flask redirection
    if redirect:
        return d0(lambda url: flask_redirect(url))
    return d0
예제 #23
0
def redirect(*args, **kws):
    code = kws.pop("code", 302)
    try:
        to = args[0] or kws.pop("to", "/")
    except IndexError as e:
        to = "/"

    from werkzeug import exceptions
    from flask import current_app, request
    if current_app.is_ssl_request() and not to.startswith('https'):
        try:
            endpoint = current_app.url_map.bind(request.host, to).match()[0]
            if endpoint in current_app.ssl_required_endpoints:
                to = "https://%s%s" % (request.host, to)
        except exceptions.NotFound as e:
            pass

    return flask_redirect(to, code=code)
예제 #24
0
def redirect(location, **kwargs):
    """assembles kwargs as querystring"""
    kwargs = ['%s=%s' % pair for pair in kwargs.items()]
    location = location + '?' + '&'.join(kwargs)
    return flask_redirect(location)
예제 #25
0
 def un_authorized_response_or_redirect(self):
     if self.redirect:
         from flask import redirect as flask_redirect
         return flask_redirect('/')
     return un_authorized_response()
예제 #26
0
def redirect(url=None):
    url = url or request.args.get('referer', '/')
    return flask_redirect(url)
예제 #27
0
파일: negotiation.py 프로젝트: jmesa/fame-1
def redirect(data, path):
    if choose_media_type(acceptable_media_types(request), [html]):
        return flask_redirect(path)
    else:
        return render_json(data)
예제 #28
0
def groups_mine():
    """
    Redirect for compatibility.
    """
    return flask_redirect(absolute_url('/groups/',
            q='member.user_name:%s' % identity.current.user.user_name))
예제 #29
0
def redirect(url):
    if request.is_xhr:
        return jsonify(redirect=url)
    return flask_redirect(url)
예제 #30
0
파일: client.py 프로젝트: tristan/palisade
 def d1(*args, **kwargs):
     if session.get(logged_in_key) is None:
         return flask_redirect(url_for(redirect_endpoint, **redirect_kwargs))
     return fn(*args, **kwargs)
예제 #31
0
def redirect(target, code=302, **kw):
    return patch_response(flask_redirect(target, code=code), **kw)
예제 #32
0
파일: user.py 프로젝트: walbon/beaker
def old_get_group():
    if 'id' in request.args:
        user = User.by_id(request.args['id'])
        if user is not None:
            return flask_redirect(absolute_url(user.href))
    raise NotFound404()
예제 #33
0
파일: __init__.py 프로젝트: viaict/viaduct
def redirect_back(default='home.home', **values):
    return flask_redirect(get_safe_redirect_url(default, **values))
예제 #34
0
 def redirect(error: RedirectToClient) -> Response:
     """
         For Redirect exceptions, performs a redirection to the client.
     """
     return flask_redirect(app.config['CLIENT'] + request.full_path)
예제 #35
0
def login():
    if g.user is not None:
        return flask_redirect(url_for("bookmarks"))
    return render_template("login-page.html", hide_header_login=True)
예제 #36
0
def old_get_group():
    if 'id' in request.args:
        user = User.by_id(request.args['id'])
        if user is not None:
            return flask_redirect(absolute_url(user.href))
    raise NotFound404()
예제 #37
0
def index():
    if g.user is None:
        return flask_redirect(url_for("recent"))
    return flask_redirect(url_for("bookmarks"))
예제 #38
0
        def decorated_function(*args, **kwargs):
            try:
                log.trace("Api Call to %s <%s>" %
                          (path.split(RELATIVE_PATH, 1)[-1], func_name))
                if auth != 'Anonymous' and not (
                        current_user.is_authenticated
                        and current_user.is_auth_level(auth)):
                    return "Insufficent Authority", 401, {
                        'Content-Type': 'application/json'
                    }

                response_code = 200  # OK
                kwargs = get_request_kwargs(func_args, arg_types, args, kwargs)
                next_url = kwargs.pop(
                    'next_url', redirect_url)  # this is for custom redirect

                if FILE_HANDLER:
                    record_api_call(FILE_HANDLER, kwargs)

                try:
                    validate_arguments(func_args, arg_types, args_required,
                                       validator, kwargs)
                except BadRequestException as e:
                    log.error("Api Call bad_arguments %s" % e.kwargs)
                    return e.message, BadRequestException.status_code, {
                        'Content-Type': 'application/json'
                    }

                if 'bypass_cache' in kwargs:
                    pass

                if cache is not None:
                    html_format = 'text/html' in request.accept_mimetypes and not request.accept_mimetypes.accept_json
                    cache_key, ret = MEMCACHE.get(cache, kwargs, html_format)
                    if ret is not None:
                        return ret

                if cache_clear is not None:
                    MEMCACHE.delete(cache_clear, kwargs)

                log.trace("Api Call kwargs: %s" % str(kwargs))
                try:
                    try:
                        ret = func(**kwargs)
                    except Exception as ex:
                        raise

                    if ret is None:
                        raise NotFoundException()

                    if add:
                        assert isinstance(ret, ApiModel) or (isinstance(ret, list) and isinstance(ret[0], ApiModel)), \
                            '%s did not return an ApiModel to commit' % func.__name__
                        if isinstance(ret, (list, tuple)):
                            db.session.add_all(ret)
                        else:
                            db.session.add(ret)

                    if delete:
                        assert isinstance(ret, ApiModel) or (isinstance(ret, list) and (
                            not ret or isinstance(ret[0], ApiModel))), \
                            '%s did not return an ApiModel to commit' % func.__name__
                        if isinstance(ret, (list, tuple)):
                            for i, r in enumerate(ret):
                                ret[i] = r.serialize()
                                db.session.delete(r)
                        else:
                            serialized_ret = ret.serialize()
                            db.session.delete(ret)
                            ret = serialized_ret

                    if commit:
                        db.session.commit()

                except Exception as e:
                    db.session.rollback()
                    # db.session.close()
                    log.critical("Api Call Exception <%s> \n%s\n\n%s" %
                                 (e.__class__, e.args, traceback.format_exc()))
                    if isinstance(e, RestException):
                        return e.message, e.status_code, {
                            'Content-Type': 'application/json'
                        }
                    else:
                        raise

                if isinstance(ret, tuple) and len(ret) == 2 and isinstance(
                        ret[1], int):  # error
                    raise DeprecationWarning  # these should have been raised as Rest Exceptions

                if isinstance(ret, (ApiModel, LocalProxy)):
                    ret = ret.serialize()

                if isinstance(ret, list) and ret and isinstance(
                        ret[0], (ApiModel, LocalProxy)):
                    ret = [row.serialize() or row for row in ret]

                if 'text/html' in request.accept_mimetypes and not request.accept_mimetypes.accept_json:
                    if response_code != GOOD_REQUEST and html:
                        return render_template(html, data=kwargs,
                                               errors=ret), response_code
                    elif next_url:
                        return flask_redirect(next_url)
                    elif html:
                        ret = render_template(html, data=kwargs, errors=ret)
                        if cache is not None:
                            MEMCACHE.set(cache_key, ret, cache_hours)
                        return ret

                ret = json.dumps(ret)
                if cache is not None:
                    MEMCACHE.set(cache_key, ret, cache_hours)

                return ret, response_code, {'Content-Type': 'application/json'}

            except Exception as e:
                log.critical("Api Call Exception %s" % traceback.format_exc())
                raise
예제 #39
0
def redirect(*args, **kwargs):
    if request.values.get('api') == '1':
        return jsonify(success=False)
    return flask_redirect(*args, **kwargs)
예제 #40
0
def redirect():
    user_context = getattr(g, 'user_context', None)
    if user_context is None or not user_context.is_authenticated:
        return flask_redirect(url_for('auth.login_page'))
    return flask_redirect(url_for('spending.index'))
예제 #41
0
 def redirect(self, url, **kwargs):
   """Check vaid url and redirect to it, if valid."""
   url = str(url)
   check_redirect_url(url)
   return flask_redirect(url, **kwargs)
예제 #42
0
def pageorbookmarks():
    if g.user is None:
        return flask_redirect(url_for("recent"))
    elif g.user.passhash is None:
        return flask_redirect(url_for("bookmarks"))
    return flask_redirect(url_for("page", title=g.user.email))
예제 #43
0
def redirect(data, path):
    if should_render_as_html():
        return flask_redirect(path)

    return render_json(data)