Python flask.request.referrer() Examples

The following are 30 code examples of flask.request.referrer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.request , or try the search function .
Example #1
Source File: csrf.py    From jbox with MIT License 8 votes vote down vote up
def protect(self):
        if request.method not in self._app.config['WTF_CSRF_METHODS']:
            return

        if not validate_csrf(self._get_csrf_token()):
            reason = 'CSRF token missing or incorrect.'
            return self._error_response(reason)

        if request.is_secure and self._app.config['WTF_CSRF_SSL_STRICT']:
            if not request.referrer:
                reason = 'Referrer checking failed - no Referrer.'
                return self._error_response(reason)

            good_referrer = 'https://%s/' % request.host
            if not same_origin(request.referrer, good_referrer):
                reason = 'Referrer checking failed - origin does not match.'
                return self._error_response(reason)

        request.csrf_valid = True  # mark this request is csrf valid 
Example #2
Source File: server.py    From figma-linux-font-helper with MIT License 7 votes vote down vote up
def version():
    if is_valid_origin(request.referrer):
        response = make_response(jsonify({
            "version": PROTOCOL_VERSION
        }))

        if request.referrer:
            response.headers['Access-Control-Allow-Origin'] = \
                request.referrer[:-1] if request.referrer.endswith("/") else \
                request.referrer[:-1]

        response.headers['Content-Type'] = 'application/json'

        return response
    else:
        return answers_with_404() 
Example #3
Source File: flask_util.py    From alfred-gmail with MIT License 6 votes vote down vote up
def authorize_view(self):
        """Flask view that starts the authorization flow.

        Starts flow by redirecting the user to the OAuth2 provider.
        """
        args = request.args.to_dict()

        # Scopes will be passed as mutliple args, and to_dict() will only
        # return one. So, we use getlist() to get all of the scopes.
        args['scopes'] = request.args.getlist('scopes')

        return_url = args.pop('return_url', None)
        if return_url is None:
            return_url = request.referrer or '/'

        flow = self._make_flow(return_url=return_url, **args)
        auth_url = flow.step1_get_authorize_url()

        return redirect(auth_url) 
Example #4
Source File: views.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def verify(institute_id, case_name, variant_id, variant_category, order):
    """Start procedure to validate variant using other techniques."""
    comment = request.form.get("verification_comment")

    try:
        variant_verification(
            store=store,
            institute_id=institute_id,
            case_name=case_name,
            comment=comment,
            variant_id=variant_id,
            sender=current_app.config.get("MAIL_USERNAME"),
            variant_url=request.referrer,
            order=order,
            url_builder=url_for,
        )
    except MissingVerificationRecipientError:
        flash("No verification recipients added to institute.", "danger")

    return redirect(request.referrer) 
Example #5
Source File: views.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def variant(institute_id, case_name, variant_id):
    """Display a specific SNV variant."""
    LOG.debug("Variants view requesting data for variant %s", variant_id)

    data = variant_controller(store, institute_id, case_name, variant_id=variant_id)
    if data is None:
        LOG.warning(
            "An error occurred: variants view requesting data for variant {}".format(variant_id)
        )
        flash("An error occurred while retrieving variant object", "danger")
        return redirect(request.referrer)

    if current_app.config.get("LOQUSDB_SETTINGS"):
        LOG.debug("Fetching loqusdb information for %s", variant_id)
        data["observations"] = observations(store, loqusdb, data["case"], data["variant"])

    return data 
Example #6
Source File: users.py    From yeti with Apache License 2.0 6 votes vote down vote up
def permissions(self, id):
        user = get_object_or_404(User, id=id)
        permdict = {}
        if request.method == "POST":
            for object_name, permissions in user.permissions.items():
                if not isinstance(permissions, dict):
                    permdict[object_name] = bool(
                        request.form.get("{}".format(object_name), False))
                else:
                    if object_name not in permdict:
                        permdict[object_name] = {}
                    for p in permissions:
                        permdict[object_name][p] = bool(
                            request.form.get(
                                "{}_{}".format(object_name, p), False))
            user.permissions = permdict
            user.save()
            flash("Permissions changed successfully", "success")
        return redirect(request.referrer)
        return render_template("user/permissions.html", user=user) 
