Пример #1
0
def cookie_from_string(text: str, domain: str) -> Cookie:
    tokens = [t.strip() for t in text.split(";")]

    name, value = tokens[0].split("=")

    path = None
    expires = None

    for tok in tokens[1:]:
        k, v = tok.split("=")
        if k == "path":
            path = v
        if k == "expires":
            expires = parse(v).timestamp()

    return Cookie(
        version=0,
        name=name, value=value,
        port=None, port_specified=False,
        domain=domain, domain_specified=True, domain_initial_dot=False,
        path=path, path_specified=path is not None,
        secure=False,
        expires=expires,
        discard=None,
        comment=None,
        comment_url=None,
        rest=None,
        rfc2109=False
    )
Пример #2
0
def merge_cookies_into_session(cookies_input):
    jar = _context.session.cookies
    if isinstance(cookies_input, list):
        for item in cookies_input:
            cookie = Cookie(
                0,
                item['name'],
                item['value'],
                None,
                False,
                item['domain'],
                True,
                bool(item['domain'].startswith(".")),
                item['path'],
                True,
                item['secure'],
                None,
                False,
                "",
                "",
                [],
            )
            jar.set_cookie(cookie)
    else:
        attrs_set = parse_ns_headers(cookies_input.split('; '))
        merge_cookies(
            jar, cookiejar_from_dict({x[0][0]: x[0][1]
                                      for x in attrs_set}))
Пример #3
0
    def login(self, mcj):
        if self.error:
            return None
        # if we wanna use https we mast add ssl=enable_ssl to cookie
        mcj.set_cookie(Cookie(0, "ssl", "enable_ssl", None, False,
                              ".nnmclub.to", True, False, "/", True,
                              False, None, False, None, None, {}))
        self.session.add_handler(HTTPCookieProcessor(mcj))

        response = self._catch_error_request(self.url_login)
        if not response:
            return None
        code = RE_CODE.search(response.decode('cp1251'))[1]
        form_data = {"username": config['username'],
                     "password": config['password'],
                     "autologin": "******",
                     "code": code,
                     "login": "******"}
        # so we first encode vals to cp1251 then do default decode whole string
        data_encoded = urlencode(
            {k: v.encode('cp1251') for k, v in form_data.items()}
        ).encode()

        self._catch_error_request(self.url_login, data_encoded)
        if self.error:
            return None
        logger.debug(f"That we have: {[cookie for cookie in mcj]}")
        if 'phpbb2mysql_4_sid' in [cookie.name for cookie in mcj]:
            mcj.save(FILE_C, ignore_discard=True, ignore_expires=True)
            logger.info('We successfully authorized')
        else:
            self.error = "We not authorized, please check your credentials!"
            logger.warning(self.error)
Пример #4
0
def authorize(request):
    phone_number = ""
    if not os.path.exists('green/config.json'):
        while(True):
            phone_number = input("Enter you phone number (+375XXXXXXXXX): ")
            if re.match(r"^\+375([29|44|25|33]{2})(\d{7})$", phone_number):
                break
            else:
                print("Try again and in correct format")
        request.post('https://shop.green-market.by/api/v1/auth/request-confirm-code/', json={"phoneNumber" : phone_number})
        response = request.post('https://shop.green-market.by/api/v1/auth/verify-confirm-code/', json={"phoneNumber": phone_number, "code" : input("Enter your code: ")})
        if response.status_code == STATUS_OK:
            with open("green/config.json", "w") as write_file:
                write_file.write(json.dumps(response.cookies._cookies['shop.green-market.by']['/']['Authorization'].__dict__))
        else:
            print("invalid phone number or code")
            return request
    else:
        with open("green/config.json", "r") as read_file:
            cookie = json.load(read_file)
        request.cookies.set_cookie(Cookie(*cookie.values()))
    user_info = request.get('https://shop.green-market.by/api/v1/users/me').json()
    if user_info.get('pickUpStoreId'):
        global store_id
        store_id = user_info.get('pickUpStoreId')
    return request
