Python flask.request.cookies() Examples

The following are 30 code examples of flask.request.cookies(). 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: utils.py    From platypush with MIT License 7 votes vote down vote up
def _authenticate_csrf_token():
    user_manager = UserManager()
    user_session_token = None

    if 'X-Session-Token' in request.headers:
        user_session_token = request.headers['X-Session-Token']
    elif 'session_token' in request.args:
        user_session_token = request.args.get('session_token')
    elif 'session_token' in request.cookies:
        user_session_token = request.cookies.get('session_token')

    if user_session_token:
        user, session = user_manager.authenticate_user_session(user_session_token)
    else:
        return False

    if user is None:
        return False

    return session.csrf_token is None or request.form.get('csrf_token') == session.csrf_token 
Example #2
Source File: server.py    From OWASP-Honeypot with Apache License 2.0 6 votes vote down vote up
def get_value_from_request(_key):
    """
    get a value from GET, POST or CCOKIES

    Args:
        _key: the value name to find

    Returns:
        the value content if found otherwise None
    """
    global flask_request
    try:
        key = flask_request.args[_key]
    except Exception as _:
        try:
            key = flask_request.form[_key]
        except Exception as _:
            try:
                key = flask_request.cookies[_key]
            except Exception as _:
                key = None
    if key:
        # todo: fix it later
        key = key.replace("\\\"", "\"").replace("\\\'", "\'")
    return key 
Example #3
Source File: auth.py    From rbb_core with MIT License 6 votes vote down vote up
def get_current_session_id_and_token():
    auth_header = request.environ.get('HTTP_AUTHORIZATION')
    auth_token = ""

    if auth_header:
        value = http.wsgi_to_bytes(auth_header)
        try:
            auth_type, auth_token = value.split(None, 1)
            auth_type = auth_type.lower()

            if auth_type != b'bearer':
                return None

        except ValueError:
            logging.warning("Invalid Auth header")
            return None
    elif "rbbtoken" in request.cookies:
        # Session token in cookie needs to be supported for embedded media links
        auth_token = urllib.parse.unquote(request.cookies['rbbtoken']).encode('latin1')
    else:
        return None

    return unpack_token(base64.b64decode(auth_token)) 
Example #4
Source File: zmirror.py    From zmirror with MIT License 6 votes vote down vote up
def zmirror_enter(input_path='/'):
    """入口函数的壳, 只是包了一层异常处理, 实际是 main_function() """
    try:
        resp = main_function(input_path=input_path)

        # 加入额外的响应头
        for name, value in parse.extra_resp_headers.items():
            resp.headers.set(name, value)

        # 加入额外的cookies
        for name, cookie_string in parse.extra_cookies.items():
            resp.headers.add("Set-Cookie", cookie_string)

    except:  # coverage: exclude
        return generate_error_page(is_traceback=True)
    else:
        return resp


# noinspection PyUnusedLocal 
Example #5
Source File: main.py    From --Awesome-Python-- with GNU General Public License v3.0 6 votes vote down vote up
def send_cookie():
    if request.method == 'GET':
        # 쿠키를 주려면 Response 객체가 필요하다
        response = Response('hello hello')
        response.set_cookie('cookie', 'value!!!!!!!!!', secure=True, httponly=True, samesite='Lax')
        # [werkzeug.wrappers.BaseResponse]
        #     def set_cookie(
        #         self, key, value='', max_age=None, expires=None, path='/',
        #         domain=None, secure=False, httponly=False, samesite=None
        #     )

        return response
    elif request.method == 'POST':
        # 쿠키를 받으려면 BaseRequest의 프로퍼티인 'cookies'에 접근
        print(request.cookies['cookie'])

        # 쿠키 제거는 expires를 0으로 주면 된다
        response = Response('hello hello!')
        response.set_cookie('cookie', '', expires=0,secure=True, httponly=True, samesite='Lax')

        return response
    else:
        return '', 405 
Example #6
Source File: screenshots.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def auth_driver(driver: WebDriver, user: "User") -> WebDriver:
    """
        Default AuthDriverFuncType type that sets a session cookie flask-login style
    :return: WebDriver
    """
    if user:
        # Set the cookies in the driver
        for cookie in get_auth_cookies(user):
            info = dict(name="session", value=cookie)
            driver.add_cookie(info)
    elif request.cookies:
        cookies = request.cookies
        for k, v in cookies.items():
            cookie = dict(name=k, value=v)
            driver.add_cookie(cookie)
    return driver 
