Python flask.request.user_agent() Examples

The following are 8 code examples of flask.request.user_agent(). 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: resources.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def is_from_browser(user_agent):
    return user_agent.browser in [
        "camino",
        "chrome",
        "firefox",
        "galeon",
        "kmeleon",
        "konqueror",
        "links",
        "lynx",
        "msie",
        "msn",
        "netscape",
        "opera",
        "safari",
        "seamonkey",
        "webkit",
    ] 
Example #2
Source File: resources.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def get(self):
        try:
            logout()
            identity_changed.send(
                current_app._get_current_object(), identity=AnonymousIdentity()
            )
        except KeyError:
            return {"Access token not found."}, 500

        logout_data = {"logout": True}

        if is_from_browser(request.user_agent):
            response = jsonify(logout_data)
            unset_jwt_cookies(response)
            return response
        else:
            return logout_data 
Example #3
Source File: views.py    From planespotter with MIT License 6 votes vote down vote up
def _is_msie8or9():
    """Returns ``True`` if and only if the user agent of the client making the
    request indicates that it is Microsoft Internet Explorer 8 or 9.

    .. note::

       We have no way of knowing if the user agent is lying, so we just make
       our best guess based on the information provided.

    """
    # request.user_agent.version comes as a string, so we have to parse it
    version = lambda ua: tuple(int(d) for d in ua.version.split('.'))
    return (request.user_agent is not None
            and request.user_agent.version is not None
            and request.user_agent.browser == 'msie'
            and (8, 0) <= version(request.user_agent) < (10, 0)) 
Example #4
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def ip_whitelist_add(ip_to_allow, info_record_dict=None):
    """添加ip到白名单, 并写入文件"""
    if ip_to_allow in single_ip_allowed_set:
        return
    dbgprint('ip white added', ip_to_allow, 'info:', info_record_dict)
    single_ip_allowed_set.add(ip_to_allow)
    is_ip_not_in_allow_range.cache_clear()
    append_ip_whitelist_file(ip_to_allow)
    # dbgprint(single_ip_allowed_set)
    try:
        with open(zmirror_root(human_ip_verification_whitelist_log), 'a', encoding='utf-8') as fp:
            fp.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " " + ip_to_allow
                     + " " + str(request.user_agent)
                     + " " + repr(info_record_dict) + "\n")
    except:  # coverage: exclude
        errprint('Unable to write log file', os.path.abspath(human_ip_verification_whitelist_log))
        traceback.print_exc() 
Example #5
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def filter_client_request():
    """过滤用户请求, 视情况拒绝用户的访问
    :rtype: Union[Response, None]
    """
    dbgprint('Client Request Url: ', request.url)

    # crossdomain.xml
    if os.path.basename(request.path) == 'crossdomain.xml':
        dbgprint('crossdomain.xml hit from', request.url)
        return crossdomain_xml()

    # Global whitelist ua
    if check_global_ua_pass(str(request.user_agent)):
        return None

    if is_deny_spiders_by_403 and is_denied_because_of_spider(str(request.user_agent)):
        return generate_simple_resp_page(b'Spiders Are Not Allowed To This Site', 403)

    if human_ip_verification_enabled and (
                ((human_ip_verification_whitelist_from_cookies or enable_custom_access_cookie_generate_and_verify)
                 and must_verify_cookies)
            or is_ip_not_in_allow_range(request.remote_addr)
    ):
        dbgprint('ip', request.remote_addr, 'is verifying cookies')
        if 'zmirror_verify' in request.cookies and \
                ((human_ip_verification_whitelist_from_cookies and verify_ip_hash_cookie(request.cookies.get('zmirror_verify')))
                 or (enable_custom_access_cookie_generate_and_verify and custom_verify_access_cookie(
                        request.cookies.get('zmirror_verify'), request))):
            ip_whitelist_add(request.remote_addr, info_record_dict=request.cookies.get('zmirror_verify'))
            dbgprint('add to ip_whitelist because cookies:', request.remote_addr)
        else:
            return redirect(
                "/ip_ban_verify_page?origin=" + base64.urlsafe_b64encode(str(request.url).encode(encoding='utf-8')).decode(
                    encoding='utf-8'),
                code=302)

    return None 
Example #6
Source File: resources.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self):
        email = get_jwt_identity()
        access_token = create_access_token(identity=email)
        auth_service.register_tokens(app, access_token)
        if is_from_browser(request.user_agent):
            response = jsonify({"refresh": True})
            set_access_cookies(response, access_token)
        else:
            return {"access_token": access_token} 
Example #7
Source File: app.py    From quay with Apache License 2.0 5 votes vote down vote up
def _request_end(resp):
    try:
        jsonbody = request.get_json(force=True, silent=True)
    except HTTPException:
        jsonbody = None

    values = request.values.to_dict()

    if jsonbody and not isinstance(jsonbody, dict):
        jsonbody = {"_parsererror": jsonbody}

    if isinstance(values, dict):
        filter_logs(values, FILTERED_VALUES)

    extra = {
        "endpoint": request.endpoint,
        "request_id": request.request_id,
        "remote_addr": request.remote_addr,
        "http_method": request.method,
        "original_url": request.url,
        "path": request.path,
        "parameters": values,
        "json_body": jsonbody,
        "confsha": CONFIG_DIGEST,
    }

    if request.user_agent is not None:
        extra["user-agent"] = request.user_agent.string

    logger.debug("Ending request: %s (%s)", request.request_id, request.path, extra=extra)
    return resp 
Example #8
Source File: decorators.py    From quay with Apache License 2.0 5 votes vote down vote up
def require_xhr_from_browser(func):
    """
    Requires that API GET calls made from browsers are made via XHR, in order to prevent reflected
    text attacks.
    """

    @wraps(func)
    def wrapper(*args, **kwargs):
        if app.config.get("BROWSER_API_CALLS_XHR_ONLY", False):
            if request.method == "GET" and request.user_agent.browser:
                has_xhr_header = request.headers.get("X-Requested-With") == "XMLHttpRequest"
                if not has_xhr_header and not app.config.get("DEBUGGING") == True:
                    logger.warning(
                        "Disallowed possible RTA to URL %s with user agent %s",
                        request.path,
                        request.user_agent,
                    )
                    abort(
                        400,
                        message="API calls must be invoked with an X-Requested-With header "
                        + "if called from a browser",
                    )

        return func(*args, **kwargs)

    return wrapper