Пример #5
0
def create_cookie(name, value, **kwargs):
    """Make a cookie from underspecified parameters.

    By default, the pair of `name` and `value` will be set for the domain ''
    and sent on every request (this is sometimes called a "supercookie").
    """
    result = dict(
        version=0,
        name=name,
        value=value,
        port=None,
        domain='',
        path='/',
        secure=False,
        expires=None,
        discard=True,
        comment=None,
        comment_url=None,
        rest={'HttpOnly': None},
        rfc2109=False,
    )
    badargs = set(kwargs) - set(result)
    if badargs:
        err = 'create_cookie() got unexpected keyword arguments: %s'
        raise TypeError(err % list(badargs))
    result.update(kwargs)
    result['port_specified'] = bool(result['port'])
    result['domain_specified'] = bool(result['domain'])
    result['domain_initial_dot'] = result['domain'].startswith('.')
    result['path_specified'] = bool(result['path'])
    return Cookie(**result)
Пример #6
0
def start(args):
    """Login and session handler
    """
    # create cookiejar
    args._cj = LWPCookieJar()

    # lets urllib handle cookies
    opener = build_opener(HTTPCookieProcessor(args._cj))
    opener.addheaders = [(
        "User-Agent",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36"
    ), ("Accept-Encoding", "identity"), ("Accept-Charset", "utf-8"),
                         ("DNT", "1")]
    install_opener(opener)

    # load cookies
    try:
        args._cj.load(getCookiePath(args), ignore_discard=True)
    except IOError:
        # cookie file does not exist
        pass

    args._cj.set_cookie(
        Cookie(0, "timezoneoffset", str(timezone // 60), None, False,
               "www.wakanim.tv", False, False, "/", True, False, None, False,
               None, None, {"HttpOnly": None}, False))
Пример #7
0
def get_cookie(value='test'):
    """Helper to create a cookie, which is quite long."""
    return Cookie(
        version=0, name='test-macaroon', value=value, port=None, port_specified=False,
        domain='snapcraft.io', domain_specified=True, domain_initial_dot=False, path='/',
        path_specified=True, secure=True, expires=2595425286, discard=False, comment=None,
        comment_url=None, rest=None, rfc2109=False)
Пример #8
0
 def set(self,
         name: str,
         value: str,
         domain: str = "",
         path: str = "/") -> None:
     cookie = Cookie(
         version=0,
         name=name,
         value=value,
         port=None,
         port_specified=False,
         domain=domain,
         domain_specified=bool(domain),
         domain_initial_dot=domain.startswith("."),
         path=path,
         path_specified=bool(path),
         secure=False,
         expires=None,
         discard=True,
         comment=None,
         comment_url=None,
         rest={},
         rfc2109=False,
     )
     self.jar.set_cookie(cookie)
Пример #9
0
def test_access_invalid_auth_token(service):
    value = """
    .eJwljksOwyAMBe_COpHABgy5TOWv2m3SrKrevUjdzkjz3ic94vTrmY73efuWHi9LR0LjFl5yWAeSPLJ3BcMGLRBnOChDZR_UPKbU6lYWQ_Yw6BrajKP6Eky5OQQTwbKdSV0r0axD2KaKtT6xkYRAWSHMgkKIaUv35ef_DGig9YJ7UOW96uz7pDJ2WXMU4Rm0pO8PiTE6Yg.XcKUnQ.hm2dNwGedmEPV-q8FHuZvgR3Xfg
    """
    cookie = Cookie(
        version=0,
        name="session",
        value=value,
        port=None,
        port_specified=False,
        domain="localhost.local",
        domain_specified=False,
        domain_initial_dot=False,
        path="/",
        path_specified=True,
        secure=False,
        expires=None,
        discard=True,
        comment=None,
        comment_url=None,
        rest={
            "HttpOnly": None
        },  # type: ignore # TODO: Clean up; this shouldn't require an ignore in theory
        rfc2109=False,
    )
    service.client.cookie_jar.set_cookie(cookie)
    response = service.client.get("/api/test/user_protected")
    assert response.status_code == 401
Пример #10
0
    def test_samesite_invalid(self):
        cookie = Cookie(name='SESSIONID',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={'HttpOnly': True, 'SameSite': 'Invalid'},
                        secure=True,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)

        result = cookies(self.reqs)

        self.assertEquals('cookies-samesite-flag-invalid', result['result'])
        self.assertFalse(result['pass'])
        self.assertIsNone(result['sameSite'])
Пример #11
0
 def mock_cookie(self):
     """
     Makes sure that the cookie is there.
     """
     from http.cookiejar import Cookie
     self.cookie_storage.write({
         'example.com': {
             '/': {
                 'NID':
                 Cookie(version=0,
                        name='NID',
                        value='0000',
                        port=None,
                        port_specified=False,
                        domain='example.com',
                        domain_specified=True,
                        domain_initial_dot=True,
                        path='/',
                        path_specified=True,
                        secure=False,
                        expires=1476201395,
                        discard=False,
                        comment=None,
                        comment_url=None,
                        rest={'HttpOnly': None},
                        rfc2109=False)
             }
         }
     })
Пример #12
0
def xuke_login(userName, password):
    s = requests.session()
    cookiefile = 'xkcookies.txt'
    s.cookies = Cookie(cookiefile)
    s.headers['Referer'] = 'http://cas.hdu.edu.cn/cas/login'
    try:
        r = s.get('http://cas.hdu.edu.cn/cas/login', timeout=5)
    except Exception:
        print("请求超时")
        sys.exit(1)
    data = {
        'encodedService': 'http://jxgl.hdu.edu.cn/default.aspx',
        'service': 'http://jxgl.hdu.edu.cn/default.aspx',
        'serviceName': 'null',
        'loginErrCnt': '0',
        'username': userName,
        'password': hashlib.md5(password.encode()).hexdigest(),
        'lt': bs(r.text).select('input[name="lt"]')[0]['value'],
    }
    try:
        r = s.post('http://cas.hdu.edu.cn/cas/login', data=data, timeout=1)
        s.get(bs(r.text).select('a')[0]['href'], timeout=1)
        r = s.get('http://jxgl.hdu.edu.cn/xs_main.aspx?xh=%s' % userName)
        s.cookies.save(ignore_discard=True, ignore_expires=True)
    except Exception:
        print("密码错误,请重新登录")
        sys.exit(1)
    with open(".username", "w") as f:
        f.write(userName)
Пример #13
0
def _init_cookies(cookie_jar: CookieJar, firefox_cookies_path: str):
    """
    Initialize cookies from firefox
    :param cookie_jar:
    :param firefox_cookies_path: Firefox Cookies SQLite file
            For example, in linux, the cookies may at ~/.mozilla/firefox/*/cookies.sqlite
    :return:
    """
    if firefox_cookies_path is None:
        firefox_cookies_path = __COOKIES_PATH
    con = sqlite3.connect(firefox_cookies_path)
    cur = con.cursor()
    # noinspection SqlResolve
    cur.execute("SELECT host, path, isSecure, expiry, name, value FROM moz_cookies")
    for item in cur.fetchall():
        c = Cookie(
            0,
            item[4],
            item[5],
            None,
            False,
            item[0],
            item[0].startswith('.'),
            item[0].startswith('.'),
            item[1],
            False,
            item[2],
            item[3],
            item[3] == "",
            None, None, {}
        )
        cookie_jar.set_cookie(c)
    return cookie_jar
Пример #14
0
 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:
     """
     Set a cookie value by name. May optionally include domain and path.
     """
     kwargs = dict(
         version=0,
         name=name,
         value=value,
         port=None,
         port_specified=False,
         domain=domain,
         domain_specified=bool(domain),
         domain_initial_dot=domain.startswith("."),
         path=path,
         path_specified=bool(path),
         secure=False,
         expires=None,
         discard=True,
         comment=None,
         comment_url=None,
         rest={"HttpOnly": None},
         rfc2109=False,
     )
     cookie = Cookie(**kwargs)  # type: ignore
     self.jar.set_cookie(cookie)
Пример #15
0
 def cookiejar_create(self, cookiejar_file, session):
     cookie_jar = LWPCookieJar(cookiejar_file.name)
     cookie_jar.set_cookie(
         Cookie(0, self.COOKIE_NAME, session, None, False, '', False, True,
                '/', True, True, None, None, None, None, {}))
     cookie_jar.save()
     cookiejar_file.flush()
Пример #16
0
def test_setting_client_cookies_to_cookiejar() -> None:
    """
    Send a request including a cookie, using a `CookieJar` instance.
    """

    url = "http://example.org/echo_cookies"
    cookies = CookieJar()
    cookie = Cookie(
        version=0,
        name="example-name",
        value="example-value",
        port=None,
        port_specified=False,
        domain="",
        domain_specified=False,
        domain_initial_dot=False,
        path="/",
        path_specified=True,
        secure=False,
        expires=None,
        discard=True,
        comment=None,
        comment_url=None,
        rest={"HttpOnly": ""},
        rfc2109=False,
    )
    cookies.set_cookie(cookie)

    client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))
    client.cookies = cookies  # type: ignore
    response = client.get(url)

    assert response.status_code == 200
    assert response.json() == {"cookies": "example-name=example-value"}