Example #7
Source File: server.py    From figma-linux-font-helper with MIT License 6 votes vote down vote up
def need_update():
    if is_valid_origin(request.referrer):
        response = make_response(jsonify({
            "version": PROTOCOL_VERSION
        }))

        if request.referrer:
            response.headers['Access-Control-Allow-Origin'] = \
                request.referrer[:-1] if request.referrer.endswith("/") else \
                request.referrer[:-1]

        response.headers['Content-Type'] = 'application/json'

        return response
    else:
        return answers_with_404() 
Example #8
Source File: server.py    From figma-linux-font-helper with MIT License 6 votes vote down vote up
def font_file():
    file_name = request.args.get("file")

    if file_name:
        if file_name in FONT_FILES:
            with open(file_name, 'rb') as bites:
                response = make_response(send_file(
                    io.BytesIO(bites.read()),
                    attachment_filename=os.path.basename(file_name),
                    mimetype='application/octet-stream'
                ))

                if request.referrer:
                    response.headers['Access-Control-Allow-Origin'] = \
                        request.referrer[:-1] if request.referrer.endswith("/") else \
                        request.referrer[:-1]

                response.headers['Content-Type'] = 'application/json'

                return response

    return ('', 404) 
Example #9
Source File: server.py    From figma-linux-font-helper with MIT License 6 votes vote down vote up
def font_files():
    if is_valid_origin(request.referrer):
        response = make_response(jsonify({
            "version": PROTOCOL_VERSION,
            "fontFiles": FONT_FILES
        }))

        if request.referrer:
            response.headers['Access-Control-Allow-Origin'] = \
                request.referrer[:-1] if request.referrer.endswith("/") else \
                request.referrer[:-1]

        response.headers['Content-Type'] = 'application/json'

        return response
    else:
        return answers_with_404() 
Example #10
Source File: system.py    From yeti with Apache License 2.0 6 votes vote down vote up
def restart_worker(self, name="all"):
        response = celery_app.control.broadcast(
            'pool_restart',
            arguments={'reload': True},
            destination=[name] if name != "all" else None,
            reply=True,
        )

        nok = []
        for r in response:
            for name in r:
                if 'ok' not in r[name]:
                    nok.append(name)
        if nok:
            flash(
                "Some workers failed to restart: {}".format(", ".join(nok)),
                "danger")
        flash(
            "Succesfully restarted {} workers".format(len(response)), "success")

        return redirect(request.referrer) 
Example #11
Source File: users.py    From fame with GNU General Public License v3.0 6 votes vote down vote up
def reset_api(self, id):
        """Reset a user's API key.

        .. :quickref: User; Reset API key

        When used on another user account, requires the `manage_users` permission.

        :param id: user id.

        :>json User user: modified user.
        """
        self.ensure_permission(id)

        user = User(get_or_404(User.get_collection(), _id=id))
        user.update_value('api_key', User.generate_api_key())

        return redirect({'user': clean_users(user)}, request.referrer) 
Example #12
Source File: http.py    From bepasty-server with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _redirect_target_url(d, use_referrer, endpoint, **values):
    """
    return redirect url to (in that order):

    - <next> from d
    - referrer (if use_referrer is True)
    - the url for endpoint/values
    """
    targets = [d.get('next'), request.referrer, url_for(endpoint, **values)]
    if not use_referrer:
        del targets[1]
    for target in targets:
        if target and is_safe_url(target):
            return target


# GET - for next 2, you may want to create urls with:
# url_for(endpoint, ..., next=something) 
Example #13
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def protect(self):
        if request.method not in current_app.config['WTF_CSRF_METHODS']:
            return

        try:
            validate_csrf(self._get_csrf_token())
        except ValidationError as e:
            logger.info(e.args[0])
            self._error_response(e.args[0])

        if request.is_secure and current_app.config['WTF_CSRF_SSL_STRICT']:
            if not request.referrer:
                self._error_response('The referrer header is missing.')

            good_referrer = 'https://{0}/'.format(request.host)

            if not same_origin(request.referrer, good_referrer):
                self._error_response('The referrer does not match the host.')

        g.csrf_valid = True  # mark this request as CSRF valid 
