Exemplo n.º 1
0
def appendCookies(cookies, newCookies):
    try:
        for c in newCookies:
            cookies.load(c)
        return cookies
    except Exception as e:
        raise e
Exemplo n.º 2
0
	def build_request(self, environ):
		''' builds :class:`.Response` objects. for internal use. '''
		method = environ['REQUEST_METHOD']
		path = environ['PATH_INFO']

		qs = environ.get('QUERY_STRING')
		if qs:
			query = parse_qs(qs)
		else:
			query = {}

		content_length = environ.get('CONTENT_LENGTH')
		if content_length:
			content_length = int(content_length)
		body = (environ['wsgi.input'], content_length)
		content_type = environ.get('CONTENT_TYPE')
		if content_type:
			handler = self.content_handlers.get(content_type)
			if handler:
				body = handler(environ['wsgi.input'], content_length)

		cookies = http.cookies.SimpleCookie()
		http_cookie = environ.get('HTTP_COOKIE')
		if http_cookie:
			cookies.load(http_cookie)

		return Request(self, method, path, query, body, cookies, environ)
Exemplo n.º 3
0
    def from_wsgi(cls, environ):
        """
        Builds a new HttpRequest from the provided WSGI `environ`.

        Args:
            environ (dict): The bag of YOLO that is the WSGI environment

        Returns:
            HttpRequest: A fleshed out request object, based on what was
                present.
        """
        headers = {}
        cookies = {}
        non_http_prefixed_headers = [
            "CONTENT-TYPE",
            "CONTENT-LENGTH",
            # TODO: Maybe in the future, add support for...?
            # 'GATEWAY_INTERFACE',
            # 'REMOTE_ADDR',
            # 'REMOTE_HOST',
            # 'SCRIPT_NAME',
            # 'SERVER_NAME',
            # 'SERVER_PORT',
        ]

        for key, value in environ.items():
            mangled_key = key.replace("_", "-")

            if mangled_key == COOKIE_HEADER:
                cookies = http.cookies.SimpleCookie()
                cookies.load(value)
            elif mangled_key.startswith("HTTP-"):
                headers[mangled_key[5:]] = value
            elif mangled_key in non_http_prefixed_headers:
                headers[mangled_key] = value

        body = ""
        wsgi_input = environ.get("wsgi.input", io.StringIO(""))
        content_length = environ.get("CONTENT_LENGTH", 0)

        if content_length not in ("", 0):
            # StringIO & the built-in server have this attribute, but things
            # like gunicorn do not. Give it our best effort.
            if not getattr(wsgi_input, "closed", False):
                body = wsgi_input.read(int(content_length))
        else:
            content_length = 0

        return cls(
            uri=wsgiref.util.request_uri(environ),
            method=environ.get("REQUEST_METHOD", GET),
            headers=headers,
            body=body,
            scheme=wsgiref.util.guess_scheme(environ),
            port=environ.get("SERVER_PORT", "80"),
            content_length=content_length,
            request_protocol=environ.get("SERVER_PROTOCOL", "HTTP/1.0"),
            cookies=cookies,
        )
Exemplo n.º 4
0
    def handle(self):
        # process available cookies
        cookies = http.cookies.SimpleCookie()
        if 'cookie' in self.request.headers:
            cookies.load(self.request.headers['cookie'])

        # set cookies on request
        self.request.cookies = cookies
Exemplo n.º 5
0
    def handle(self):
        # process available cookies
        cookies = http.cookies.SimpleCookie()
        if 'cookie' in self.request.headers:
            cookies.load(self.request.headers['cookie'])

        # set cookies on request
        self.request.cookies = cookies
Exemplo n.º 6
0
def load_cookies():
    cookies = http.cookies.SimpleCookie()
    with open("cookie", "r") as f:
        cookies.load(f.readline())
    result = {}
    for k, v in cookies.items():
        result[k] = v.value
    return result