Пример #17
0
 def set(self,
         name: str,
         value: str,
         domain: str = "",
         path: str = "/") -> None:
     """
     Set a cookie value by name. May optionally include domain and path.
     """
     kwargs = {
         "version": 0,
         "name": name,
         "value": value,
         "port": None,
         "port_specified": False,
         "domain": domain,
         "domain_specified": bool(domain),
         "domain_initial_dot": domain.startswith("."),
         "path": path,
         "path_specified": bool(path),
         "secure": False,
         "expires": None,
         "discard": True,
         "comment": None,
         "comment_url": None,
         "rest": {
             "HttpOnly": None
         },
         "rfc2109": False,
     }
     cookie = Cookie(**kwargs)  # type: ignore
     self.jar.set_cookie(cookie)
Пример #18
0
    def test_session_cookie_no_secure_but_hsts(self):
        cookie = Cookie(name='SESSIONID',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={'HttpOnly': True},
                        secure=False,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)
        self.reqs['responses']['https'].headers[
            'Strict-Transport-Security'] = 'max-age=15768000'

        result = cookies(self.reqs)

        self.assertEquals(
            'cookies-session-without-secure-flag-but-protected-by-hsts',
            result['result'])
        self.assertFalse(result['pass'])
Пример #19
0
    def test_session_no_httponly(self):
        cookie = Cookie(name='SESSIONID',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={},
                        secure=True,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)

        result = cookies(self.reqs)

        self.assertEquals('cookies-session-without-httponly-flag',
                          result['result'])
        self.assertFalse(result['pass'])
