Exemple #1
0
 def cookies(self):
     try:
         cookie = hcookies.BaseCookie()
         cookie.load(self.headers.get("cookie"))
         return cookie
     except Exception as e:
         return hcookies.BaseCookie()
Exemple #2
0
 def cookies(self):
     try:
         cookie = hcookies.BaseCookie()
         for _, v in self.headers.pairs('set-cookie'):
             cookie.load(v)
         return cookie
     except Exception as e:
         return hcookies.BaseCookie()
def get_raw_refresh_token(event) -> str:
    headers = canonicalize_headers(event['headers'])
    try:
        request_cookies = cookies.BaseCookie(headers['cookie'][0])
        raw_refresh_token = request_cookies[
            get_config().cookie_name_refresh_token].value
    except (KeyError, IndexError):
        structlog.get_logger().log("No refresh_token cookie found")
        raise NotLoggedIn()
    return raw_refresh_token
Exemple #4
0
 def set_cookies(self, c):
     self.headers.delete("set-cookie")
     if isinstance(c, hcookies.BaseCookie):
         cookies = c
     else:
         cookies = hcookies.BaseCookie()
         for k, v in c.items():
             cookies[k] = v
     for _, m in c.items():
         self.headers.add("Set-Cookie", m.OutputString())
Exemple #5
0
 def on_header(self, name, value):
     key = _normalize_header_key(name.decode('utf-8'))
     if key == 'Cookie':
         self.request.cookies = cookies.BaseCookie(value.decode('utf-8'))
     elif key in {'X-Forwarded-For', 'X-Real-Ip'}:
         try:
             self.request.remote_ip = \
                 str(ipaddress.ip_address(value.split(',')[-1].strip()))
         except ValueError:
             pass
     elif key in {'X-Scheme', 'X-Forwarded-Proto'}:
         self.request.protocol = value.decode('utf-8')
     elif key == 'Host':
         self.request.host = value.decode('utf-8')
     self.request.headers[key] = value.decode('utf-8')
def validate_request(event: dict) -> VerifyAccessRequest:
    headers = canonicalize_headers(event['headers'])
    request_cookies = cookies.BaseCookie(headers['cookie'][0])
    access_token = request_cookies[get_config().cookie_name].value

    token = jwt.decode(  # may raise
        access_token,
        key=get_jwt_secret(),
        algoritms=['HS256'],
        verify=True,
    )
    structlog.get_logger().log("Valid access token found", jwt=token)

    return_to = event['queryStringParameters']['return_to']

    return VerifyAccessRequest(
        raw_token=access_token,
        access_token=token,
        return_to=return_to,
    )
def validate_login_cookie(event: dict) -> dict:
    """
    Validates the login cookie.
    Returns the decoded token, or raises NotLoggedInError.
    :raises: NotLoggedInError
    """
    headers = canonicalize_headers(event['headers'])

    try:
        request_cookies = cookies.BaseCookie(headers['cookie'][0])
        login_token = request_cookies[get_config().login_cookie_name].value

        token = jwt.decode(  # may raise
            login_token,
            key=get_jwt_secret(),
            algoritms=['HS256'],
            verify=True,
        )
        structlog.get_logger().log("Valid login token found", jwt=token)
        return token
    except KeyError as e:
        raise NotLoggedInError("No login cookie found") from e
    except jwt.exceptions.InvalidTokenError as e:
        raise NotLoggedInError("Invalid login cookie") from e
Exemple #8
0
def get_cookie_dict_from_headers(r):
    cookie = cookies.BaseCookie()
    if r.headers.get("Cookie"):
        cookie.load(r.headers.get("Cookie"))
    return cookie
Exemple #9
0
def get_session_token(request):
    if 'HTTP_COOKIE' in request:
        kakor = cookies.BaseCookie(request['HTTP_COOKIE'])
        if "session_token" in kakor:
            return kakor["session_token"].value
    return False
Exemple #10
0
        def handle_response(self, response, context={}, error=False):

            if not isinstance(response, ResponseObj):
                if debug_level >= 4:
                    print("<<<<<<<< RESPONSE <<<<<<<")
                    pprint.pprint(response.__dict__)

                responseobj = ResponseObj(
                    code=response.code,
                    headers=response.headers,
                    pass_headers=True,
                    body=response.body,
                    context=context,
                )
            else:
                responseobj = response

            if debug_level >= 3:
                print("<<<<<<<< RESPONSEOBJ <<<<<<<")
                responseprint = copy(responseobj)
                responseprint.body = "-- body content not displayed --"
                pprint.pprint(responseprint.__dict__)

            if not error:
                mod = resp_callback(responseobj)
            else:
                mod = err_callback(responseobj)

            # set the response status code

            if mod.code == 599:
                self.set_status(500)
                self.write('Internal server error. Server unreachable.')
                self.finish()
                return

            self.set_status(mod.code)

            # set the response headers

            if type(mod.pass_headers) == bool:
                header_keys = mod.headers.keys() if mod.pass_headers else []
            else:
                header_keys = mod.pass_headers
            for key in header_keys:
                if key.lower() == "set-cookie":
                    cookies = Cookie.BaseCookie()
                    cookies.load(tornado.escape.native_str(mod.headers.get(key)))
                    for cookie_key in cookies:
                        cookie = cookies[cookie_key]
                        params = dict(cookie)
                        expires = params.pop('expires', None)
                        if expires:
                            expires = dateutil.parser.parse(expires)
                        self.set_cookie(
                            cookie.key,
                            cookie.value,
                            expires = expires,
                            **params
                        )
                else:
                    val = mod.headers.get(key)
                    self.set_header(key, val)

            if debug_level >= 2:
                print(">>>>>>>> RESPONSE (%s) >>>>>>>" % mod.code)
                for k, v in self._headers.items():
                    print("%s: %s" % (k, v))
                if hasattr(self, '_new_cookie'):
                    print(self._new_cookie.output())

            # set the response body

            if mod.body:
                self.write(mod.body)

            self.finish()
def test_headers_cookie():
    cookie = cookielib.BaseCookie('a=b; domain=.example.com')
    assert headers([cookie]) == {"set-cookie": "a=b; Domain=.example.com"}
Exemple #12
0
conn = sqlite3.connect('BajtaHack.db')
c = conn.cursor()

#c.execute("DROP TABLE IF EXISTS users")
c.execute("CREATE TABLE IF NOT EXISTS passwords ( password PRIMARY KEY)")
c.execute("CREATE TABLE IF NOT EXISTS users (name TEXT, mac TEXT PRIMARY KEY)")
c.execute("DROP TABLE IF EXISTS active")
c.execute("CREATE TABLE IF NOT EXISTS active (mac TEXT, FOREIGN KEY (mac) REFERENCES users(mac))")
c.execute("INSERT OR IGNORE INTO passwords (password) VALUES ('izviren')")
conn.commit()

static_cooke_lol = set()

expiration = datetime.datetime.now() + datetime.timedelta(days=30)
cookie = cookies.BaseCookie()
cookie["session"] = static_cooke_lol
cookie["session"]["domain"] = "never.sleep.com"
cookie["session"]["path"] = "/main.html"
cookie["session"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")
cookie.update()
print(cookie.output())


def get_mac_from_ip(ip):
    return arpreq.arpreq(ip)


def get_file(filename):
    with open("web/" + filename, "rb") as f:
        return f.read()