· 8 years ago · Jun 20, 2018, 02:30 AM
1import wsgiref.simple_server
2import urllib.parse
3import sqlite3
4import http.cookies
5import random
6
7connection = sqlite3.connect('users.db')
8cursor = connection.cursor()
9exp = 'CREATE TABLE IF NOT EXISTS users (username, password)'
10connection.execute(exp)
11connection.commit()
12
13
14def application(environ, start_response):
15 headers = [('Content-Type', 'text/html; charset=utf-8')]
16
17 path = environ['PATH_INFO']
18 params = urllib.parse.parse_qs(environ['QUERY_STRING'])
19 un = params['username'][0] if 'username' in params else None
20 pw = params['password'][0] if 'password' in params else None
21
22 if path == '/register' and un and pw:
23 user = cursor.execute('SELECT * FROM users WHERE username = ?', [un]).fetchall()
24 connection.commit()
25 if user:
26 start_response('200 OK', headers)
27 return ['Sorry, username {} is taken'.format(un).encode()]
28 else:
29 start_response('200 OK', headers)
30 cursor.execute("INSERT INTO users VALUES (?, ?)", [un, pw])
31 connection.commit()
32 return ["Account Registered.".encode()]
33
34 elif path == '/login' and un and pw:
35 user = cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', [un, pw]).fetchall()
36 connection.commit()
37 if user:
38 headers.append(('Set-Cookie', 'session={}:{}'.format(un, pw)))
39 start_response('200 OK', headers)
40 return ['User {} successfully logged in. <a href="/account">Account</a>'.format(un).encode()]
41 else:
42 start_response('200 OK', headers)
43 return ['Incorrect username or password'.encode()]
44
45 elif path == '/logout':
46 headers.append(('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
47 start_response('200 OK', headers)
48 return ['Logged out. <a href="/">Login</a>'.encode()]
49
50 elif path == '/account':
51 start_response('200 OK', headers)
52
53 if 'HTTP_COOKIE' not in environ:
54 return ['Not logged in <a href="/">Login</a>'.encode()]
55
56 cookies = http.cookies.SimpleCookie()
57 cookies.load(environ['HTTP_COOKIE'])
58 if 'session' not in cookies:
59 return ['Not logged in <a href="/">Login</a>'.encode()]
60
61 [un, pw] = cookies['session'].value.split(':')
62 user = cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', [un, pw]).fetchall()
63 connection.commit()
64
65 # This is where the game begins. This section of is code only executed if the login form works, and if the user
66 # is successfully logged in
67 if user:
68 correct = 0
69 wrong = 0
70
71 cookies = http.cookies.SimpleCookie()
72 if 'HTTP_COOKIE' in environ:
73
74 if "score" in cookies:
75 print(cookies)
76 tot = cookies["score"].value.split(":")
77 print(tot)
78 correct = tot[0]
79 wrong = tot[1]
80
81 page = '<!DOCTYPE html><html><head><title>Multiply with Score</title></head><body>'
82 if 'factor1' in params and 'factor2' in params and 'answer' in params:
83
84 if params["answer"][0] == str(int(params["factor1"][0])*int(params["factor2"][0])):
85 correct += 1
86 print(correct)
87 page += "<html><p style=\"background-color: lightgreen\">Correct. {} x {} = {} </p></html>".format(params["factor1"][0], params["factor2"][0], params["answer"][0])
88 else:
89 wrong += 1
90 page += "<html><p style=\"background-color: red\">Wrong. {} x {} = {} </p></html>".format(params["factor1"][0], params["factor2"][0], str(int(params["factor1"][0])*int(params["factor2"][0])))
91
92 elif 'reset' in params:
93 correct = 0
94 wrong = 0
95
96 headers.append(('Set-Cookie', 'score={}:{}'.format(correct, wrong)))
97
98 f1 = random.randrange(10) + 1
99 f2 = random.randrange(10) + 1
100
101 page = page + '<h1>What is {} x {}</h1>'.format(f1, f2)
102
103 fake1 = random.randint(1, 100)
104
105 fake2 = random.randint(1, 100)
106
107 fake3 = random.randint(1, 100)
108
109 answer = [f1*f2, fake1, fake2, fake3]
110
111 random.shuffle(answer)
112
113 hyperlink = '<a href="/account?username={}&password={}&factor1={}&factor2={}&answer={}">{}: {}</a><br>'
114
115 page += hyperlink.format(un, pw, f1, f2, answer[0], "A", answer[0])
116
117 page += hyperlink.format(un, pw, f1, f2, answer[1], "B", answer[1])
118
119 page += hyperlink.format(un, pw, f1, f2, answer[2], "C", answer[2])
120
121 page += hyperlink.format(un, pw, f1, f2, answer[3], "D", answer[3])
122
123 page += '''<h2>Score</h2>
124 Correct: {}<br>
125 Wrong: {}<br>
126 <a href="/account?reset=true">Reset</a>
127 </body></html>'''.format(correct, wrong)
128
129 return [page.encode()]
130 else:
131 return ['Not logged in. <a href="/">Login</a>'.encode()]
132
133 elif path == '/':
134 start_response('200 OK', headers)
135
136 return ["""<form action="/login" style="background-color:blue">
137 <h1>Login</h1>
138 Username <input type="text" name="username"><br>
139 Password <input type="password" name="password"><br>
140 <input type="submit" value="Log in">
141</form>
142<form action="/register" style="background-color:blue">
143 <h1>Register</h1>
144 Username <input type="text" name="username"><br>
145 Password <input type="password" name="password"><br>
146 <input type="submit" value="Register">
147</form>""".encode()]
148
149 else:
150 start_response('404 Not Found', headers)
151 return ['Status 404: Resource not found'.encode()]
152
153
154httpd = wsgiref.simple_server.make_server('', 8000, application)
155print("Serving Port 8000...")
156httpd.serve_forever()