Пример #20
0
    def login(self, mcj):
        if self.error:
            return
        # if we wanna use https we mast add ssl=enable_ssl to cookie
        mcj.set_cookie(Cookie(0, 'ssl', "enable_ssl", None, False,
                              '.rutracker.org', True, False, '/', True,
                              False, None, 'ParserCookie', None, None, None))
        self.session.add_handler(HTTPCookieProcessor(mcj))

        form_data = {"login_username": config['username'],
                     "login_password": config['password'],
                     "login": "******"}
        logger.debug(f"Login. Data before: {form_data}")
        # so we first encode vals to cp1251 then do default decode whole string
        data_encoded = urlencode(
            {k: v.encode('cp1251') for k, v in form_data.items()}).encode()
        logger.debug(f"Login. Data after: {data_encoded}")
        self._catch_error_request(self.url + 'login.php', data_encoded)
        if self.error:
            return
        logger.debug(f"That we have: {[cookie for cookie in mcj]}")
        if 'bb_session' in [cookie.name for cookie in mcj]:
            mcj.save(FILE_C, ignore_discard=True, ignore_expires=True)
            logger.info("We successfully authorized")
        else:
            self.error = "We not authorized, please check your credentials!"
            logger.warning(self.error)
Пример #21
0
    def test_anticsrf_without_samesite(self):
        cookie = Cookie(name='CSRFTOKEN',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={'HttpOnly': True},
                        secure=True,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)

        result = cookies(self.reqs)

        self.assertEquals('cookies-anticsrf-without-samesite-flag', result['result'])
        self.assertFalse(result['pass'])
        self.assertFalse(result['sameSite'])