Exemplo n.º 7
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/plain; charset=utf-8')]

    path = environ['PATH_INFO']
    query = urllib.parse.parse_qs(environ['QUERY_STRING'])
    username = query['username'][0] if 'username' in query else None
    password = query['password'][0] if 'password' in query else None
    if path == "/register" and username and password:
        product_cursor = cursor.execute(
            'SELECT username FROM users WHERE username = ?', [username])
        product_list = product_cursor.fetchall()
        print(product_list)
        if product_list:
            start_response('200 OK', headers)
            return [("Sorry, username " + username + " is taken.").encode()]
        else:
            connection.execute('INSERT INTO users VALUES (?, ?)',
                               [username, password])
            connection.commit()
            if 'HTTP_COOKIE' in environ:
                start_response('200 OK', headers)
                return [("User " + username +
                         " was successfully registered.").encode()]
    elif path == "/login" and username and password:
        product_cursor = cursor.execute(
            'SELECT * FROM users WHERE username = ? AND password = ?',
            [username, password])
        product_list = product_cursor.fetchall()
        if product_list:
            headers.append(
                ('Set-Cookie', 'session=' + username + ':' + password))
            start_response('200 OK', headers)
            return [("User " + username + " successfully logged in.").encode()]
        else:
            start_response('200 OK', headers)
            return [("Incorrect username or password.").encode()]
    elif path == "/logout":
        headers.append(
            ('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
        start_response('200 OK', headers)
        return [("Logged out").encode()]
    elif path == "/account":
        if 'HTTP_COOKIE' in environ:
            cookies = http.cookies.SimpleCookie()
            cookies.load(environ['HTTP_COOKIE'])
            if 'session' in cookies:
                start_response('200 OK', headers)
                return [("You are logged in").encode()]
            else:
                start_response('200 OK', headers)
                return [("You are not logged in").encode()]
        else:
            start_response('200 OK', headers)
            return [("You are not logged in").encode()]
    else:
        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 8
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/plain; charset=utf-8')]

    path = environ['PATH_INFO']
    params = urllib.parse.parse_qs(environ['QUERY_STRING'])
    un = params['username'][0] if 'username' in params else None
    pw = params['password'][0] if 'password' in params else None

    if path == '/register' and un and pw:
        user = cursor.execute('SELECT * FROM users WHERE username = ?', [un]).fetchall()
        if user:
            start_response('200 OK', headers)
            return ['Sorry, username {} is taken'.format(un).encode()]
        else:
            connection.execute('INSERT INTO users VALUES (?, ?)', [un, pw])
            connection.commit()
            headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
            start_response('200 OK', headers)
            return ['Congratulations, username {} been successfully registered'.format(un).encode()]

    elif path == '/login' and un and pw:
        user = cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', [un, pw]).fetchall()
        if user:
            headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
            start_response('200 OK', headers)
            return ['User {} successfully logged in'.format(un).encode()]
        else:
            start_response('200 OK', headers)
            return ['Incorrect username or password'.encode()]

    elif path == '/logout':
        headers.append(('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
        start_response('200 OK', headers)
        return ['Logged out'.encode()]

    elif path == '/account':
        start_response('200 OK', headers)

        if 'HTTP_COOKIE' not in environ:
            return ['Not logged in'.encode()]

        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        if 'session' not in cookies:
            return ['Not logged in'.encode()]

        [un, pw] = cookies['session'].value.split(':')
        user = cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', [un, pw]).fetchall()
        if user:
            return ['Logged in: {}'.format(un).encode()]
        else:
            return ['Not logged in'.encode()]

    else:
        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 9
0
 def _load_cookies(self):
     """Robustified cookie parser that silently drops invalid cookies."""
     cookies = http.cookies.SimpleCookie()
     for fragment in self.headers.get('cookie', '').split('; '):
         if fragment:
             try:
                 cookies.load(fragment)
             except http.cookies.CookieError:
                 pass
     return cookies
Exemplo n.º 10
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/html; charset=utf-8')]

    path = environ['PATH_INFO']
    params = urllib.parse.parse_qs(environ['QUERY_STRING'])
    un = params['username'][0] if 'username' in params else None
    pw = params['password'][0] if 'password' in params else None

    if path == '/register' and un and pw:
        user = cursor.execute('SELECT * FROM users WHERE username = ?', [un]).fetchall()
        if user:
            start_response('200 OK', headers)
            return ['Sorry, username {} is taken'.format(un).encode()]
        else:
            ###INSERT CODE HERE. Use SQL commands to insert the new username and password into the table that was created.###

    elif path == '/login' and un and pw:
        user = cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', [un, pw]).fetchall()
        if user:
            headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
            start_response('200 OK', headers)
            return ['User {} successfully logged in. <a href="/account">Account</a>'.format(un).encode()]
        else:
            start_response('200 OK', headers)
            return ['Incorrect username or password'.encode()]

    elif path == '/logout':
        headers.append(('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
        start_response('200 OK', headers)
        return ['Logged out. <a href="/">Login</a>'.encode()]

    elif path == '/account':
        start_response('200 OK', headers)

        if 'HTTP_COOKIE' not in environ:
            return ['Not logged in <a href="/">Login</a>'.encode()]

        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        if 'session' not in cookies:
            return ['Not logged in <a href="/">Login</a>'.encode()]

        [un, pw] = cookies['session'].value.split(':')
        user = cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', [un, pw]).fetchall()
        if user:
            return ['Logged in: {}. <a href="/logout">Logout</a>'.format(un).encode()]
        else:
            return ['Not logged in. <a href="/">Login</a>'.encode()]

    elif path == '/':
        ###INSERT CODE HERE. Create two forms. One is to log in with a username and password, the other to register a new username and password.###

    else:
        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 11
0
def get_cookies(event):
    cookie_dict = {}
    try:
        cookies = http.cookies.SimpleCookie()
        cookies.load(event["headers"].get("Cookie", ""))
        for k in cookies:
            morsel = cookies[k]
            cookie_dict[morsel.key] = morsel.value
    except:
        traceback.print_exc()
    return cookie_dict
Exemplo n.º 12
0
def application(environ, start_response):
    headers = [
        ('Content-Type', 'text/plain; charset=utf-8'),
        ('Set-Cookie', 'favoriteColor=red'),
        ('Set-Cookie', 'favoriteNumber=4'),
        ('Set-Cookie', 'name=Jason'),
    ]
    start_response('200 OK', headers)
    cookies = http.cookies.SimpleCookie()
    cookies.load('favoriteColor=red;favoriteNumber=4;name=Jason')
    response = ''
    for key in cookies:
        response += str(key + ': ' + cookies[key].value + '\n')
    return [response.encode()]
Exemplo n.º 13
0
def add_event_params(event, *args, **kwargs):
    params = {}
    event["queryStringParameters"] = event.get(
        "queryStringParameters") if event.get("queryStringParameters") else {}
    params.update(event["queryStringParameters"])
    if event["httpMethod"] == "POST" and event.get("body"):
        body = event["body"]
        update_lists(params, parse_body(body))
    cookie_dict = {}
    try:
        cookies = http.cookies.SimpleCookie()
        cookies.load(event["headers"].get("Cookie", ""))
        for k in cookies:
            morsel = cookies[k]
            cookie_dict[morsel.key] = morsel.value
    except:
        traceback.print_exc()
    params = listify_dict(params)
    params = {"kwargs": params}
    params["single_kwargs"] = unlistify_dict(params["kwargs"])
    params["cookies"] = cookie_dict
    params["path"] = {}
    params["path"]["raw"] = event["path"]
    params["path"]["base"] = event["requestContext"]["path"][:-1 *
                                                             len(event["path"]
                                                                 )].rstrip("/")
    params["path"][
        "full"] = "https://" + event["headers"]["Host"] + params["path"]["raw"]
    params["path"]["full_base"] = "https://" + event["headers"][
        "Host"] + params["path"]["base"]
    if "STATIC_BUCKET" in os.environ and "STATIC_PATH" in os.environ:
        params["path"][
            "static_base"] = "https://s3.amazonaws.com/{STATIC_BUCKET}/{STATIC_PATH}".format(
                **os.environ)
    else:
        params["path"]["static_base"] = params["path"]["base"]
    params["http"] = {}
    params["http"]["Referer"] = event.get("headers", {}).get("Referer", "")
    params["http"]["Referer"] = params["http"]["Referer"] if params["http"][
        "Referer"] else params["path"]["full_base"]
    params["http"]["User-Agent"] = event.get("headers", {}).get("User-Agent")
    params["http"]["Method"] = event["httpMethod"]
    params["redirect"] = params["single_kwargs"].get("redirect",
                                                     params["http"]["Referer"])
    params["redirect"] = params["redirect"] if params["redirect"] else params[
        "path"]["full_base"]
    params["objects"] = {}
    event["params"] = params
    return event
Exemplo n.º 14
0
	def test_cookie(self):
		app = PigWig([])
		r = Response()
		r.set_cookie('cow', 'moo')
		r.set_cookie('duck', 'quack', path='/pond')

		cookies = http.cookies.SimpleCookie()
		for header, value in r.headers:
			if header == 'Set-Cookie':
				cookies.load(value)

		req = Request(app, None, None, None, None, None, cookies, None)
		self.assertEqual(req.cookies['cow'].value, 'moo')
		self.assertEqual(req.cookies['cow']['path'], '/')
		self.assertEqual(req.cookies['duck'].value, 'quack')
		self.assertEqual(req.cookies['duck']['path'], '/pond')
Exemplo n.º 15
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/plain; charset=utf-8'),
               ('Set-Cookie', 'name=Jason'),
               ('Set-Cookie', 'favoriteNumber=4'),
               ('Set-Cookie', 'favoriteColor=red')]
    start_response('200 OK', headers)

    if 'HTTP_COOKIE' in environ:
        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        res = ""
        for key in cookies:
            res += (key + ": " + cookies[key].value + "\n")
        return [res.encode()]
    else:
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 16
0
 def update_cookies(self, values, time_received=None):
     cookies = http.cookies.SimpleCookie()
     if isinstance(time_received, (list, tuple)):
         time_received = time_received[0] if time_received else None
     if isinstance(time_received, str):
         time_received = parsedate_tz(time_received)
         if time_received:
             time_received = mktime_tz(time_received)
     if time_received is None:
         time_received = time.time()
     for value in values:
         cookies.load(value)
     for cookie in cookies.values():
         cookie.time_received = time_received
     self._cookies.update(cookies)
     self.log.debug('Updated cookie headers: %s' % values)
Exemplo n.º 17
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/plain; charset=utf-8'),
               ('Set-Cookie', 'name=Jason'),
               ('Set-Cookie', 'favoriteNumber=4'),
               ('Set-Cookie', 'favoriteColor=red')
               ]
    if 'HTTP_COOKIE' in environ:
        start_response('200 OK', headers)
        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        res = ""
        for key in cookies:
            res += (key + ": " + cookies[key].value + "\n")
        return[res.encode()]
    else:
        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 18
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/plain; charset=utf-8')]

    path = environ['PATH_INFO']
    params = urllib.parse.parse_qs(environ['QUERY_STRING'])
    un = params['username'][0] if 'username' in params else None
    pw = params['password'][0] if 'password' in params else None

    if path == '/register' and un and pw:
        user = cursor.execute('SELECT * FROM users WHERE uid = ?', [un]).fetchall()

        if user:
            start_response('200 OK', headers)
            return ['Sorry, username {} is taken'.format(un).encode()]
        else:
            connection.execute('INSERT INTO users (uid, pwd) VALUES (?, ?)', [un, pw])
            connection.commit()
            start_response('200 OK', [('Content-Type', 'text/plain; charset=utf-8'), ('Set-Cookie', 'session=un:pw')])
            return ['Username {} was successfully registered'.format(un).encode()]

    elif path == '/login' and un and pw:
        user = cursor.execute('SELECT * FROM users WHERE uid = ? AND pwd = ?', [un, pw]).fetchall()
        if user:
            start_response('200 OK', [('Content-Type', 'text/plain; charset=utf-8'), ('Set-Cookie', 'session={}:{}'.format(un, pw))])
            return ['User {} successfully logged in'.format(un).encode()]
        else:
            start_response('200 OK', headers)
            return ['Incorrect username or password'.encode()]

    elif path == '/logout':
        start_response('200 OK', [('Content-Type', 'text/plain; charset=utf-8'), ('Set-Cookie', 'session={}:{}; expires=Sun, 25 Dec 2016 00:15:49 GMT'.format(un, pw))])
        return ['Logged Out'.encode()]

    elif path == '/account':
        start_response('200 OK', headers)
        if 'HTTP_COOKIE' in environ:
            cookies = http.cookies.SimpleCookie()
            cookies.load(environ['HTTP_COOKIE'])
            if 'session' in cookies:
                return ['Currently logged in'.encode()]
            else:
                return ['Currently logged out'.encode()]

    else:
        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 19
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/plain; charset=utf-8'),
               ('Set-Cookie', 'favoriteColor=green'),
               ('Set-Cookie', 'favoriteNumber=79'),
               ('Set-Cookie', 'name=Malachi')]
    start_response('200 OK', headers)
    print(environ)
    if 'HTTP_COOKIE' in environ:
        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        text = ''
        for key in cookies:
            text += (key + ': ' + cookies[key].value)
        return [text.encode()]
    else:
        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 20
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/plain; charset=utf-8'),
               ('Set-Cookie', 'name=Jason'),
               ('Set-Cookie', 'favoriteNumber=4'),
               ('Set-Cookie', 'favoriteColor=red')]

    if 'HTTP_COOKIE' in environ:
        #start_response cannot be set twice, has to be in loop, moved below line from line 10
        start_response('200 OK', headers)
        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        res = ""
        for key in cookies:
            res += (key + ": " + cookies[key].value + "\n")
        return [res.encode()]
    else:
        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 21
0
def application(environ, start_response):

    if 'HTTP_COOKIE' in environ:
        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        if '/counter' in cookies:
            counter = int(cookies['counter'].value) + 1
        else:
            counter = 0
    else:
        counter = 0

    headers = [
        ('Content-Type', 'text/plain; charset=utf-8'),
        ('Set-Cookie', 'counter={}'.format(counter))
    ]

    start_response('200 OK', headers)
    return ['Counter = {}'.format(counter).encode()]
Exemplo n.º 22
0
    def test_headers():
        webdriver = instantiate_webdriver(webdriver_class)
        # TODO: Add more cookie examples with additional fields, such as
        # expires, path, comment, max-age, secure, version, httponly
        cookies = (
            {
                "domain": "127.0.0.1",
                "name": "hello",
                "value": "world"
            },
            {
                "domain": "127.0.0.1",
                "name": "another",
                "value": "cookie"
            },
        )
        # Open the server URL with the WebDriver instance initially so we can
        # set custom cookies
        webdriver.get(echo_header_server)
        for cookie in cookies:
            webdriver.add_cookie(cookie)
        response = webdriver.request("GET",
                                     echo_header_server,
                                     headers={"extra": "header"},
                                     cookies={"extra": "cookie"})
        sent_headers = requests.structures.CaseInsensitiveDict(
            json.loads(response.headers["echo"]))

        # Simply assert that the User-Agent isn't requests' default one, which
        # means that it and the rest of the headers must have been overwritten
        assert sent_headers["user-agent"] != requests.utils.default_user_agent(
        )
        # Check if the additional header was sent as well
        assert "extra" in sent_headers and sent_headers["extra"] == "header"
        cookies = http.cookies.SimpleCookie()
        # Python 2's Cookie module expects a string object, not Unicode
        cookies.load(sent_headers["cookie"])
        assert "hello" in cookies and cookies["hello"].value == "world"
        assert "another" in cookies and cookies["another"].value == "cookie"
        # Check if the additional cookie was sent as well
        assert "extra" in cookies and cookies["extra"].value == "cookie"

        webdriver.quit()
Exemplo n.º 23
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/plain; charset=utf-8'),
               ('Set-Cookie',
                'session=dallan; expires=Sun, 25 Dec 2016 00:15:49 GMT'.format(
                    counter)), ('Set-Cookie', 'weight=140'),
               ('Set-Cookie', 'shoe_size=10')

               #Set cookies here inside the headers
               ]
    start_response('200 OK', headers)

    if 'HTTP_COOKIE' in environ:
        #print(environ['HTTP_COOKIE'])
        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        res = ''
        for key in cookies:
            res += (key + ": " + cookies[key].value + "\n")
        return [res.encode()]
Exemplo n.º 24
0
def get_store(cookie_header: str) -> dict:
    """Given an HTTP cookie header return the store

    Extract the cookie with the name CONFIG.cookie_name from the cookie_header
    parse the JSON from it and return it

    :param cookie_header: The content of the "Cookie" HTTP header
    :return: The value of the cookie
    """
    cookies = http.cookies.SimpleCookie()
    cookies.load(cookie_header)
    if CONFIG.cookie_name in cookies:
        try:
            return json.loads(cookies[CONFIG.cookie_name].value)
        except json.JSONDecodeError:
            logger.error('Unable to parse  JSON from "{}"'.format(
                cookies[CONFIG.cookie_name].value))
            return {}
    else:
        return {}
Exemplo n.º 25
0
    def test_plugins(self):
        webapp = Pluggdapps.webapps['webapp']
        cookie_plugins = query_plugins(webapp, IHTTPCookie)
        assert 'httpcookie' in list(map(pluginname, cookie_plugins))
        for cookp in cookie_plugins:
            cookies = cookp.parse_cookies(refheaders)
            assert 'bcookie' in cookies
            m = cookies['bcookie']
            assert m.key == 'bcookie'
            assert m.value == 'v=2&95d39ed5-7853-4246-8a84-a00e00356edb'
            cookies = cookp.set_cookie(cookies,
                                       'hello',
                                       'world',
                                       expires=dt.datetime(2012, 8, 13),
                                       path="/for/this/path",
                                       comment="some comment",
                                       domain=".x.com",
                                       max_age=10000,
                                       secure=True,
                                       version="1.1",
                                       httponly=True)
            s = cookies['hello'].output()
            assert cookies['hello'].value == 'world'
            assert 'expires=Mon, 13 Aug' in s
            assert 'Path=/for/this/path' in s
            assert 'Comment=some comment' in s
            assert 'Domain=.x.com' in s
            assert 'Version=1.1' in s
            assert 'Max-Age=10000' in s
            assert 'secure;' in s
            assert 'httponly;' in s

            # Signed value
            cookies['newname'] = cookp.create_signed_value('newname', 'world')
            s = cookies['newname'].output()
            del cookies['newname']
            cookies.load(s)
            val = cookp.decode_signed_value('newname',
                                            cookies['newname'].value)
            assert val == 'world'
Exemplo n.º 26
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/plain; charset=utf-8'),
               ('Set-Cookie', 'name=Jason'),
               ('Set-Cookie', 'favoriteNumber=4'),
               ('Set-Cookie', 'favoriteColor=red')]

    if 'HTTP_COOKIE' in environ:
        print("Environ" + str(environ["HTTP_COOKIE"]))
        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        res = ""
        for key in cookies:
            print(str(cookies))
            print("Cookie key name=" + str(cookies["name"].value))
            if cookies["name"] == "Jason":
                cookies["name"] = "Nathan"
            res += (key + ": " + cookies[key].value + "\n")
        start_response('200 OK', headers)
        return [res.encode()]
    else:
        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 27