Example #14
Source File: decorators.py    From flask-security with MIT License 6 votes vote down vote up
def default_unauthz_handler(func, params):
    unauthz_message, unauthz_message_type = get_message("UNAUTHORIZED")
    if _security._want_json(request):
        payload = json_error_response(errors=unauthz_message)
        return _security._render_json(payload, 403, None, None)
    view = config_value("UNAUTHORIZED_VIEW")
    if view:
        if callable(view):
            view = view()
        else:
            try:
                view = get_url(view)
            except BuildError:
                view = None
        do_flash(unauthz_message, unauthz_message_type)
        redirect_to = "/"
        if request.referrer and not request.referrer.split("?")[0].endswith(
            request.path
        ):
            redirect_to = request.referrer

        return redirect(view or redirect_to)
    abort(403) 
Example #15
Source File: app.py    From analytics-quarry-web with MIT License 6 votes vote down vote up
def query_runs_all():
    queries = g.conn.session.query(Query)\
        .join(Query.latest_rev).join(QueryRevision.latest_run)
    queries_filter = 'all'
    if request.args.get('published') == 'true':
        queries = queries.filter(Query.published)
        queries_filter = 'published'
    limit = int(request.args.get(
        'limit', app.config.get('QUERY_RESULTS_PER_PAGE', 50)))
    queries, prev_link, next_link = QueriesRangeBasedPagination(
        queries, request.args.get('from'), limit,
        request.path,
        request.referrer, dict(request.args)).paginate()
    return render_template(
        "query/list.html", user=get_user(), queries=queries,
        prev_link=prev_link, next_link=next_link,
        queries_filter=queries_filter) 
Example #16
Source File: api.py    From elearning with MIT License 6 votes vote down vote up
def comment():
    if request.method == 'GET':
        p_id = request.args.get('pid')
        p = int(request.args.get('p') or 1)
        p -= 1
        items = Comment.query_range(Comment.c_belong == p_id, start=p*10, stop=p*10+10)
        if items:
            comments = basic.make_obj_serializable(items)
        else:
            comments = []
        return jsonify(comments)
    elif request.method == 'POST':
        data = dict()
        data['c_cont'] = request.values.get('c_cont')
        data['c_dtime'] = datetime.utcnow()
        data['c_creator'] = session['uid']
        referrer = request.referrer or request.headers['referrer']
        data['c_belong'] = referrer.split('=')[-1]
        # data['c_belong'] = request.args.get('pid')
        Comment.insert(Comment(**data))
        Comment.commit()
        return redirect(referrer)


# 应该检查文件类型 
Example #17
Source File: negotiation.py    From fame with GNU General Public License v3.0 6 votes vote down vote up
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()}) 
Example #18
Source File: views.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def panel_update(panel_id):
    """Update panel to a new version."""
    panel_obj = store.panel(panel_id)
    if request.form.get("cancel_pending"):
        updated_panel = store.reset_pending(panel_obj)
        if updated_panel is None:
            flash("Couldn't find a panel with ID {}".format(panel_id), "warning")
        elif updated_panel.get("pending") is None:
            flash("Pending actions were correctly canceled!", "success")

        return redirect(request.referrer)

    if panel_write_granted(panel_obj, current_user):
        update_version = request.form.get("version", None)
        new_panel_id = store.apply_pending(panel_obj, update_version)
        panel_id = new_panel_id
    else:
        flash(
            "Permission denied: please ask a panel maintainer or admin for help.", "danger",
        )

    return redirect(url_for("panels.panel", panel_id=panel_id)) 
Example #19
Source File: views.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def clinvar_download_csv(submission, csv_type, clinvar_id):
    """Download a csv (Variant file or CaseData file) for a clinVar submission"""

    def generate_csv(header, lines):
        """Return downloaded header and lines with quoted fields"""
        yield header + "\n"
        for line in lines:
            yield line + "\n"

    clinvar_file_data = controllers.clinvar_submission_file(store, submission, csv_type, clinvar_id)

    if clinvar_file_data is None:
        return redirect(request.referrer)

    headers = Headers()
    headers.add(
        "Content-Disposition", "attachment", filename=clinvar_file_data[0],
    )
    return Response(
        generate_csv(",".join(clinvar_file_data[1]), clinvar_file_data[2]),
        mimetype="text/csv",
        headers=headers,
    ) 