Пример #22
0
def test_set_cookie_with_cookiejar():
    """
    Send a request including a cookie, using a `CookieJar` instance.
    """

    url = "http://example.org/echo_cookies"
    cookies = CookieJar()
    cookie = Cookie(
        version=0,
        name="example-name",
        value="example-value",
        port=None,
        port_specified=False,
        domain="",
        domain_specified=False,
        domain_initial_dot=False,
        path="/",
        path_specified=True,
        secure=False,
        expires=None,
        discard=True,
        comment=None,
        comment_url=None,
        rest={"HttpOnly": None},
        rfc2109=False,
    )
    cookies.set_cookie(cookie)

    with Client(dispatch=MockDispatch()) as client:
        response = client.get(url, cookies=cookies)

    assert response.status_code == 200
    assert response.json() == {"cookies": "example-name=example-value"}
Пример #23
0
def test_cookie_dict():
    c = RetsHttpClient('login_url', 'username', 'password')
    c._session = mock.MagicMock()
    jar = RequestsCookieJar()
    c1 = Cookie(
        1,
        'name1',
        'value1',
        80,
        80,
        'domain',
        'domain_specified',
        'domain_initial_dot',
        'path',
        'path_specified',
        True,
        True,
        False,
        'comment',
        'comment_url',
        'rest',
    )
    c2 = Cookie(
        1,
        'name2',
        'value2',
        80,
        80,
        'domain',
        'domain_specified',
        'domain_initial_dot',
        'path',
        'path_specified',
        True,
        True,
        False,
        'comment',
        'comment_url',
        'rest',
    )

    jar.set_cookie(c1)
    jar.set_cookie(c2)
    c._session.cookies = jar

    assert c.cookie_dict == {'name1': 'value1', 'name2': 'value2'}
Пример #24
0
 def test_convert_cookie_to_dict(self):
     cook1 = {'name': 'cook1', 'value': 'value1', 'path': '/', 'secure': False, 'expiry': 1453912471}
     cookie = Cookie(
         0, cook1['name'], cook1['value'], None, False, '.github.com', True, True, cook1['path'], True,
         cook1['secure'], cook1['expiry'], False, None, None, None, False
     )
     dict1 = convert_cookie_to_dict(cookie)
     eq_(cook1, dict1)
Пример #25
0
 def create_cookie(self):
     """ Cookie de autorizacion de logueo """
     cookie_jar = CookieJar()
     cookie = Cookie(0, self.cookie_name, self.cookie_value, self.port,
                     None, self.host, None, None, self.path, None, False,
                     None, None, '', '', None, True)
     cookie_jar.set_cookie(cookie)
     return cookie_jar
Пример #26
0
    def test_secure_with_httponly_sessions(self):
        # Python cookies are the literal worst, seriously, the worst
        cookie = Cookie(name='SESSIONID',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={'HttpOnly': None},
                        secure=True,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)

        cookie = Cookie(name='foo',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={},
                        secure=True,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)

        result = cookies(self.reqs)

        self.assertEquals('cookies-secure-with-httponly-sessions',
                          result['result'])
        self.assertTrue(result['pass'])
Пример #27
0
 def save_cookie(self, file_name=None, **kwargs):
     file_name = file_name or self._cookie_file
     lwp_jar = LWPCookieJar()
     for item in self._cookie_jar:
         args = dict(vars(item).items())
         args['rest'] = args['_rest']
         del (args['_rest'])
         cookie = Cookie(**args)
         lwp_jar.set_cookie(cookie)
     lwp_jar.save(file_name, **kwargs)
Пример #28
0
def test_foggycam_unpickle_cookies():
    foggycam = FoggyCam("joey-tribianni","how-you-doin")
    
    cztoken_cookie = Cookie(None, 'cztoken', 'b.000000000', None, None, 'home.nest.com', 
       None, None, '/', None, False, False, 'TestCookie', None, None, None)

    foggycam.cookie_jar.set_cookie(cztoken_cookie)
    foggycam.pickle_cookies()
    foggycam.unpickle_cookies()

    assert foggycam.nest_access_token
