-
Notifications
You must be signed in to change notification settings - Fork 0
/
guestbook.py
executable file
·266 lines (218 loc) · 7.55 KB
/
guestbook.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
import re
import os
import cgi
import datetime
import wsgiref.handlers
import uuid
import hashlib
import logging
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.api import mail
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class Greeting(db.Model):
author = db.StringProperty()
content = db.TextProperty()
date = db.DateTimeProperty(auto_now_add=True)
class User(db.Model):
email = db.EmailProperty()
password = db.StringProperty()
name = db.StringProperty()
salt = db.StringProperty()
class MainPage(webapp.RequestHandler):
def get(self):
MESSAGES = {
'regSuccessful': 'You are successfully registered.',
'loginSuccessful': ''
}
ERROR_MESSAGES = {
'tooLongValue': 'Your message is too long.',
'emptyField': 'Message can\'t be empty.',
}
user = self.__userName()
greetings_query = Greeting.all().order('-date')
greetings = greetings_query.fetch(10)
template_values = {
'greetings': greetings,
'message': MESSAGES.get(self.request.get('message')),
'error': ERROR_MESSAGES.get(self.request.get('error')),
'user': user
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
def post(self):
self.content = self.request.get('content')
error = self.__error()
if error:
self.redirect('/?error=' + error)
else:
user = self.__userName()
greeting = Greeting()
if user:
greeting.author = user.name
greeting.content = self.content
greeting.put()
self.redirect('/')
def __error(self):
if len(self.content) > 500:
return 'tooLongValue'
if re.match('^\s*$', self.content):
return 'emptyField'
def __userName(self):
sessionId = self.request.cookies.get('sid')
if sessionId:
userId = memcache.get(sessionId)
if userId is not None:
return User.get_by_id(userId)
class Login(webapp.RequestHandler):
def __init__(self):
self.ERROR_MESSAGES = {
'wrongPassword': 'Password is incorrect.',
'incorrectEmail': 'Please, enter valid email address.',
'wrongEmail': 'Email not found.'
}
def get(self):
template_values = {
'error': self.ERROR_MESSAGES.get(self.request.get('error')),
'email': self.request.get('email')
}
path = os.path.join(os.path.dirname(__file__), 'login.html')
self.response.out.write(template.render(path, template_values))
def post(self):
xhr = self.request.headers.get('X-Requested-With') == 'XMLHttpRequest'
self.email = self.request.get('email')
error = self.__error()
if error:
if error == 'incorrectEmail':
self.email = ''
if xhr:
# self.response.out.write({"error": error, "email": self.email})
self.response.out.write("{\"error\": \"%s\", \"email\": \"%s\"}" % \
(self.ERROR_MESSAGES[error], self.email))
else:
self.redirect('/login?error=' + error + '&email=' + self.email)
return
sessionId = str(uuid.uuid4()).replace('-','')
memcache.set(sessionId, self.user.key().id(), 36000)
self.response.headers.add_header('Set-Cookie',
'sid=%s; path=/' % sessionId)
if xhr:
# self.response.out.write({"name": str(self.user.name)})
# json
self.response.out.write("{\"name\": \"%s\"}" % str(self.user.name))
else:
self.redirect('/')
def __error(self):
if re.match('^[-.\w]+@(?:[a-z\d][-a-z\d]+\.)+[a-z]{2,6}$', self.email) is None:
return 'incorrectEmail'
self.user = User.all().filter('email =', self.email).get()
if self.user is None:
return 'wrongEmail'
salt = self.user.salt
password = self.request.get('password')
if re.match('^\w+$', password) is None:
password = ''
passwordHash = hashlib.sha1(password + salt).hexdigest()
if self.user.password != passwordHash:
return 'wrongPassword'
class Logout(webapp.RequestHandler):
def get(self):
sessionId = self.request.cookies.get('sid')
logging.info(sessionId)
# if sessionId:
memcache.delete(sessionId)
self.response.headers.add_header('Set-Cookie', 'sid=; path=/')
if self.request.headers.get('X-Requested-With') != 'XMLHttpRequest':
self.redirect('/')
class Register(webapp.RequestHandler):
def get(self):
ERROR_MESSAGES = {
'tooLongValue': 'The value is too long.',
'emptyField': 'Required fields are not filled.',
'wrongEmail': 'Sorry, such email already exists.',
'incorrectEmail': 'Please, enter valid email address.',
'wrongPassword': 'Password should contain only English letters, numbers or underscores.',
'wrongConfirmation': 'Passwords don\'t match.',
'wrongName': 'Sorry, name should contain only English letters, numbers or underscores.'
}
template_values = {
'error' : ERROR_MESSAGES.get(self.request.get('error')),
'errorMessages' : ERROR_MESSAGES,
'form' : [
{
'label': 'Email',
'type': 'text',
'name': 'email',
'value': self.request.get('email')
},
{
'label': 'Password',
'type': 'password',
'name': 'password',
},
{
'label': 'Confirm password',
'type': 'password',
'name': 'confirmPassword',
},
{
'label': 'Name',
'type': 'text',
'name': 'name',
'value': self.request.get('name')
}
]
}
path = os.path.join(os.path.dirname(__file__), 'registration.html')
self.response.out.write(template.render(path, template_values))
def __error(self):
for i in [self.email, self.password, self.confirmPassword, self.name]:
if len(i) > 100:
return 'tooLongValue'
if len(i) == 0:
return 'emptyField'
if re.match('^[-.\w]+@(?:[a-z\d][-a-z\d]+\.)+[a-z]{2,6}$', self.email) is None:
return 'incorrectEmail'
if User.all().filter('email =', self.email).get() is not None:
return 'wrongEmail'
if re.match('^\w+$', self.password) is None:
return 'wrongPassword'
if self.password != self.confirmPassword:
return 'wrongConfirmation'
if re.match('^\w+$', self.name) is None:
return 'wrongName'
def post(self):
self.email = self.request.get('email')
self.password = self.request.get('password')
self.confirmPassword = self.request.get('confirmPassword')
self.name = self.request.get('name')
error = self.__error()
if error:
errorUrl = '/register?error=' + error
if error != 'tooLongValue' and error != 'incorrectEmail':
errorUrl += '&email=' + self.email
if error != 'wrongName':
errorUrl += '&name=' + self.name
self.redirect(errorUrl)
else:
salt = str(uuid.uuid4()).replace('-','')
passwordHash = hashlib.sha1(self.password + salt).hexdigest()
user = User()
user.email = self.email
user.password = str(passwordHash)
user.salt = salt
user.name = self.name
user.put()
self.redirect('/?message=regSuccessful')
application = webapp.WSGIApplication([
('/', MainPage),
('/register', Register),
('/login', Login),
('/logout', Logout)
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()