Example #20
Source File: files.py    From fame with GNU General Public License v3.0 6 votes vote down vote up
def add_comment(self, id):
        if comments_enabled():
            f = File(get_or_404(current_user.files, _id=id))

            if current_user.has_permission('add_probable_name'):
                probable_name = request.form.get('probable_name')
            else:
                probable_name = None

            comment = request.form.get('comment')
            analysis_id = request.form.get('analysis')
            notify = request.form.get('notify')

            if comment:
                # If there is an analysis ID, make sure it is accessible
                if analysis_id:
                    get_or_404(current_user.analyses, _id=analysis_id)

                f.add_comment(current_user['_id'], comment, analysis_id, probable_name, notify)
            else:
                flash('Comment should not be empty', 'danger')

        return redirect(request.referrer) 
Example #21
Source File: routing.py    From cmdb with GNU General Public License v2.0 6 votes vote down vote up
def logout():
    """
    When the user accesses this route they are logged out.
    """

    cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
    cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY']

    cas_username_session_key in session and session.pop(cas_username_session_key)
    "acl" in session and session.pop("acl")
    "uid" in session and session.pop("uid")
    cas_token_session_key in session and session.pop(cas_token_session_key)
    "next" in session and session.pop("next")

    redirect_url = create_cas_logout_url(
        current_app.config['CAS_SERVER'],
        current_app.config['CAS_LOGOUT_ROUTE'],
        url_for('cas.login', _external=True, next=request.referrer))

    logout_user()

    current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))

    return redirect(redirect_url) 
Example #22
Source File: flask_util.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def authorize_view(self):
        """Flask view that starts the authorization flow.

        Starts flow by redirecting the user to the OAuth2 provider.
        """
        args = request.args.to_dict()

        # Scopes will be passed as mutliple args, and to_dict() will only
        # return one. So, we use getlist() to get all of the scopes.
        args['scopes'] = request.args.getlist('scopes')

        return_url = args.pop('return_url', None)
        if return_url is None:
            return_url = request.referrer or '/'

        flow = self._make_flow(return_url=return_url, **args)
        auth_url = flow.step1_get_authorize_url()

        return redirect(auth_url) 
Example #23
Source File: application.py    From fava with MIT License 5 votes vote down vote up
def jump():
    """Redirect back to the referer, replacing some parameters.

    This is useful for sidebar links, e.g. a link ``/jump?time=year``
    would set the time filter to `year` on the current page.

    When accessing ``/jump?param1=abc`` from
    ``/example/page?param1=123&param2=456``, this view should redirect to
    ``/example/page?param1=abc&param2=456``.

    """
    url = werkzeug.urls.url_parse(request.referrer)
    qs_dict = url.decode_query()
    for key, values in request.args.lists():
        if len(values) == 1 and values[0] == "":
            try:
                del qs_dict[key]
            except KeyError:
                pass
            continue
        qs_dict.setlist(key, values)

    redirect_url = url.replace(
        query=werkzeug.urls.url_encode(qs_dict, sort=True)
    )
    return redirect(werkzeug.urls.url_unparse(redirect_url)) 
Example #24
Source File: settings.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def put(self, server=None):
        """Creates a new template"""
        if not current_user.is_anonymous and \
                current_user.acl.is_moderator() and \
                not current_user.acl.is_server_rw(server):
            self.abort(403, 'You don\'t have rights on this server')

        newtemplate = self.parser.parse_args()['newtemplate']
        if not newtemplate:
            self.abort(400, 'No template name provided')
        parser = bui.client.get_parser(agent=server)
        templates = parser.list_templates()
        for tpl in templates:
            if tpl['name'] == newtemplate:
                self.abort(409, "Template '{}' already exists".format(newtemplate))
        # clientconfdir = bui.client.get_parser_attr('clientconfdir', server)
        # if not clientconfdir:
        #    flash('Could not proceed, no \'clientconfdir\' find', 'warning')
        #    return redirect(request.referrer)
        noti = bui.client.store_conf_cli(ImmutableMultiDict(), newtemplate, None, True, False, server)
        if server:
            url = url_for('view.cli_settings', server=server, client=newtemplate, template=True)
        else:
            url = url_for('view.cli_settings', client=newtemplate, template=True)
        noti.append([NOTIF_INFO, _('<a href="%(url)s">Click here</a> to edit \'%(template)s\' configuration', url=url, template=newtemplate)])
        # clear the cache when we add a new client
        cache.clear()
        bui.audit.logger.info(f'created new template {newtemplate}', server=server)
        return {'notif': noti}, 201 