Пример #29
0
def cookie_from_str(cookie_str):
    from http.cookiejar import split_header_words, LWPCookieJar, LoadError, Cookie, iso2time
    import time

    cookie_str = cookie_str.split('\n')
    cookie = LWPCookieJar()

    index = 0
    while 1:

        line = cookie_str[index]
        index += 1
        if line == "": break
        if not line.startswith(HEADER):
            continue
        line = line[len(HEADER):].strip()

        for data in split_header_words([line]):
            name, value = data[0]
            standard = {}
            rest = {}
            for k in BOOLEAN_ATTRS:
                standard[k] = False
            for k, v in data[1:]:
                if k is not None:
                    lc = k.lower()
                else:
                    lc = None
                if (lc in VALUE_ATTRS) or (lc in BOOLEAN_ATTRS):
                    k = lc
                if k in BOOLEAN_ATTRS:
                    if v is None: v = True
                    standard[k] = v
                elif k in VALUE_ATTRS:
                    standard[k] = v
                else:
                    rest[k] = v

            h = standard.get
            expires = h("expires")
            discard = h("discard")
            if expires is not None:
                expires = iso2time(expires)
            if expires is None:
                discard = True
            domain = h("domain")
            domain_specified = domain.startswith(".")
            c = Cookie(h("version"), name, value, h("port"), h("port_spec"),
                       domain, domain_specified, h("domain_dot"), h("path"),
                       h("path_spec"), h("secure"), expires, discard,
                       h("comment"), h("commenturl"), rest)
            cookie.set_cookie(c)
    return cookie
Пример #30
0
    def __init__(self, pstk='B2F39E7B866A4F13A1207FC98790BD1000000'):
        print("This is the B365 constructor")
        super().__init__(self.defaultHeaders)
        
        # some 'constants' to use in the creation of the cookies
        expiry = '1370002304'
        cookie_host = '.bet365.com'
        root = '/'
        port = '80'
        
        # Cookie(version, name, value, port, port_specified, domain,
        # domain_specified, domain_initial_dot, path, path_specified,
        # secure, expires, discard, comment, comment_url, rest, rfc2109=False)
        c = Cookie(0, 'session', 'processform=0', port, True, cookie_host, 
              True, False, root, True, False, expiry, False, 'TestCookie', None, None, False)
        super().addCookie(c)
 
        c = Cookie(0, 'pstk', pstk, port, True, cookie_host, 
              True, False, root, True, False, expiry, False, 'TestCookie', None, None, False)
        super().addCookie(c)
    
        
Пример #31
0
    def _really_load(self, f, filename, ignore_discard, ignore_expires):
        now = time.time()

        magic = f.readline()
        if not re.search(self.magic_re, magic):
            f.close()
            raise LoadError(
                "%r does not look like a Netscape format cookies file" %
                filename)

        try:
            while 1:
                line = f.readline()
                if line == "": break

                # last field may be absent, so keep any trailing tab
                if line.endswith("\n"): line = line[:-1]

                # skip comments and blank lines XXX what is $ for?
                if (line.strip().startswith(("#", "$")) or
                    line.strip() == ""):
                    continue

                domain, domain_specified, path, secure, expires, name, value = \
                        line.split("\t")
                secure = (secure == "TRUE")
                domain_specified = (domain_specified == "TRUE")
                if name == "":
                    # cookies.txt regards 'Set-Cookie: foo' as a cookie
                    # with no name, whereas cookielib regards it as a
                    # cookie with no value.
                    name = value
                    value = None

                initial_dot = domain.startswith(".")
                assert domain_specified == initial_dot

                discard = False
                # curl and Wget set expires to 0 for session cookies.
                if expires == "0" or expires == "":

                    expires = None
                    discard = True

                # assume path_specified is false
                c = Cookie(0, name, value,
                           None, False,
                           domain, domain_specified, initial_dot,
                           path, False,
                           secure,
                           expires,
                           discard,
                           None,
                           None,
                           {})
                if not ignore_discard and c.discard:
                    continue
                if not ignore_expires and c.is_expired(now):
                    continue
                self.set_cookie(c)

        except IOError:
            raise
        except Exception:
            _warn_unhandled_exception()
            raise LoadError("invalid Netscape format cookies file %r: %r" %
                            (filename, line))