0
def application(environ, start_response):
    if environ['PATH_INFO'] != '/count':
        start_response('200 OK', [('Content-Type', 'text/plain; charset=utf-8')])
        return ['Unknown app {}'.format(environ['PATH_INFO']).encode()]

    if 'HTTP_COOKIE' in environ:
        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        if 'counter' in cookies:
            counter = int(cookies['counter'].value) + 1
        else:
            counter = 0
    else:
        counter = 0

    headers = [
        ('Content-Type', 'text/plain; charset=utf-8'),
        ('Set-Cookie', 'counter={}'.format(counter))
    ]

    start_response('200 OK', headers)
    return ['Counter = {}'.format(counter).encode()]
Exemplo n.º 28
0
 def test_plugins( self ):
     webapp = Pluggdapps.webapps['webapp']
     cookie_plugins = query_plugins( webapp, IHTTPCookie )
     assert 'httpcookie' in list( map( pluginname, cookie_plugins ))
     for cookp in cookie_plugins :
         cookies = cookp.parse_cookies( refheaders )
         assert 'bcookie' in cookies
         m = cookies['bcookie']
         assert m.key == 'bcookie'
         assert m.value == 'v=2&95d39ed5-7853-4246-8a84-a00e00356edb'
         cookies = cookp.set_cookie( cookies, 'hello', 'world',
                           expires=dt.datetime( 2012, 8, 13 ),
                           path="/for/this/path",
                           comment="some comment",
                           domain=".x.com",
                           max_age=10000,
                           secure=True,
                           version="1.1",
                           httponly=True
                   )
         s = cookies['hello'].output()
         assert cookies['hello'].value == 'world'
         assert 'expires=Mon, 13 Aug' in s
         assert 'Path=/for/this/path' in s
         assert 'Comment=some comment' in s
         assert 'Domain=.x.com' in s
         assert 'Version=1.1' in s
         assert 'Max-Age=10000' in s
         assert 'secure;' in s
         assert 'httponly;' in s
         
         # Signed value
         cookies['newname'] = cookp.create_signed_value( 'newname', 'world' )
         s = cookies['newname'].output()
         del cookies['newname']
         cookies.load( s )
         val = cookp.decode_signed_value( 
                 'newname', cookies['newname'].value )
         assert val == 'world'