Example #7
Source File: screenshots.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def get_auth_cookies(user: "User") -> List[Dict[Any, Any]]:
    # Login with the user specified to get the reports
    with current_app.test_request_context("/login"):
        login_user(user)
        # A mock response object to get the cookie information from
        response = Response()
        current_app.session_interface.save_session(current_app, session, response)

    cookies = []

    # Set the cookies in the driver
    for name, value in response.headers:
        if name.lower() == "set-cookie":
            cookie = parse_cookie(value)
            cookies.append(cookie["session"])
    return cookies 
Example #8
Source File: test_user.py    From runbook with Apache License 2.0 6 votes vote down vote up
def test_get_by_id(self):
        # Ensure id is correct for the current/logged in user
        with self.client:
            response = self.client.post('/login', data=dict(
                email='test@tester.com', password='password456'
            ), follow_redirects=True)
            print response
            logged_in_user_id = verifyLogin(
                app.config['SECRET_KEY'],
                app.config['COOKIE_TIMEOUT'],
                request.cookies
            )
            user = User()
            user.config = app.config
            user_id = user.getUID('test@tester.com', g.rdb_conn)
            self.assertTrue(logged_in_user_id == user_id) 
Example #9
Source File: openid-demo.py    From python-wargaming with MIT License 6 votes vote down vote up
def login():
    if 'SESSION_ID' not in request.cookies:
        session_id = randomString(16, '0123456789abcdef')
    else:
        session_id = request.cookies['SESSION_ID']

    oidconsumer = consumer.Consumer({'id': session_id}, None)
    oidrequest = oidconsumer.begin(u'http://ru.wargaming.net/id/openid/')

    print(oidrequest.shouldSendRedirect())
    redirect_url = oidrequest.redirectURL(
        realm='http://127.0.0.1:5000/',
        return_to='http://127.0.0.1:5000/auth_cb',
    )
    print(oidrequest.shouldSendRedirect())
    response = redirect(redirect_url)
    response.set_cookie('SESSION_ID', session_id)
    return response 
Example #10
Source File: utils.py    From platypush with MIT License 6 votes vote down vote up
def _authenticate_session():
    user_manager = UserManager()
    user_session_token = None
    user = None

    if 'X-Session-Token' in request.headers:
        user_session_token = request.headers['X-Session-Token']
    elif 'session_token' in request.args:
        user_session_token = request.args.get('session_token')
    elif 'session_token' in request.cookies:
        user_session_token = request.cookies.get('session_token')

    if user_session_token:
        user, session = user_manager.authenticate_user_session(user_session_token)

    return user is not None 
Example #11
Source File: openid-demo.py    From python-wargaming with MIT License 5 votes vote down vote up
def index():
    return render_template_string(HTML_TEMPLATE, **request.cookies) 
Example #12
Source File: Login.py    From skf-labs with GNU Affero General Public License v3.0 5 votes vote down vote up
def loggedin():
    txt='You have to login first'
    msg="Find the way to login as an admin !"
    if isloggedin():
        hash=request.cookies.get('sessionid')
        sqli  = dbaccess()
        values=sqli.getHash(hash.lower())
        username=values[0][0].lower()
        if username == 'admin':
            msg="Congratulations !"
        return render_template("loggedin.html",username=username,msg=msg)
    else:       
        return render_template("index.html",msg=txt) 
Example #13
Source File: Login.py    From skf-labs with GNU Affero General Public License v3.0 5 votes vote down vote up
def isloggedin():
    if 'sessionid' in request.cookies:
        hash=request.cookies.get('sessionid')
        sqli  = dbaccess()
        values=sqli.getHash(hash.lower())
        if values:
            return True
    return False 
Example #14
Source File: Login.py    From skf-labs with GNU Affero General Public License v3.0 5 votes vote down vote up
def login():
    sqli  = Classes()
    if 'rememberme' in request.cookies:
        b64=request.cookies.get('rememberme')
        a = pickle.loads(base64.b64decode(b64))
        session['username'] = a.username
        session['loggedin'] = True
        return render_template("loggedin.html")
    else:
        values = 'admin' #
        values=sqli.getUser(request.form['username'])
        if values:
            if values[0][2] == request.form['password']:
                session['username'] = values[0][1]
                session['loggedin'] = True
                if 'rememberme' in request.form:
                    if request.form['rememberme'] == 'on':
                        u1 = usr(values[0][1],values[0][2])
                        ser = pickle.dumps(u1)
                        b64 = base64.b64encode(ser)
                        res = make_response(render_template("loggedin.html"))
                        res.set_cookie("rememberme", b64, 60*60*24*15)
                        return res
                else:
                    return render_template("loggedin.html")
    return render_template("index.html") 