Пример #32
0
    def _really_load(self, f, filename, ignore_discard, ignore_expires):
        now = time.time()
        try:
            while 1:
                line = f.readline()
                if line == "":
                    break

                # last field may be absent, so keep any trailing tab
                if line.endswith("\n"):
                    line = line[:-1]

                sline = line.strip()
                # support HttpOnly cookies (as stored by curl or old Firefox).
                if sline.startswith("#HttpOnly_"):
                    line = sline[10:]
                elif sline.startswith("#") or sline == "":
                    continue

                domain, domain_specified, path, secure, expires, name, value = line.split(
                    "\t"
                )
                secure = secure == "TRUE"
                domain_specified = domain_specified == "TRUE"
                if name == "":
                    # cookies.txt regards 'Set-Cookie: foo' as a cookie
                    # with no name, whereas http.cookiejar regards it as a
                    # cookie with no value.
                    name = value
                    value = None

                initial_dot = domain.startswith(".")
                assert domain_specified == initial_dot

                discard = False
                if expires == "":
                    expires = None
                    discard = True

                # assume path_specified is false
                c = Cookie(
                    0,
                    name,
                    value,
                    None,
                    False,
                    domain,
                    domain_specified,
                    initial_dot,
                    path,
                    False,
                    secure,
                    expires,
                    discard,
                    None,
                    None,
                    {},
                )
                if not ignore_discard and c.discard:
                    continue
                if not ignore_expires and c.is_expired(now):
                    continue
                self.set_cookie(c)

        except OSError:
            raise
        except Exception:
            _warn_unhandled_exception()
            raise OSError(
                "invalid Netscape format cookies file %r: %r" % (filename, line)
            )
Пример #33
0
    def load_cookie_data(self, filename,
                         ignore_discard=False, ignore_expires=False):
        """Load cookies from file containing actual cookie data.

        Old cookies are kept unless overwritten by newly loaded ones.

        You should not call this method if the delayload attribute is set.

        I think each of these files contain all cookies for one user, domain,
        and path.

        filename: file containing cookies -- usually found in a file like
         C:\WINNT\Profiles\joe\Cookies\joe@blah[1].txt

        """
        now = int(time.time())

        cookie_data = self._load_cookies_from_file(filename)

        for cookie in cookie_data:
            flags = cookie["FLAGS"]
            secure = ((flags & 0x2000) != 0)
            filetime = (cookie["HIXP"] << 32) + cookie["LOXP"]
            expires = epoch_time_offset_from_win32_filetime(filetime)
            if expires < now:
                discard = True
            else:
                discard = False
            domain = cookie["DOMAIN"]
            initial_dot = domain.startswith(".")
            if initial_dot:
                domain_specified = True
            else:
                # MSIE 5 does not record whether the domain cookie-attribute
                # was specified.
                # Assuming it wasn't is conservative, because with strict
                # domain matching this will match less frequently; with regular
                # Netscape tail-matching, this will match at exactly the same
                # times that domain_specified = True would.  It also means we
                # don't have to prepend a dot to achieve consistency with our
                # own & Mozilla's domain-munging scheme.
                domain_specified = False

            # assume path_specified is false
            # XXX is there other stuff in here? -- e.g. comment, commentURL?
            c = Cookie(0,
                       cookie["KEY"], cookie["VALUE"],
                       None, False,
                       domain, domain_specified, initial_dot,
                       cookie["PATH"], False,
                       secure,
                       expires,
                       discard,
                       None,
                       None,
                       {"flags": flags})
            if not ignore_discard and c.discard:
                continue
            if not ignore_expires and c.is_expired(now):
                continue
            CookieJar.set_cookie(self, c)