/
code.py
executable file
·475 lines (397 loc) · 16.6 KB
/
code.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#!/usr/bin/env python3
from __future__ import absolute_import, division, print_function
""" Using webpy 0.3 """
import web
import model
import time
import hashlib
import os
import utils
import emailconfirm
### Setup app DB
if not os.path.isfile(model.DB_FILE):
model.initDb()
### Url mappings
urls = (
'/', 'Index',
'/new', 'New',
'/view/(\d+)', 'View',
'/delete/(\d+)', 'Delete',
'/edit/(\d+)', 'Edit',
'/newitem/(\d+)', 'NewItem',
'/deleteitem/(\d+)', 'DeleteItem',
'/edititem/(\d+)', 'EditItem',
'/helpsignup/(\d+)', 'HelpSignup',
'/login', 'Login',
'/logout', 'Logout',
'/error/(.*)', 'Error',
'/helpconfirm/(\d+)', 'HelpConfirm',
'/newadmin', 'NewAdmin',
'/editadmin', 'EditAdmin',
'/rmadmin', 'RemoveAdmin',
)
app = web.application(urls, globals())
# This statement is more complicated than just the session line so that
# debug prompts that cause reload of the module work properly.
if web.config.get('_session') is None:
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'admin': False, 'userId': None})
# session = web.session.Session(app, web.session.DBStore(model.db,'SessionData'), initializer={'admin': False})
web.config._session = session
else:
session = web.config._session
### Templates
t_globals = {
'session': session,
'utils' : utils,
'model' : model,
# form paths relative to basedir in templates
'app_base': lambda p: web.ctx.homepath[:-8] + p
}
render = web.template.render('templates', base='base', globals=t_globals)
# Constants
class Index:
def GET(self):
""" Show page """
posts = model.get_posts()
for post in posts:
# Post is set active only if it has an item yet to occur
post.active = False
items = model.get_items(post.id)
for item in items:
if not utils.date_in_past(item.date):
post.active = True
return render.index(posts)
class New:
# Build contact list of dropdown
contact_list = [(contact.id,contact.name) for contact in model.get_contacts()]
form = web.form.Form(
web.form.Textbox('title', web.form.notnull, size=30, description="Title:"),
web.form.Textarea('details', web.form.notnull, rows=10, cols=65, description="Details:"),
web.form.Button('Done', type='submit')
)
def GET(self):
if not session.admin:
authorization_error()
form = self.form()
return render.new(form)
def POST(self):
if not session.admin:
authorization_error()
form = self.form()
if not form.validates():
return render.new(form)
post_id = model.new_post(form.d.title, form.d.details, session.userId)
raise web.seeother('/view/%d' % post_id)
class View:
def GET(self, id):
""" View single post """
id = int(id)
post_data = model.get_post(id)
if not post_data:
argument_error()
if session.admin and not model.authorized_user(session.userId, post_data.contactId):
authorization_error()
# Modify details of post_data for display. Need to be able to handle
# newlines in textarea data in a websafe way.
post_data.details = web.net.websafe(post_data.details)
post_data.details = utils.nl2br(post_data.details)
item_data = model.get_items(id)
contact_data = model.get_contact_data(post_data.contactId)
return render.view(post_data, item_data, contact_data)
class Delete:
def GET(self, id):
if not session.admin:
authorization_error()
post = model.get_post(int(id))
if not model.authorized_user(session.userId, post.contactId):
authorization_error()
return render.delete(post)
def POST(self, id):
if not session.admin:
authorization_error()
post = model.get_post(int(id))
if not model.authorized_user(session.userId, post.contactId):
authorization_error()
model.del_post(int(id))
raise web.seeother('/')
class Edit:
def GET(self, id):
if not session.admin:
authorization_error()
post = model.get_post(int(id))
if not model.authorized_user(session.userId, post.contactId):
authorization_error()
form = New.form()
form.fill(post)
return render.edit(post, form)
def POST(self, id):
if not session.admin:
authorization_error()
#TODO: take care of display issue with details (textarea data)
form = New.form()
post = model.get_post(int(id))
if not model.authorized_user(session.userId, post.contactId):
authorization_error()
if not form.validates():
return render.edit(post, form)
model.update_post(int(id), form.d.title, form.d.details)
raise web.seeother('/view/%d' % int(id))
class NewItem:
date_fmt_str = utils.get_date_validator_string()
form = web.form.Form(
web.form.Textbox('date', web.form.Validator('%s expected' % date_fmt_str, utils.date_valid), size=8, description="Date (%s):" % date_fmt_str),
web.form.Textbox('description', web.form.notnull, size=30, description="Description:"),
web.form.Textbox('count', web.form.regexp(r'^\d+$', 'Must be a number'), size=2, description="Number of Entries:", value='1'),
web.form.Button('Done', type='submit')
)
def GET(self, post_id):
if not session.admin:
authorization_error()
post_id = int(post_id)
post = model.get_post(post_id)
if not model.authorized_user(session.userId, post.contactId):
authorization_error()
form = self.form()
return render.newitem(post, form)
def POST(self, post_id):
if not session.admin:
authorization_error()
post_id = int(post_id)
post = model.get_post(post_id)
if not model.authorized_user(session.userId, post.contactId):
authorization_error()
form = self.form()
if not form.validates():
post = model.get_post(post_id)
return render.newitem(post, form)
for idx in range(int(form.d.count)):
model.new_help_item(post_id, utils.standardize_date(form.d.date), form.d.description)
raise web.seeother('/view/%d' % post_id)
class DeleteItem:
def GET(self, item_id):
if not session.admin:
authorization_error()
item = model.get_item(int(item_id))
post = model.get_post(item.helpRequestId)
if not model.authorized_user(session.userId, post.contactId):
authorization_error()
return render.deleteitem(post, item)
def POST(self, item_id):
if not session.admin:
authorization_error()
item_data = model.get_item(int(item_id))
post = model.get_post(item_data.helpRequestId)
if not model.authorized_user(session.userId, post.contactId):
authorization_error()
post_id = model.del_help_item(int(item_id))
raise web.seeother('/view/%d' % item_data.helpRequestId)
class EditItem:
date_fmt_str = utils.get_date_validator_string()
form = web.form.Form(
web.form.Textbox('date', web.form.Validator('%s expected' % date_fmt_str, utils.date_valid), size=8, description="Date (%s):" % date_fmt_str),
web.form.Textbox('description', web.form.notnull, size=30, description="Description:"),
web.form.Textbox('helpName', size=30, description="Helper Name:"),
web.form.Textbox('helpEmail', size=30, description="Helper Email:"),
web.form.Textbox('helpPhone', size=30, description="Helper Phone:"),
web.form.Button('Done', type='submit')
)
def GET(self, id):
if not session.admin:
authorization_error()
item = model.get_item(int(id))
post = model.get_post(item.helpRequestId)
if not model.authorized_user(session.userId, post.contactId):
authorization_error()
form = self.form()
form.fill(item)
return render.edititem(post, item, form)
def POST(self, id):
if not session.admin:
authorization_error()
#TODO: take care of display issue with details (textarea data)
form = self.form()
item = model.get_item(int(id))
post = model.get_post(item.helpRequestId)
if not model.authorized_user(session.userId, post.contactId):
authorization_error()
if not form.validates():
return render.edititem(post, item, form)
model.update_help_item(int(id), utils.standardize_date(form.d.date), form.d.description,
form.d.helpName, form.d.helpEmail, form.d.helpPhone)
raise web.seeother('/view/%d' % item.helpRequestId)
class HelpSignup:
#TODO: get email address validation working
vemail = web.form.regexp(r".*@.*","must be a valid email address")
# vemail = EmailRegexp(r".*@.*", "Email address not valid")
form = web.form.Form(
web.form.Textbox('helpName', web.form.notnull, size=30, description="Name:"),
web.form.Textbox('helpEmail', size=30, description="Email:"),
web.form.Textbox('helpEmail2', size=30, description="Repeat Email:"),
web.form.Textbox('helpPhone', size=30, description="Phone:"),
web.form.Button('Signup', type='submit'),
validators = [ web.form.Validator("Email addresses do not match",
lambda i: i.helpEmail == i.helpEmail2),
web.form.Validator("Must provide either email or phone number",
lambda i: i.helpEmail != '' or i.helpPhone != ''),
]
)
def GET(self, id):
item = model.get_item(int(id))
#TODO: should error checking like this be done elsewhere?
if not item: # Requested item doesn't exist
raise web.seeother('/')
if item.helpName: # Someone has already signed up for this item
raise web.seeother('/error/item_help_provided?req_id=%d' % int(item.helpRequestId))
post = model.get_post(item.helpRequestId)
form = self.form()
return render.helpsignup(post, item, form)
def POST(self, id):
form = self.form()
item = model.get_item(int(id))
if not item: # Requested item doesn't exist
raise web.seeother('/')
if item.helpName: # Someone has already signed up for this item
raise web.seeother('/error/item_help_provided?req_id=%d' % int(item.helpRequestId))
if not form.validates():
post = model.get_post(item.helpRequestId)
return render.helpsignup(post, item, form)
model.update_help_item(int(id), item.date, item.description,
form.d.helpName, form.d.helpEmail, form.d.helpPhone)
emailconfirm.sendConfirmationEmail(int(id))
raise web.seeother('/helpconfirm/%d' % item.id)
class HelpConfirm:
def GET(self, id):
item = model.get_item(int(id))
if not item: # Requested item doesn't exist
raise web.seeother('/')
return render.helpconfirm(item)
class Login:
form = web.form.Form(
web.form.Textbox('username', web.form.notnull),
web.form.Password('password', web.form.notnull),
web.form.Button('Login', type='submit')
)
def GET(self):
form = self.form()
return render.login(form)
def POST(self):
form = self.form()
if not form.validates():
return render.login(form)
pwdhash = hashlib.md5(form.d.password.encode()).hexdigest()
session.user = None
for contact in model.get_contacts():
if form.d.username == contact.username and pwdhash == contact.passhash:
#login successful
session.userId = contact.id
session.admin = True
raise web.seeother('/')
if not session.user:
return render.login(form)
class Logout:
def GET(self):
session.userId = None
session.admin = False
raise web.seeother('/')
class Error:
def GET(self, error):
if error == 'bogus_arguments':
title = 'Bogus Arguments for Page'
msg = 'Click below to goto home page'
link = ''
elif error == 'item_help_provided':
data = web.input(req_id=None)
if data.req_id == None:
return self.unknown_error()
title = 'Help Already Provided'
msg = 'Help has already been provded for this item. Click link below to find other available items.'
link = 'view/%s' % data.req_id
elif error == 'not_authorized':
title = 'Authorization Error'
msg = 'You are not authorized to perform the requested operation.'
link = ''
else:
return self.unknown_error()
return render.error(title, msg, link)
def unknown_error(self):
title = 'Unknown Error'
msg = 'Click link below to goto home page.'
link = ''
return render.error(title, msg, link)
def argument_error():
"""Call this function whenever invalid arguments are provided by user in
URL string"""
raise web.seeother('/error/bogus_arguments')
def authorization_error():
"""Call this function whenever user attempts unauthorized action"""
raise web.seeother('/error/not_authorized')
class NewAdmin:
form = web.form.Form(
web.form.Textbox('username', web.form.notnull, size=30, description="Username:"),
web.form.Password('password', web.form.notnull, size=30, description="Password:"),
web.form.Password('password2', web.form.notnull, size=30, description="Repeat Password:"),
web.form.Textbox('name', web.form.notnull, size=30, description="Name:"),
web.form.Textbox('email', web.form.notnull, web.form.regexp(r'.*@.*\..*', 'Invalid email'), size=30, description="Email:"),
web.form.Textbox('email2', web.form.notnull, size=30, description="Repeat Email:"),
web.form.Textbox('phone', web.form.notnull, size=30, description="Phone:"),
web.form.Button('OK', type='submit'),
validators = [ web.form.Validator("Passwords do not match",
lambda i: i.password == i.password2),
web.form.Validator("Email addresses do not match",
lambda i: i.email == i.email2),
]
)
def GET(self):
if not session.admin:
authorization_error()
form = self.form()
return render.newadmin(form)
def POST(self):
if not session.admin:
authorization_error()
form = self.form()
if not form.validates():
return render.newadmin(form)
passhash = hashlib.md5(form.d.password.encode()).hexdigest()
model.add_contact(form.d.username, passhash, form.d.name, form.d.email, form.d.phone)
raise web.seeother('/')
class EditAdmin:
def GET(self):
if not session.admin:
authorization_error()
admin = model.get_contacts(session.userId)
#print(admin)
form = NewAdmin.form()
form.fill(admin)
return render.editadmin(form)
def POST(self):
if not session.admin:
authorization_error()
form = NewAdmin.form()
if not form.validates():
return render.editadmin(form)
passhash = hashlib.md5(form.d.password.encode()).hexdigest()
model.update_contact(session.userId, form.d.username, passhash, form.d.name, form.d.email, form.d.phone)
raise web.seeother('/')
class RemoveAdmin:
def gen_form(self):
form = web.form.Form(
web.form.Dropdown('admindropid', [(contact.id,contact.name) for contact in model.get_contacts()], web.form.notnull, size=5, description="Remove:"),
web.form.Button('Remove', type='submit')
)
return form
def GET(self):
if not session.admin and session.userId == 1:
authorization_error()
form = self.gen_form()
return render.rmadmin(form)
def POST(self):
if not session.admin and session.userId == 1:
authorization_error()
form = self.gen_form()
if not form.validates():
return render.rmadmin(form)
model.rm_contact(form.d.admindropid)
raise web.seeother('/')
if __name__ == '__main__':
app.run()