Example #15
Source File: Login.py    From skf-labs with GNU Affero General Public License v3.0 5 votes vote down vote up
def loggedin():
    txt='You have to login first'
    msg="Find the way to login as an admin !"
    if isloggedin():
        hash=request.cookies.get('sessionid')
        sqli  = dbaccess()
        values=sqli.getHash(hash.lower())
        username=values[0][0].lower()
        if username == 'admin':
            msg="Congratulations !"
        return render_template("loggedin.html",username=username,msg=msg)
    else:       
        return render_template("index.html",msg=txt) 
Example #16
Source File: Login.py    From skf-labs with GNU Affero General Public License v3.0 5 votes vote down vote up
def isloggedin():
    if 'sessionid' in request.cookies:
        hash=request.cookies.get('sessionid')
        sqli  = dbaccess()
        values=sqli.getHash(hash.lower())
        if values:
            return True
    return False 
Example #17
Source File: auth.py    From python-wargaming with MIT License 5 votes vote down vote up
def index():
    return render_template_string(HTML_TEMPLATE, **request.cookies) 
Example #18
Source File: auth.py    From python-wargaming with MIT License 5 votes vote down vote up
def logout():
    wot.auth.logout(access_token=request.cookies['access_token'])
    response = redirect('/')
    for k in request.cookies:
        response.delete_cookie(k)
    return response 
Example #19
Source File: flask_app.py    From BlackSheep with MIT License 5 votes vote down vote up
def echo_cookies():
    cookies = request.cookies
    return {name: value for name, value in cookies.items()} 
Example #20
Source File: openid-demo.py    From python-wargaming with MIT License 5 votes vote down vote up
def auth_cb():
    oidconsumer = consumer.Consumer({'id': request.cookies['SESSION_ID']}, None)
    result = oidconsumer.complete(request.args, 'http://127.0.0.1:5000/auth_cb')
    if result.status == consumer.SUCCESS:
        account_id, nickname = urllib.parse.urlparse(
            request.args['openid.identity']).path.split('/')[2].split('-')
        response = redirect('/')
        response.set_cookie('account_id', account_id)
        response.set_cookie('nickname', nickname)
        return response
    return render_template_string(HTML_TEMPLATE, error=result) 
Example #21
Source File: screenshots.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def auth(self, user: "User") -> WebDriver:
        # Setting cookies requires doing a request first
        driver = self.create()
        driver.get(headless_url("/login/"))
        return self._auth_func(driver, user) 
Example #22
Source File: server.py    From tavern with MIT License 5 votes vote down vote up
def expect_cookie():
    cookie_name = _maybe_get_cookie_name()
    if cookie_name not in request.cookies:
        return (
            jsonify({"error": "No cookie named {} in request".format(cookie_name)}),
            400,
        )
    else:
        return jsonify({"status": "ok"}), 200 
Example #23
Source File: embed.py    From Titan with GNU Affero General Public License v3.0 5 votes vote down vote up
def cookietest2():
    js = "window._3rd_party_test_step2_loaded("
    if "third_party_c_t" in request.cookies and request.cookies["third_party_c_t"] == "works":
        js = js + "true"
    else:
        js = js + "false"
    js = js + ");"
    response = make_response(js, 200, {'Content-Type': 'application/javascript'})
    response.set_cookie('third_party_c_t', "", expires=0, samesite='None')
    return response 
Example #24
Source File: single.py    From learning-python with MIT License 5 votes vote down vote up
def set_cookie():
    if 'num' in request.cookies:
        count = int(request.cookies['num']) + 1
    else:
        count = 0

    # 每个view最后返回的都是response对象,render_template内部做了处理
    # 也可以这样表示response = make_response(render_template('index.html', count=100))
    # 不设置max_age和expires时,默认是会话cookie,浏览器关闭后cookie就失效
    # domain可以设置跨域cookie,如domain=".example.com",这样cookie可以 被"www.example.com,alex.example.com"共享
    response = app.make_response(str(count))
    response.set_cookie('num', value=count, max_age=None, expires=None, domain=None)
    return response 
