Python flask.request.access_route() Examples

The following are 7 code examples of flask.request.access_route(). 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: health.py    From bearded-avenger with Mozilla Public License 2.0 6 votes vote down vote up
def get(self):

        # feeds get large need to force some cleanup
        gc.collect()

        if get_remote_address() != request.access_route[-1]:
            return jsonify_unauth()

        if not HTTPD_TOKEN:
            return jsonify_success()

        remote = ROUTER_ADDR
        if current_app.config.get('CIF_ROUTER_ADDR'):
            remote = current_app.config['CIF_ROUTER_ADDR']

        try:
            r = Client(remote, HTTPD_TOKEN).ping()
            r = Client(remote, HTTPD_TOKEN).indicators_search({'indicator': 'example.com', 'nolog': '1'})
            r = True

        except TimeoutError:
            return jsonify_unknown(msg='timeout', code=408)

        except AuthError:
            return jsonify_unauth()

        if not r:
            return jsonify_unknown(503)

        return jsonify_success() 
Example #2
Source File: __init__.py    From bearded-avenger with Mozilla Public License 2.0 6 votes vote down vote up
def proxy_get_remote_address():
    if HTTPD_PROXY in ['1', 1]:
        return request.access_route[-1]

    return get_remote_address() 
Example #3
Source File: api.py    From hoaxy-backend with GNU General Public License v3.0 6 votes vote down vote up
def authenticate_rapidapi(func):
    """Decorator to authenticate request with Rapid API."""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # Rapid authentication
        if rapid_enabled:
            rapid_secret = request.headers.get('X-RapidAPI-Proxy-Secret')
            if rapid_secret is not None:
                client_ip = request.access_route[-1]
                # test the rapid api with corresponding request header
                if rapid_secret == app.config['RAPID_SECRET']:
                    return func(*args, **kwargs)
            # No authentication
            return "Invalid/expired token", 401
        else:
            return func(*args, **kwargs)

    return wrapper 
Example #4
Source File: routes.py    From AUCR with GNU General Public License v3.0 5 votes vote down vote up
def login():
    """Flask AUCR user login route."""
    if current_user.is_authenticated:
        # if user is logged in we get out of here
        return redirect(url_for('main.index'))
    if request.method == "POST":
        form = LoginForm()
        if form.validate_on_submit():
            user_name = User.query.filter_by(username=form.username.data).first()
            if user_name is not None and user_name.otp_secret is not None:
                otp_auth_check = user_name.verify_totp(form.token.data)
                if otp_auth_check is False or not user_name.check_password(form.password.data):
                    flash('Invalid username, password or token.')
                    return redirect(url_for('auth.login'))
            if user_name is None or not user_name.check_password(form.password.data):
                flash('Invalid username, password or token.')
                return redirect(url_for('auth.login'))
            # log user in
            if form.remember_me.data:
                login_user(user_name, remember=form.remember_me.data)
            else:
                login_user(user_name)
            session["navbar"] = get_group_permission_navbar()
            session["groups"] = get_groups()
            flash('You are now logged in!')
            user_name.set_last_used_ip(request.access_route[0])
            db.session.add(user_name)
            db.session.commit()
            page = request.args.get('page', 1, type=int)
            return redirect(url_for('main.index', page=page))
        else:
            for error in form.errors:
                flash(str(form.errors[error][0]), 'error')
        flash('Invalid username, password or token.')
        return redirect(url_for('auth.login'))
    page = request.args.get('page', 1, type=int)
    form = LoginForm()
    return render_template('login.html', title=_('Sign In'), form=form, page=page) 
Example #5
Source File: util.py    From flask-limiter with MIT License 5 votes vote down vote up
def get_ipaddr():  # pragma: no cover
    """
    :return: the ip address for the current request
     (or 127.0.0.1 if none found) based on the X-Forwarded-For headers.

    .. deprecated:: 0.9.2
     """
    if request.access_route:
        return request.access_route[0]
    else:
        return request.remote_addr or '127.0.0.1' 