Example #25
Source File: settings.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def put(self, server=None):
        """Creates a new template"""
        if not current_user.is_anonymous and \
                current_user.acl.is_moderator() and \
                not current_user.acl.is_server_rw(server):
            self.abort(403, 'You don\'t have rights on this server')

        newtemplate = self.parser.parse_args()['newstatictemplate']
        if not newtemplate:
            self.abort(400, 'No template name provided')
        parser = bui.client.get_parser(agent=server)
        templates = parser.list_static_templates()
        if any(tpl['name'] == newtemplate for tpl in templates):
            self.abort(409, "Static template '{}' already exists".format(newtemplate))
        # clientconfdir = bui.client.get_parser_attr('clientconfdir', server)
        # if not clientconfdir:
        #    flash('Could not proceed, no \'clientconfdir\' find', 'warning')
        #    return redirect(request.referrer)
        noti = bui.client.store_conf_cli(ImmutableMultiDict(), newtemplate, None, False, True, server)
        if server:
            url = url_for('view.cli_settings', server=server, client=newtemplate, statictemplate=True)
        else:
            url = url_for('view.cli_settings', client=newtemplate, statictemplate=True)
        noti.append([NOTIF_INFO, _('<a href="%(url)s">Click here</a> to edit \'%(template)s\' configuration', url=url, template=newtemplate)])
        # clear the cache when we add a new client
        cache.clear()
        bui.audit.logger.info(f'created new static template {newtemplate}', server=server)
        return {'notif': noti}, 201 
Example #26
Source File: __init__.py    From realms-wiki with GNU General Public License v2.0 5 votes vote down vote up
def redirect_url(referrer=None):
    if not referrer:
        referrer = request.referrer
    return request.args.get('next') or referrer or url_for('index') 
Example #27
Source File: web.py    From SwarmOps with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_referrer_url():
    """获取上一页地址"""
    if request.referrer and request.referrer.startswith(request.host_url) and request.endpoint and not "api." in request.endpoint:
        url = request.referrer
    else:
        url = None
    return url 
Example #28
Source File: views.py    From yeti with Apache License 2.0 5 votes vote down vote up
def change_password():
    if current_user.has_role('admin') and request.args.get('id'):
        u = get_object_or_404(User, id=request.args.get('id'))
    else:
        u = current_user

    current = request.form.get("current", "")
    new = request.form.get("new", "")
    bis = request.form.get("bis", "")

    if not current_user.has_role('admin'):
        if not check_password_hash(u.password, current):
            flash('Current password is invalid', 'danger')
            return redirect(request.referrer)

    if new != bis:
        flash('Password confirmation differs from new password.', 'danger')
    else:
        u = set_password(u, new)
        u.save()
        # re-execute the login if the changes were made on current_user
        if u.id == current_user.id:
            login_user(u)
        flash('Password was successfully changed.', 'success')

    return redirect(request.referrer) 
Example #29
Source File: web.py    From SwarmOps with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_redirect_url(endpoint="front.index"):
    """获取重定向地址
    NextUrl: 引导重定向下一步地址
    ReturnUrl: 最终重定向地址
    以上两个不存在时,如果定义了非默认endpoint,则首先返回;否则返回referrer地址,不存在时返回endpoint默认主页
    """
    url = request.args.get('NextUrl') or request.args.get('ReturnUrl')
    if not url:
        if endpoint != "front.index":
            url = url_for(endpoint)
        else:
            url = get_referrer_url() or url_for(endpoint)
    return url 
Example #30
Source File: views.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clinvar_rename_casedata(submission, case, old_name):
    """Rename one or more casedata individuals belonging to the same clinvar submission, same case"""

    new_name = request.form.get("new_name")
    controllers.update_clinvar_sample_names(
        store, submission, case, old_name, new_name,
    )
    return redirect(request.referrer)