Exemplo n.º 29
0
	def build_request(self, environ):
		''' builds :class:`.Response` objects. for internal use. '''
		method = environ['REQUEST_METHOD']
		path = environ['PATH_INFO']
		query = {}
		headers = HTTPHeaders()
		cookies = http.cookies.SimpleCookie()
		body = err = None

		try:
			qs = environ.get('QUERY_STRING')
			if qs:
				query = parse_qs(qs)

			content_length = environ.get('CONTENT_LENGTH')
			if content_length:
				headers['Content-Length'] = content_length
				content_length = int(content_length)
			body = (environ['wsgi.input'], content_length)
			content_type = environ.get('CONTENT_TYPE')
			if content_type:
				headers['Content-Type'] = content_type
				media_type, params = cgi.parse_header(content_type)
				handler = self.content_handlers.get(media_type)
				if handler:
					body = handler(environ['wsgi.input'], content_length, params)

			http_cookie = environ.get('HTTP_COOKIE')
			if http_cookie:
				cookies.load(http_cookie)

			for key in environ:
				if key.startswith('HTTP_'):
					headers[key[5:].replace('_', '-')] = environ[key]
		except Exception as e:
			err = e

		return Request(self, method, path, query, headers, body, cookies, environ), err
Exemplo n.º 30
0
def application(environ, start_response):
    headers = [
        ('Content-Type', 'text/plain; charset=utf-8'),
        ('Set Cookie', 'favoriteColor=red'),
        ('Set Cookie', 'favoriteNumber=4'),
        ('Set Cookie', 'name=Jason')
    ]
    start_response('200 OK', headers)

    if 'HTTP_COOKIE' in environ:
        element = environ['HTTP_COOKIE']

        cookies = http.cookies.SimpleCookie()
        cookies.load(str(element))

        lst = ''
        for key in cookies:
            lst += str(key+': '+cookies[key].value)

        return [lst.encode()]

    else:
        start_response('404 Not Found',headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 31
0
def application(environ, start_response):
    if environ['PATH_INFO'] != '/counter':
        start_response('200 OK',
                       [('Content-Type', 'text/plain; charset=utf-8')])
        return [
            '404 Not Found, stop trying you idiot Unknown app {}'.format(
                environ['PATH_INFO']).encode()
        ]

    if 'HTTP_COOKIE' in environ:
        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        if 'counter' in cookies:
            counter = int(cookies['counter'].value) + 1
        else:
            counter = 0
    else:
        counter = 0

    headers = [('Content-Type', 'text/plain; charset=utf-8'),
               ('Set-Cookie', 'counter={}'.format(counter))]

    start_response('200 OK', headers)
    return ['Counter = {}'.format(counter).encode()]
Exemplo n.º 32
0
 def from_env(environ: Dict[str, Any]) -> 'Cookies':
     cookies = Cookies()     # type: ignore
     if 'HTTP_COOKIE' in environ:
         cookies.load(environ['HTTP_COOKIE'])
     return cookies
Exemplo n.º 33
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/html; charset=utf-8')]

    path = environ['PATH_INFO']
    params = urllib.parse.parse_qs(environ['QUERY_STRING'])
    un = params['username'][0] if 'username' in params else None
    pw = params['password'][0] if 'password' in params else None
    correct = 0
    wrong = 0

    if path == '/register' and un and pw:
        user = cursor.execute('SELECT * FROM users WHERE username = ?', [un]).fetchall()
        if user:
            start_response('200 OK', headers)
            return ['Sorry, username {} is taken'.format(un).encode()]
        else:
            connection.execute('INSERT INTO users VALUES (?, ?)', [un, pw])
            connection.commit()
            headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
            start_response('200 OK', headers)
            return ['Congratulations, username {} been successfully registered. <a href="/account">Account</a>'.format(
                un).encode()]

    elif path == '/login' and un and pw:
        user = cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', [un, pw]).fetchall()
        if user:
            headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
            start_response('200 OK', headers)
            return ['User {} successfully logged in. <a href="/account">Account</a>'.format(un).encode()]
        else:
            start_response('200 OK', headers)
            return ['Incorrect username or password'.encode()]

    elif path == '/logout':
        headers.append(('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
        start_response('200 OK', headers)
        return ['Logged out. <a href="/">Login</a>'.encode()]

    elif path == '/account':
        start_response('200 OK', headers)

        if 'HTTP_COOKIE' not in environ:
            return ['Not logged in <a href="/">Login</a>'.encode()]

        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        if 'session' not in cookies:
            return ['Not logged in <a href="/">Login</a>'.encode()]

        [un, pw] = cookies['session'].value.split(':')
        user = cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', [un, pw]).fetchall()

        #This is where the game begins. This section of is code only executed if the login form works, and if the user is successfully logged in
        if user:


            if 'HTTP_COOKIE' in environ:
                cookies = http.cookies.SimpleCookie()
                cookies.load(environ['HTTP_COOKIE'])


            page = '<!DOCTYPE html><html><head><title>Multiply with Score</title></head><body>'
            if 'factor1' in params and 'factor2' in params and 'answer' in params:
                cookies = http.cookies.SimpleCookie()
                cookies.load(environ['HTTP_COOKIE'])
                if (int(params['factor1'][0]) * int(params['factor2'][0]) == int(params['answer'][0])):
                    correct = int(cookies['correct'].value) + 1
                    wrong= int(cookies['wrong'].value)
                    page += '''
                    <h2 style="background-color:lightgreen">Correct, {}x{}={}</h2>
                    '''.format(params['factor1'][0], params['factor2'][0], params['answer'][0])

                else:
                    wrong = int(cookies['wrong'].value) + 1
                    correct = int(cookies['correct'].value)
                    page += '''
                        <h2 style="background-color:red">Wrong, {}x{}&#8800;{}</h2>
                        '''.format(params['factor1'][0], params['factor2'][0], params['answer'][0])



            elif 'reset' in params:
                correct = 0
                wrong = 0

            headers.append(('Set-Cookie', 'correct={}'.format(correct)))
            headers.append(('Set-Cookie', 'wrong={}'.format(wrong)))


            f1 = random.randrange(10) + 1
            f2 = random.randrange(10) + 1

            page = page + '<h1>What is {} x {}?</h1>'.format(f1, f2)

            answer = []
            answer1 = f1 * f2
            for i in range(3):
                answer.append(random.randrange(100) + 1)
            answer.append(answer1)
            random.shuffle(answer)


            page += '''
                        A: <a href="/account?username={}&amp;password={}&amp;factor1={}&amp;factor2={}&amp;answer={}">{}</a><br>
                        B: <a href="/account?username={}&amp;password={}&amp;factor1={}&amp;factor2={}&amp;answer={}">{}</a><br>
                        C: <a href="/account?username={}&amp;password={}&amp;factor1={}&amp;factor2={}&amp;answer={}">{}</a><br>
                        D: <a href="/account?username={}&amp;password={}&amp;factor1={}&amp;factor2={}&amp;answer={}">{}</a><br>
                      '''.format(un,pw,f1,f2,answer[0],answer[0],un,pw,f1,f2,answer[1],answer[1],un,pw,f1,f2,answer[2],answer[2],un,pw,f1,f2,answer[3],answer[3])

            page += '''<h2>Score</h2>
            Correct: {}<br>
            Wrong: {}<br>
            <a href="/account?reset=true">Reset</a>
            </body></html>'''.format(correct, wrong)

            return [page.encode()]
        else:
            return ['Not logged in. <a href="/">Login</a>'.encode()]

    elif path == '/':
        login_form = '''
        <form action="/login" style="background-color:gold">
            <h1>Login</h1>
            Username <input type="text" name="username"><br>
            Password <input type="password" name="password"><br>
            <input type="submit" value="Log in">
        </form>
        <form action="/register" style="background-color:gold">
            <h1>Register</h1>
            Username <input type="text" name="username"><br>
            Password <input type="password" name="password"><br>
            <input type="submit" value="Register">
        </form>'''
        start_response('200 OK', headers)
        return [login_form.encode()]
    else:
        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 34
0
    config["cycles"] = int(parsed_args.cycles)
if parsed_args.no_cookie_save:
    config["cookiesave"] = False
elif parsed_args.cookie_save:
    config["cookiesave"] = True
if parsed_args.no_login:
    config["login"] = False
elif parsed_args.login:
    config["login"] = True

# Build urllib.request opener
cookieprocessor = urllib.request.HTTPCookieProcessor()
cookies = http.cookiejar.MozillaCookieJar()
if config.get("cookiefilepath") and os.path.isfile(config["cookiefilepath"]):
    try:
        cookies.load(config["cookiefilepath"])
    except IOError as err:
        prtmsg("err_io", str(err))
    else:
        debug_prt('Cookies loaded from "{}"', config["cookiefilepath"])
cookieprocessor.cookiejar = cookies
defopener = urllib.request.build_opener(cookieprocessor, httphandler)
urllib.request.install_opener(defopener)

# Alternative actions
if "genconf" in parsed_args:
    genconf((parsed_args.genconf if None != parsed_args.genconf else "-"), False, parsed_args.separate)
    exit()
elif "genfullconf" in parsed_args:
    genconf((parsed_args.genfullconf if None != parsed_args.genfullconf else "-"), True, parsed_args.separate)
    exit()
Exemplo n.º 35
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/html; charset=utf-8')]
    path = environ['PATH_INFO']
    post_env = environ.copy()
    post_env['QUERY_STRING'] = ''
    post = cgi.FieldStorage(fp=environ['wsgi.input'],
                            environ=post_env,
                            keep_blank_values=True)
    #print('hello loser 2.0')
    un = post['username'].value if 'username' in post else None
    pw = post['password'].value if 'password' in post else None
    print(un, pw)
    if path == '/register' and un and pw:
        print('hello loser')
        user = cursor.execute('SELECT * FROM users WHERE username = ?',
                              [un]).fetchall()
        if user:
            start_response('200 OK', headers)
            return ['Sorry, username {} is taken'.format(un).encode()]
        else:
            start_response('200 OK', headers)
            cursor.execute('INSERT INTO users (username,password) VALUES(?,?)',
                           (un, pw))
            connection.commit()
            connection.close()
            return ['User created successfully'.encode()]
        ### insert code here###

    elif path == '/login' and un and pw:
        user = cursor.execute(
            'SELECT * FROM users WHERE username = ? AND password = ?',
            [un, pw]).fetchall()
        if user:
            headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
            start_response('200 OK', headers)
            return [
                'User {} successfully logged in. <a href="/account"> Account </a>'
                .format(un).encode()
            ]
        else:
            start_response('200 OK', headers)
            return ['Incorrect username or password'.encode()]
    elif path == '/logout':
        headers.append(
            ('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
        start_response('200 OK', headers)
        return ['Logged out. <a href="/">Login</a>'.encode()]

    elif path == '/account':
        start_response('200 OK', headers)
        if 'HTTP_COOKIE' not in environ:
            return ['Not logged in <a href="/">Login</a>'.encode()]
        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        if 'session' not in cookies:
            return ['Not logged in <a href="/">Login</a>'.encode()]
        [un, pw] = cookies['session'].value.split(':')
        user = cursor.execute(
            'SELECT * FROM users WHERE username = ? AND password = ?'[
                un, pw]).fetchall()
        if user:
            return [
                'Logged in: {}. <a href="/">Logout</a>'.formar(un).encode()
            ]

        else:
            return ['Not logged in. <a href="/">Login</a>'.encode()]

    elif path == '/':

        start_response('200 OK', headers)
        page = [b"<html>", registerform.encode(), b"</html>"]
        headers = [('content-type', 'text/html')]
        return page

    else:

        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 36
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/html; charset=utf-8')]

    path = environ['PATH_INFO']
    params = urllib.parse.parse_qs(environ['QUERY_STRING'])
    un = params['username'][0] if 'username' in params else None
    pw = params['password'][0] if 'password' in params else None

    if path == '/register' and un and pw:
        start_response('200 OK', headers)
        user = cursor.execute('SELECT * FROM userTable WHERE username = ?', [un]).fetchall()
        if user:

            return ['Sorry, username {} is taken. <a href="/"Login</a>'.format(un).encode()]
        else:
            connection.execute('INSERT INTO userTable VALUES (?, ?)', [un, pw])
            connection.commit()
            return ['Username {} was been successfully registered. <a href="/"Login</a>'.format(un).encode()]
            ###INSERT CODE HERE. Use SQL commands to insert the new username and password into the table that was created.###

    elif path == '/login' and un and pw:
        user = cursor.execute('SELECT * FROM userTable WHERE username = ? AND password = ?', [un, pw]).fetchall()
        if user:
            headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
            start_response('200 OK', headers)
            return ['User {} successfully logged in. <a href="/account">Account</a>'.format(un).encode()]
        else:
            start_response('200 OK', headers)
            return ['Incorrect username or password'.encode()]

    elif path == '/logout':
        headers.append(('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
        start_response('200 OK', headers)
        return ['Logged out. <a href="/">Login</a>'.encode()]

    elif path == '/account':
        start_response('200 OK', headers)

        if 'HTTP_COOKIE' not in environ:
            return ['Not logged in <a href="/">Login</a>'.encode()]

        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        if 'session' not in cookies:
            return ['Not logged in <a href="/">Login</a>'.encode()]

        [un, pw] = cookies['session'].value.split(':')
        user = cursor.execute('SELECT * FROM userTable WHERE username = ? AND password = ?', [un, pw]).fetchall()
        if user:
            return ['Logged in: {}. <a href="/logout">Logout</a>'.format(un).encode()]
        else:
            return ['Not logged in. <a href="/">Login</a>'.encode()]

    elif path == '/':
        page = '''<form action = "/login"
        style = "background-color:gold" >
        <h1> Login </h1>
        Username <input type = "text" name = "username"> <br>
        Password <input type = "password" name = "password"> <br>
        <input type = "submit" value = "Log in">
    </form>
    <hr>
    <form action = "/register" style = "background-color:gold">
    <h1> Register </h1>
    Username <input type = "text" name = "username"> <br>
    Password <input type = "password" name = "password"> <br>
    <input type = "submit" value = "Register">
    </form>'''

        ###INSERT CODE HERE. Create two forms. One is to log in with a username and password, the other to register a new username and password.###
        start_response('200 OK', headers)
        return [page.encode()]
    else:
        start_response('404 Not Found', headers)
        return ['Status 404: Resource not found'.encode()]
Exemplo n.º 37
0
    def convertAsync(self,config):
        if (config != None):
            config['clientName'] = "PYTHON"
            config['clientVersion'] = PDFreactor.VERSION;

        url = self.url + "/convert/async.json"
        if (self.apiKey != None):
            url += '?apiKey=' + self.apiKey
        result = ""
        if len(self.__headers.keys()) == False:
            headers = self.__headers
        else :
            headers = {}
            for (key, value) in self.__headers.items():
                lcKey = key.lower()
                if lcKey != "content-type" and lcKey != "range" and lcKey != "user-agent":
                    headers[key] = value
        headers['Content-Type'] = 'application/json'
        headers['Cookie'] = '; '.join(['%s=%s' % (key, value) for (key, value) in self.__cookies.items()])
        headers['User-Agent'] = 'PDFreactor Python API v4'
        headers['X-RO-User-Agent'] = 'PDFreactor Python API v4'
        req = None
        if sys.version_info[0] == 2:
            from urllib2 import HTTPError
        else:
            from urllib.error import HTTPError
        try:
            if sys.version_info[0] == 2:
                import Cookie
                from Cookie import SimpleCookie
                import urllib2
                from urllib2 import URLError
                options = json.dumps(config)
                req = urllib2.Request(url, options, headers)
                response = urllib2.urlopen(req)
            else:
                import http.cookies
                from http.cookies import SimpleCookie
                import urllib.request
                options = json.dumps(config)
                req = urllib.request.Request(url, options.encode(), headers)
                response = urllib.request.urlopen(req)
        except HTTPError as e:
            if (e.code == 422):
                raise Exception(json.loads(e.read())['error'])
            elif (e.code == 400):
                raise Exception('Invalid client data. ' + json.loads(e.read())['error'])
            elif (e.code == 404):
                raise Exception('Error connecting to PDFreactor Web Service at ' + self.url + '. Please make sure the PDFreactor Web Service is installed and running ' + json.loads(e.read())['error'])
            elif (e.code == 403):
                raise Exception('Request rejected. ' + json.loads(e.read())['error'])
            elif (e.code == 401):
                raise Exception('Unauthorized. ' + json.loads(e.read())['error'])
            elif (e.code == 413):
                raise Exception('The configuration is too large to process.')
            elif (e.code == 500):
                raise Exception(json.loads(e.read())['error'])
            elif (e.code == 503):
                raise Exception('Asynchronous conversions are unavailable.')
            elif (e.code > 400):
                raise Exception('PDFreactor Web Service error (status: ' + str(e.code) + ').')
        except Exception as e:
            raise Exception('Error connecting to PDFreactor Web Service at ' + self.url + '. Please make sure the PDFreactor Web Service is installed and running (Error: ' + str(e.reason) + ')')
        documentId = None;
        if (response != None and response.info() != None):
            location = response.info().getheader("Location")
            if (location != None):
                documentId = location[location.rfind("/")+1:len(location)]
            cookieHeader = response.info().getheader("Set-Cookie")
            if (cookieHeader != None):
                self.stickyMap[documentId] = {'cookies': {}, 'keepDocument': config['keepDocument'] if ('keepDocument' in config) else False}
                cookies = SimpleCookie()
                cookies.load(cookieHeader)
                for name in cookies:
                    self.stickyMap[documentId]['cookies'][name] = cookies[name].value
        return documentId
Exemplo n.º 38
0
    if value == "":
        value = "&nbsp;&nbsp;&nbsp;"
    
    return """<span style="%(label_style)s" id="%(label)s" ondblclick="$('#%(input)s').val($('#%(label)s').text()); $('#%(label)s').hide(); $('#%(input)s').show(); $('#%(input)s').select();">%(value)s</span><input style="display:none; margin:-2px;" type="text" name="value" id="%(input)s" size="%(size)s" value="" onblur="$('#%(label)s').load('web.py', {'mode':'edit_one_field','table':'%(table)s','field':'%(field)s','where':'%(where)s','value':$('#%(input)s').val()}, function () {$('#%(label)s').show(); $('#%(input)s').hide();});" />""" % {
    "table": table,
    "field": field,
    "where": where_field,
    "value": value,
    "label_style": label_style,
    "size": size,
    
    "label": "label_%s_%s_%s" % (field, data['double_click_id_cache'], data['uid']),
    "input": "input_%s_%s_%s" % (field, data['double_click_id_cache'], data['uid']),
    }

# Cookies are loaded and set automatically by web.py, to alter them simply use the below functions
cookies = cookies.SimpleCookie()
cookies.load(os.environ.get('HTTP_COOKIE', ''))

def set_cookie(name, value):
    cookies[name] = value

def delete_cookie(name):
    del(cookies[name])

def get_cookie(name, default=None):
    if name in cookies:
        return cookies[name].value
    else:
        return default
Exemplo n.º 39
0
# coding = utf-8
import http.cookies

cookies = http.cookies.SimpleCookie('name=louis')
cookies['pass'] = '******'
cookies.load('work=swim')
print(cookies.output())
out = cookies.output()
print(type(out))
print(out.encode('utf-8'))
Exemplo n.º 40
0
    config['cycles'] = int(parsed_args.cycles)
if parsed_args.no_cookie_save:
    config['cookiesave'] = False
elif parsed_args.cookie_save:
    config['cookiesave'] = True
if parsed_args.no_login:
    config['login'] = False
elif parsed_args.login:
    config['login'] = True

# Build urllib.request opener
cookieprocessor = urllib.request.HTTPCookieProcessor()
cookies = http.cookiejar.MozillaCookieJar()
if config.get('cookiefilepath') and os.path.isfile(config['cookiefilepath']):
    try:
        cookies.load(config['cookiefilepath'])
    except IOError as err:
        prtmsg('err_io', str(err))
    else:
        debug_prt('Cookies loaded from "{}"', config['cookiefilepath'])
cookieprocessor.cookiejar = cookies
defopener = urllib.request.build_opener(cookieprocessor, httphandler)
urllib.request.install_opener(defopener)

# Alternative actions
if 'genconf' in parsed_args:
    genconf((parsed_args.genconf if None != parsed_args.genconf else '-'), False, parsed_args.separate)
    exit()
elif 'genfullconf' in parsed_args:
    genconf((parsed_args.genfullconf if None != parsed_args.genfullconf else '-'), True, parsed_args.separate)
    exit()
Exemplo n.º 41
0
def application(environ, start_response):
    headers = [('Content-Type', 'text/html; charset=utf-8')]

    path = environ['PATH_INFO']
    params = urllib.parse.parse_qs(environ['QUERY_STRING'])
    un = params['username'][0] if 'username' in params else None
    pw = params['password'][0] if 'password' in params else None

    if path == '/register' and un and pw:
        user = cursor.execute('SELECT * FROM users WHERE username = ?', [un]).fetchall()
        if user:
            start_response('200 OK', headers)
            return ['Sorry, username {} is taken'.format(un).encode()]
        else:
            connection.execute('INSERT INTO products VALUES (username, password)')
    elif path == '/login' and un and pw:
        user = cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', [un, pw]).fetchall()
        if user:
            headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
            start_response('200 OK', headers)
            return ['User {} successfully logged in. <a href="/account">Account</a>'.format(un).encode()]
        else:
            start_response('200 OK', headers)
            return ['Incorrect username or password'.encode()]

    elif path == '/logout':
        headers.append(('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
        start_response('200 OK', headers)
        return ['Logged out. <a href="/">Login</a>'.encode()]

    elif path == '/account':
        start_response('200 OK', headers)

        if 'HTTP_COOKIE' not in environ:
            return ['Not logged in <a href="/">Login</a>'.encode()]

        cookies = http.cookies.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])
        if 'session' not in cookies:
            return ['Not logged in <a href="/">Login</a>'.encode()]

        [un, pw] = cookies['session'].value.split(':')
        user = cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', [un, pw]).fetchall()

        #This is where the game begins. This section of is code only executed if the login form works, and if the user is successfully logged in
        if user:
            correct = 0
            wrong = 0

            cookies = http.cookies.SimpleCookie()
            if 'HTTP_COOKIE' in environ:
                correct = int(cookies['score'].value.split(':')[0])

            page = '<!DOCTYPE html><html><head><title>Multiply with Score</title></head><body>'
            if 'factor1' in params and 'factor2' in params and 'answer' in params:

                if 'answer' == correct:
                    print('Correct')
                else :
                    print('Incorrect')

            elif 'reset' in params:
                correct = 0
                wrong = 0

            headers.append(('Set-Cookie', 'score={}:{}'.format(correct, wrong)))

            f1 = random.randrange(10) + 1
            f2 = random.randrange(10) + 1

            page = page + '<h1>What is {} x {}</h1>'.format(f1, f2)

            import sqlite3

            connection = sqlite3.connect('numbers.db')

            connection.execute('INSERT INTO products VALUES (?, ?, ?, ?)', [1, 2, 3, 4])
            connection.execute('INSERT INTO products VALUES (?, ?, ?, ?)', [3,6,9,12])
            connection.execute('INSERT INTO products VALUES (?, ?, ?, ?)', [4, 16, 8, 2])

            connection.commit()

            hyperlink = '<a href="/account?username={}&amp;password={}&amp;factor1={}&amp;factor2={}&amp;answer={}">{}: {}</a><br>'

            <a href="answera.html"></a>
            <a href ="answerb.html"></a>
            <a href ="answerc.html"></a>
            <a href ="answerd.html"></a>

            page += '''<h2>Score</h2>
            Correct: {}<br>
            Wrong: {}<br>
            <a href="/account?reset=true">Reset</a>
            </body></html>'''.format(correct, wrong)

            return [page.encode()]
        else:
            return ['Not logged in. <a href="/">Login</a>'.encode()]

    elif path == '/':
        if user:
            headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
            start_response('200 OK', headers)
            return ['User {} successfully logged in. <a href="/account">Account</a>'.format(un).encode()]
        else:
            start_response('200 OK', headers)
            return ['Incorrect username or password'.encode()]
        elif:
            connection.execute('INSERT INTO users VALUES (?, ?)', [un, pw])
            connection.commit()
            headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
            start_response('200 OK', headers)
            return ['Congratulations, username {} been successfully registered. <a href="/account">Account</a>'.format( un).encode()]
Exemplo n.º 42
0
def application(e, start_response):
    db = DB()

    headers = [('Content-Type', 'text/html; charset=utf-8')]
    app_root = urllib.parse.urlunsplit((e['wsgi.url_scheme'], e['HTTP_HOST'], e['SCRIPT_NAME'], '', ''))
    params = urllib.parse.parse_qs(e['QUERY_STRING'])
    path_info = e['PATH_INFO']

    # ----- If user has valid session cookie set session = True --------------------

    session = False
    session_user = None
    cookies = http.cookies.SimpleCookie()
    if 'HTTP_COOKIE' in e:
        cookies.load(e['HTTP_COOKIE'])
        if 'session' in cookies:
            session_user, session_pass = cookies['session'].value.split(':')
            session = db.user_pass_valid(session_user, session_pass)

    # ----- The common start of every page ---------------------------

    page = '''<!DOCTYPE html>
<html><head><title>Game</title>
<style>
    table { border-collapse: collapse; }
    table, th, td { border: 1px solid silver; padding: 2px; }
</style>
</head>
<body>
<h1>Rock-Paper-Scissors</h1>'''

    # ----- For logging in and registering ---------------------------

    if path_info == '/login_register':
        param_do = params['do'][0] if 'do' in params else None
        param_user = params['username'][0] if 'username' in params else None
        param_pass = params['password'][0] if 'password' in params else None

        login_register_form = '''
<form>
    <input type="text" name="username"> Username<br>
    <input type="password" name="password"> Password<br>
    <input type="submit" name="do" value="Login"> or
    <input type="submit" name="do" value="Register">
</form>'''

        if param_do == 'Login' and param_user and param_pass:
            if db.user_pass_valid(param_user, param_pass):
                headers.append(('Set-Cookie', 'session={}:{}'.format(param_user, param_pass)))
                headers.append(('Location', app_root))
                start_response('303 See Other', headers)
                return []
            else:
                start_response('200 OK', headers)
                page += login_register_form
                return [(page + 'Wrong username or password</body></html>').encode()]

        elif param_do == 'Register' and param_user and param_pass:
            if db.add_username(param_user, param_pass):
                headers.append(('Set-Cookie', 'session={}:{}'.format(param_user, param_pass)))
                headers.append(('Location', app_root))
                start_response('303 See Other', headers)
                return []
            else:
                start_response('200 OK', headers)
                page += login_register_form
                return [(page + 'Username {} is taken.</body></html>'.format(param_user)).encode()]

        else:
            start_response('200 OK', headers)
            return [(page + login_register_form + '</body></html>').encode()]

    # ----- Logout --------------------------------------------

    elif path_info == '/logout':
        headers.append(('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
        headers.append(('Location', app_root))
        start_response('303 See Other', headers)
        return []

    # ----- Root page -----------------------------------------

    elif path_info == '/' or not path_info:
        if not session:
            start_response('200 OK', headers)
            page += '<a href="{}/login_register">Log in or register</a> to play</body></html>'.format(app_root)
            return [page.encode()]

        page += '{} | <a href="{}/logout">Logout</a>'.format(session_user, app_root)
#       page += ' | <a href="{}">Refresh</a>'.format(app_root)
        page += '<h2>My games</h2>\n'
        page += '<table><tr><th>Game</th><th>Goal</th><th>Quit</th><th>State</th><th>Players</th></tr>\n'
        games = [
            Pyramid(i, p, g, st, ts, t, db.connection) for i, p, g, st, ts, t in db.get_games_by_user(session_user)
            ]
        for game in games:
            page += '<tr><td>{}</td><td>{}</td><td><a href="{}/quit?id={}">quit</a></td>'.format(
                game.id, game.goal, app_root, game.id
            )
            players_scores = ', '.join(
                [
                    '{}{}|{}{}'.format(
                        '' if p['playing'] else '<s>',  # Add open strikethrough tag if player left game
                        p['name'],
                        p['score'],
                        '' if p['playing'] else '</s>'  # Add close strikethrough tag
                    ) for p in game.players
                ]
            )
            if game.state == 0:  # Accepting players
                page += '<td>Awaiting {}</td>'.format(game.num_players - len(game.players))
                page += '<td>' + ', '.join([p['name'] for p in game.players]) + '</td>'
            elif game.state == 2:
                page += '<td><a href="{}/game?id={}">Game over</a></td>'.format(app_root, game.id)
                page += '<td>' + players_scores + '</td>'
            elif game.is_players_turn(session_user):  # Playing, player's turn
                page += '<td><a href="{}/game?id={}">My turn</a></td>'.format(app_root, game.id)
                page += '<td>' + players_scores + '</td>'
            else:  # Playing, not player's turn
                page += '<td><a href="{}/game?id={}">Awaiting Turn</a></td>'.format(app_root, game.id)
                page += '<td>' + players_scores + '</td>'
            page += '</tr>\n'
        page += '</table>'
        page += '<p><a href="{}/newgame">Start a New Game</a></p>'.format(app_root)
        ts1 = max(game.ts for game in games) if games else None

        page += '<h2>Games accepting players</h2>\n'
        page += '<table><tr><th>Game</th><th>Goal</th><th>Join</th><th>State</th><th>Players</th></tr>\n'
        games = [
            Pyramid(i, p, g, 0, ts, t, db.connection)
            for i, p, g, ts, t in db.get_registering_games_by_user(session_user)
            ]
        for game in games:
            page += '<tr><td>{}</td><td>{}</td><td><a href="{}/join?id={}">join</a></td>'.format(
                game.id, game.goal, app_root, game.id
            )
            page += '<td>{} of {} players</td>'.format(len(game.players), game.num_players, game.id)
            page += '<td>' + ', '.join([p['name'] for p in game.players]) + '</td>'
            page += '</tr>\n'
        page += '</table>'
        ts2 = max(game.ts for game in games) if games else None

        page += '''
<script>
    function callback(event) {{
        if (event.target.readyState == 4 && event.target.responseText != '{} {}') {{
            window.location = '{}'
        }}
    }}
    function timeFunc(event) {{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.addEventListener("readystatechange", callback)
        xmlhttp.open("GET", "{}/updated_games", true)
        xmlhttp.setRequestHeader("Content-Type", "text/plain")
        xmlhttp.send()
    }}
    setInterval(timeFunc, 1000)
</script>'''.format(ts1, ts2, app_root, app_root)

        start_response('200 OK', headers)
        return [(page + '</body></html>').encode()]

    # ----- Check if game list changed -------------------------------------------

    elif path_info == '/updated_games':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        ts1, ts2 = db.updated_games(session_user)

        start_response('200 OK', headers)
        return ['{} {}'.format(ts1, ts2).encode()]

    # ----- Register new game ---------------------------------------------------------------
    # ***** MODIFY THIS PART TO ASK FOR NUMBER OF PLAYERS AND RECEIVE NUMBER OF PLAYERS *****

    elif path_info == '/newgame':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        if 'goal' in params:
            db.new_game(2, params['goal'][0], session_user)
            headers.append(('Location', app_root))
            start_response('303 See Other', headers)
            return []

        page += '''
<h2>Create New Game</h2>
<form>
    <h3>Play until score:</h3>
    <input type="radio" name="goal" value="1">1<br>
    <input type="radio" name="goal" value="3">3<br>
    <input type="radio" name="goal" value="5">5<br>
    <input type="radio" name="goal" value="10" checked>10<br>
    <input type="radio" name="goal" value="20">20<br>
    <input type="radio" name="goal" value="100">100<br>
    <input type="submit" value="Create">
</form>
</body></html>'''

        start_response('200 OK', headers)
        return [page.encode()]

    # ----- Join game -----------------------------------------

    elif path_info == '/join':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        game_id = params['id'][0]
        db.join_game(game_id, session_user)

        headers.append(('Location', app_root))
        start_response('303 See Other', headers)
        return []

    # ----- Quit game -----------------------------------------

    elif path_info == '/quit':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        game_id = params['id'][0]
        db.quit_game(game_id, session_user)

        headers.append(('Location', app_root))
        start_response('303 See Other', headers)
        return []

    # ----- Game ------------------------------------------------------------

    elif path_info == '/game':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        game_id = params['id'][0]

        (players, goal, state, ts, turns) = db.get_game_by_id(game_id)
        game = Pyramid(game_id, players, goal, state, ts, turns, db.connection)
        if game.state == 0:  # Error: cannot view game, it is still registering players
            start_response('200 OK', headers)
            return [(page + 'Still registering players</body></html>').encode()]

        if 'move' in params:  # Player came here by making a move
            game.add_player_move(session_user, params['move'][0])

        page += '<a href="{}">Home</a>'.format(app_root)
#       page += ' | <a href="{}/game?id={}">Refresh</a>'.format(app_root, game_id)
        page += '<h3>Game {} -- Play to {}</h3>'.format(game.id, game.goal)

        if game.state == 2:
            page += '<p>Game over</p>'
        elif game.is_players_turn(session_user):
            page += '<p>Your move: '
            move_template = '<a href="{}/game?id={}&amp;move={}">{}</a>'
            move_links = [
                move_template.format(app_root, game.id, mval, mname) for mval, mname in game.valid_moves(session_user)
                ]
            page += ' | '.join(move_links)
        else:
            page += '<p>Wait for your turn</p>'

        page += '<table>\n<tr><th>&nbsp;</th>'
        for p in game.players:
            page += '<th>{}</th>'.format(p['name']) if p['playing'] else '<th><s>{}</s></th>'.format(p['name'])
        page += '</tr>\n<tr style="background-color: silver"><td>Round</td>'
        for p in game.players:
            page += '<td>{} p</td>'.format(p['score'])
        page += '</tr>\n'

        for index, turn in enumerate(reversed(game.decorated_moves(session_user))):
            page += '<tr><td>{}</td>'.format(len(game.turns) - index)
            for move, winner in turn:
                if winner:
                    page += '<td style="background-color:lightgreen">{}</td>'.format(move)
                else:
                    page += '<td>{}</td>'.format(move)
            page += '</tr>\n'

        page += '</table>'

        if game.state == 1:
            page += '''
<script>
    function callback(event) {{
        if (event.target.readyState == 4 && event.target.responseText != '{}') {{
            window.location = '{}/game?id={}'
        }}
    }}
    function timeFunc(event) {{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.addEventListener("readystatechange", callback)
        xmlhttp.open("GET", "{}/updated_game?id={}", true)
        xmlhttp.setRequestHeader("Content-Type", "text/plain")
        xmlhttp.send()
    }}
    setInterval(timeFunc, 1000)
</script>'''.format(game.ts, app_root, game.id, app_root, game.id)

        start_response('200 OK', headers)
        return [(page + '</body></html>').encode()]

    # ----- Check if game changed --------------------------------------

    elif path_info == '/updated_game':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        start_response('200 OK', headers)
        p, g, s, ts, t = db.get_game_by_id(params['id'][0])
        return ['{}'.format(ts).encode()]

    # ----- Dump tables ------------------------------------------------

    elif path_info == '/dump':
        users, games, players = db.dump()

        page += '<a href="{}">Home</a>'.format(app_root)
        page += ' | <a href="{}/clear_games">Clear games and players</a>'.format(app_root)
        page += ' | <a href="{}/clear_all">Clear all</a>'.format(app_root)

        page += '<h2>Table "user"</h2>\n'
        page += '<p>Contains all registered users and their passwords.</p>\n'
        page += '<table><tr><th>name</th><th>password</th></tr>\n'
        for name, password in users:
            page += '<tr><td>{}</td><td>{}</td></tr>\n'.format(name, password)
        page += '</table>\n'

        page += '<h2>Table "game"</h2>\n'
        page += '<p>One row for every game.</p>\n'
        page += '<table><tr><th>rowid</th><th>players</th><th>goal</th><th>state</th><th>ts</th><th>turns</th></tr>\n'
        for rowid, numplayers, goal, state, ts, turns in games:
            page += '<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n'.format(
                rowid, numplayers, goal, state, ts, turns
            )
        page += '</table>\n'

        page += '<h2>Table "player"</h2>\n'
        page += '<p>Connects players with games. One row for every player in a game.</p>\n'
        page += '<table><tr><th>rowid</th><th>game_id</th><th>user_name</th><th>score</th><th>playing</th></tr>\n'
        for rowid, game_id, user_name, score, playing in players:
            page += '<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n'.format(
                rowid, game_id, user_name, score, playing
            )
        page += '</table>\n'

        page += '</body></html>'

        start_response('200 OK', headers)
        return [page.encode()]

    # ----- Clear tables --------------------------------------

    elif path_info == '/clear_games':
        db.clear_tables(False)
        headers.append(('Location', '{}/dump'.format(app_root)))
        start_response('303 See Other', headers)
        return []

    elif path_info == '/clear_all':
        db.clear_tables(True)
        headers.append(('Location', '{}/dump'.format(app_root)))
        start_response('303 See Other', headers)
        return []

    # ----- Unknown web app ----------------------------------------------------------

    else:
        start_response('200 OK', headers)
        return [(page + 'Unknown Web app {}</body></html>'.format(path_info)).encode()]