Example #6
Source File: api.py    From http-observatory with Mozilla Public License 2.0 4 votes vote down vote up
def api_get_scanner_stats():
    pretty = True if request.args.get('pretty', '').lower() == 'true' else False
    verbose = True if request.args.get('verbose', '').lower() == 'true' else False

    # Disallow verbose stat requests from the public if this setting is set
    if verbose and not API_ALLOW_VERBOSE_STATS_FROM_PUBLIC:
        verbose = True if request.access_route[0] == '127.0.0.1' else False

    # Get the scanner statistics from the backend database, defaulting to the quick stats only
    stats = database.select_scan_scanner_statistics(verbose)

    # If a grade isn't in the database, return it with quantity 0
    grade_distribution = {grade: stats['grade_distribution'].get(grade, 0) for grade in GRADES}
    grade_distribution_all_scans = {grade: stats['grade_distribution_all_scans'].get(grade, 0) for grade in GRADES}

    # Get the number of grade improvements
    grade_improvements_all = stats['scan_score_difference_distribution_summation']

    # Make sure we only list the ones that are improvements, with a maximum of 5 letter grades
    grade_improvements = {k: 0 for k in range(0, 6)}
    for k, v in grade_improvements_all.items():
        grade_improvements[min(5, max(0, int(k / 20)))] += v

    # Convert all the datetimes to HTTP strings
    stats['most_recent_scan_datetime'] = http_date(stats['most_recent_scan_datetime'].utctimetuple())
    stats['recent_scans'] = {http_date(i.utctimetuple()): v for i, v in stats['recent_scans']}

    resp = make_response(json.dumps({
        'gradeDistribution': {
            'latest': grade_distribution,
            'all': grade_distribution_all_scans,
        },
        'gradeImprovements': grade_improvements,
        'misc': {
            'mostRecentScanDate': stats['most_recent_scan_datetime'],
            'numHoursWithoutScansInLast24Hours': 24 - len(stats['recent_scans']) if verbose else -1,
            'numImprovedSites': sum([v for k, v in grade_improvements_all.items() if k > 0]),
            'numScans': stats['scan_count'],
            'numScansLast24Hours': sum(stats['recent_scans'].values()) if verbose else -1,
            'numSuccessfulScans': sum(grade_distribution_all_scans.values()),
            'numUniqueSites': sum(grade_improvements_all.values())
        },
        'recent': {
            'scans': {
                'best': database.select_scan_recent_finished_scans(13, 90, 1000),   # 13, as there are 13 grades
                'recent': database.select_scan_recent_finished_scans(13, 0, 1000),  # 13, as there are 13 grades
                'worst': database.select_scan_recent_finished_scans(13, 0, 20),     # 13, as there are 13 grades
                'numPerHourLast24Hours': stats['recent_scans'],
            },
        },
        'states': {state: stats['states'].get(state, 0) for state in STATES},
    }, indent=4 if pretty else None, sort_keys=pretty, default=str))

    resp.mimetype = 'application/json'

    return resp 
Example #7
Source File: test_decorators.py    From flask-limiter with MIT License 4 votes vote down vote up
def test_decorated_dynamic_limits(extension_factory):
    app, limiter = extension_factory(
        {"X": "2 per second"}, default_limits=["1/second"]
    )

    def request_context_limit():
        limits = {
            "127.0.0.1": "10 per minute",
            "127.0.0.2": "1 per minute"
        }
        remote_addr = (request.access_route and request.access_route[0]
                       ) or request.remote_addr or '127.0.0.1'
        limit = limits.setdefault(remote_addr, '1 per minute')
        return limit

    @app.route("/t1")
    @limiter.limit("20/day")
    @limiter.limit(lambda: current_app.config.get("X"))
    @limiter.limit(request_context_limit)
    def t1():
        return "42"

    @app.route("/t2")
    @limiter.limit(lambda: current_app.config.get("X"))
    def t2():
        return "42"

    R1 = {"X_FORWARDED_FOR": "127.0.0.1, 127.0.0.0"}
    R2 = {"X_FORWARDED_FOR": "127.0.0.2"}

    with app.test_client() as cli:
        with hiro.Timeline().freeze() as timeline:
            for i in range(0, 10):
                assert cli.get("/t1", headers=R1).status_code == 200
                timeline.forward(1)
            assert cli.get("/t1", headers=R1).status_code == 429
            assert cli.get("/t1", headers=R2).status_code == 200
            assert cli.get("/t1", headers=R2).status_code == 429
            timeline.forward(60)
            assert cli.get("/t1", headers=R2).status_code == 200
            assert cli.get("/t2").status_code == 200
            assert cli.get("/t2").status_code == 200
            assert cli.get("/t2").status_code == 429
            timeline.forward(1)
            assert cli.get("/t2").status_code == 200