Example #25
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def response_text_rewrite(resp_text):
    """
    rewrite urls in text-like content (html,css,js)
    :type resp_text: str
    :rtype: str
    """
    # v0.20.6+ plain replace domain alias, support json/urlencoded/json-urlencoded/plain
    if url_custom_redirect_enable:
        for before_replace, after_replace in (plain_replace_domain_alias + parse.temporary_domain_alias):
            resp_text = resp_text.replace(before_replace, after_replace)

    # v0.9.2+: advanced url rewrite engine
    resp_text = regex_adv_url_rewriter.sub(regex_url_reassemble, resp_text)

    if developer_string_trace is not None and developer_string_trace in resp_text:
        # debug用代码, 对正常运行无任何作用
        infoprint('StringTrace: appears after advanced rewrite, code line no. ', current_line_number())

    # v0.28.0 实验性功能, 在v0.28.3后默认启用
    resp_text = response_text_basic_mirrorlization(resp_text)

    if developer_string_trace is not None and developer_string_trace in resp_text:
        # debug用代码, 对正常运行无任何作用
        infoprint('StringTrace: appears after basic mirrorlization, code line no. ', current_line_number())

    # for cookies set string (in js) replace
    # eg: ".twitter.com" --> "foo.com"
    resp_text = resp_text.replace('\".' + target_domain_root + '\"', '\"' + my_host_name_no_port + '\"')
    resp_text = resp_text.replace("\'." + target_domain_root + "\'", "\'" + my_host_name_no_port + "\'")
    resp_text = resp_text.replace("domain=." + target_domain_root, "domain=" + my_host_name_no_port)
    resp_text = resp_text.replace('\"' + target_domain_root + '\"', '\"' + my_host_name_no_port + '\"')
    resp_text = resp_text.replace("\'" + target_domain_root + "\'", "\'" + my_host_name_no_port + "\'")

    if developer_string_trace is not None and developer_string_trace in resp_text:
        # debug用代码, 对正常运行无任何作用
        infoprint('StringTrace: appears after js cookies string rewrite, code line no. ', current_line_number())

    # resp_text = resp_text.replace('lang="zh-Hans"', '', 1)
    return resp_text 
Example #26
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 #27
Source File: test_plugin_flask.py    From spectree with Apache License 2.0 5 votes vote down vote up
def user_score(name):
    score = [randint(0, request.context.json.limit) for _ in range(5)]
    score.sort(reverse=request.context.query.order)
    assert request.context.cookies.pub == 'abcdefg'
    assert request.cookies['pub'] == 'abcdefg'
    return jsonify(name=request.context.json.name, score=score) 
Example #28
Source File: flask_plugin.py    From spectree with Apache License 2.0 5 votes vote down vote up
def request_validation(self, request, query, json, headers, cookies):
        req_query = request.args or {}
        req_json = request.get_json() or {}
        req_headers = request.headers or {}
        req_cookies = request.cookies or {}
        request.context = Context(
            query.parse_obj(req_query) if query else None,
            json.parse_obj(req_json) if json else None,
            headers.parse_obj(req_headers) if headers else None,
            cookies.parse_obj(req_cookies) if cookies else None,
        ) 
Example #29
Source File: flask_plugin.py    From spectree with Apache License 2.0 5 votes vote down vote up
def validate(self,
                 func,
                 query, json, headers, cookies, resp,
                 before, after,
                 *args, **kwargs):
        from flask import request, abort, make_response, jsonify

        response, req_validation_error, resp_validation_error = None, None, None
        try:
            self.request_validation(request, query, json, headers, cookies)
        except ValidationError as err:
            req_validation_error = err
            response = make_response(jsonify(err.errors()), 422)

        before(request, response, req_validation_error, None)
        if req_validation_error:
            abort(response)

        response = make_response(func(*args, **kwargs))

        if resp and resp.has_model():
            model = resp.find_model(response.status_code)
            if model:
                try:
                    model.validate(response.get_json())
                except ValidationError as err:
                    resp_validation_error = err
                    response = make_response(jsonify(
                        {'message': 'response validation error'}
                    ), 500)

        after(request, response, resp_validation_error, None)

        return response 
Example #30
Source File: login_utils.py    From app with MIT License 5 votes vote down vote up
def get_referral() -> Optional[Referral]:
    """Get the eventual referral stored in cookie"""
    # whether user arrives via a referral
    referral = None
    if request.cookies:
        ref_code = request.cookies.get(_REFERRAL_COOKIE)
        referral = Referral.get_by(code=ref_code)

    return referral