-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
266 lines (201 loc) · 8.6 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
from flask import Flask, render_template, redirect, url_for, request, session, jsonify
from helpers import parseCSV, getHint, login_required, encrPw, getPw
from helpers import get_rand_word, scramble, randCompl
from datetime import timedelta
import jyserver.Flask as jsf
from cs50 import SQL
import re
app = Flask(__name__, static_url_path='/static')
app.secret_key = 'secret'
app.permanent_session_lifetime = timedelta(days=3)
""" Loading in the database """
db = SQL('sqlite:///wordnerd.db')
""" Reads the Dictionary """
parseCSV()
chosenDiff = 'Easy'
name = ''
word = ''
score = 0
@jsf.use(app)
class App:
def __init__(self) -> None:
self.word =''
# sets the scale of the score based on factors (length of word, difficulty, bulb used)
# This function is called from an external JS file
def scoreScale(self, n) :
self.scaledScore= n
return self.scaledScore
# returns the scaledScore
def getScaledScore(self):
return self.scaledScore
def isCorrect(self):
l = db.execute('SELECT name,email,password,score from accounts where email=?', session['user'])
for d in l:
global name
global score
n = d['name']
p = d['password']
s = d['score'] + self.getScaledScore()
name = n
score = s
self.score = s
db.execute('DELETE FROM accounts where email=?', session['user'])
db.execute('INSERT INTO accounts (name,email,password,score) values (?,?,?,?)', n, session['user'], p, s)
def getScoreE():
l = db.execute('SELECT score FROM accounts WHERE email = ?', session['user'])
for d in l:
return d['score']
@app.route('/score', methods=['POST'])
def giveScore():
return jsonify({'score_value': score})
""" HOMEPAGE """
@app.route('/', methods=['POST', 'GET'])
@app.route('/home', methods=['POST', 'GET'])
@app.route('/play', methods=['POST', 'GET'])
@login_required
def index():
d = request.form.to_dict()
global chosenDiff
global word
global score
score = getScoreE()
if request.method == 'POST':
chosenDiff = list(dict(d).keys())[0].lower() # difficulty
word = get_rand_word(chosenDiff) # the literal word
scrambled = scramble(word) # the scrambled version
return App.render(render_template('home.html', word=word, scrambled=scrambled, hint=getHint(chosenDiff, word)\
, diff=chosenDiff.capitalize(), compliment=randCompl(), firstLoad=False, score=score))
else:
if not d:
return App.render(render_template('home.html', scrambled='Welcome', hint='Really... 0_o',diff=chosenDiff.capitalize(), firstLoad=True, \
instruction='Choose a difficulty to begin...', score=score))
""" ABOUT """
@app.route('/about')
@login_required
def about():
return render_template('about.html')
""" ACCOUNTS """
@app.route('/accounts', methods=['POST', 'GET'])
@login_required
def accounts():
return render_template('accounts.html', email=session['user'])
""" LOGIN """
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
""" E-MAIL CHECKING """
if not email:
return render_template('error.html', msg='E-mail can\'t be empty!')
# IF EMAIL STRUCTURE IS INVALID
try:
re.match(r'(\w+)(@gmail.com)$', email).group()
ecorrect = True
except AttributeError:
ecorrect = False
if not ecorrect:
return render_template('error.html', msg='Invalid Email address!')
""" Checking if the user is in the database """
try:
em = db.execute("Select * from accounts where email = (?)", email)
except ValueError:
return render_template('error.html', msg='Please create an account first!')
if not em:
return render_template('error.html', msg='You don\'t have an account! Create one.')
""" PASSWORD CHECKING """
if not password:
return render_template('error.html', msg='Password can\'t be empty!')
try:
l = db.execute("Select password from accounts where email = (?)", email)
except KeyError:
return render_template('error.html', msg='Incorrect Password. Please try again!')
for d in l:
cpass = getPw(d['password'])
if password != cpass:
return render_template('error.html', msg='Incorrect Password. Please try again!')
# Check if the password is the users from the database
session['user'] = email
return redirect(url_for('index'))
else:
return render_template('login.html')
""" SIGNUP """
@app.route('/signup', methods=['POST', 'GET'])
def signup():
if request.method == 'POST':
username = request.form.get('username')
email = request.form.get('email')
password = request.form.get('password')
cpassword = request.form.get('cpassword')
""" USERNAME HANDLING """
if not username:
return render_template('error.html', msg='Username can\'t be empty!')
if len(username) > 15:
return render_template('error.html', msg='Username can\'t exceed 15 characters.')
if len(username) < 4:
return render_template('error.html', msg='Username can\'t be less than 4 characters.')
# if username inside database redirect to login page
try:
user = db.execute("Select * from accounts where name = (?)", username)
em = db.execute("Select * from accounts where email = (?)", email)
except ValueError:
return render_template('error.html', msg='You already have an account! Please Login.')
if user:
return render_template('error.html', msg='Username already taken! Choose another.')
if em:
return render_template('error.html', msg='You already have an account! Please Login.')
# IF SPECIAL CHAR PRESENT IN USERNAME
try:
re.search('\W+', username).group()
sc = True
except AttributeError:
sc = False
if sc:
return render_template('error.html', msg='Special characters aren\'t allowed as username!')
""" E-MAIL CHECKING """
if not email:
return render_template('error.html', msg='E-mail can\'t be empty!')
try:
re.match(r'(\w+)(@gmail.com)$', email).group()
ecorrect = True
except AttributeError:
ecorrect = False
# IF EMAIL STRUCTURE IS INVALID
if not ecorrect:
return render_template('error.html', msg='Invalid Email address!')
""" PASSWORD CHECKING """
if not password:
return render_template('error.html', msg='Password can\'t be empty!')
if not cpassword:
return render_template('error.html', msg='Confirmation Password can\'t be empty!')
if password != cpassword:
return render_template('error.html', msg='The two passwords don\'t match!')
if not(8 <= len(password) <= 15):
return render_template('error.html', msg='Password must be between 8 - 15 characters long!')
""" ADDING THE USER INTO THE DATABASE """
db.execute('INSERT INTO accounts (name, email, password, score, firsttime) VALUES(?,?,?,0,1)', username, email, encrPw(password))
return render_template('login.html', msg='Successfully Registered! You can login to your account.')
else:
return render_template('signup.html')
""" LOGOUT """
@app.route('/logout', methods=['POST', 'GET'])
@login_required
def logout():
session.pop('user', None)
return redirect(url_for('login'))
razeCount = 0
""" RAZING ACCOUNT """
@app.route('/raze', methods=['POST', 'GET'])
@login_required
def raze():
global razeCount
if request.method == 'POST':
razebtn = request.form.get('flag')
if int(razebtn) == 1:
razeCount+=1
if razeCount >= 5:
db.execute('DELETE FROM accounts WHERE email=?', session['user'])
return redirect(url_for('logout'))
return render_template('raze.html' , msg='You\'ll need to create a new account if you want to play again. All your progress will be wiped out...')
if __name__ == '__main__':
app.run(debug=True)