]> asedeno.scripts.mit.edu Git - bluechips.git/blob - bluechips/controllers/user.py
c59733355c131c4f56e3df911fa204e5141c4182
[bluechips.git] / bluechips / controllers / user.py
1 """
2 Calculate the current state of the books
3 """
4
5 import logging
6
7 from bluechips.lib.base import *
8
9 import sqlalchemy
10 from sqlalchemy import orm
11
12 from pylons import request
13 from pylons.decorators import validate
14 from pylons.decorators.secure import authenticate_form
15
16 from formencode import validators, Schema, FancyValidator, Invalid
17
18 log = logging.getLogger(__name__)
19
20
21 class EmailSchema(Schema):
22     "Validate email updates."
23     allow_extra_fields = False
24     new_email = validators.Email()
25
26
27 class UniqueUsername(FancyValidator):
28     def _to_python(self, value, state):
29         u = meta.Session.query(model.User).\
30             filter(model.User.username == value).\
31             first()
32         if u:
33             raise Invalid(
34                 'That username already exists',
35                 value, state)
36         return value
37
38
39 class NewUserSchema(Schema):
40     "Validate new users."
41     allow_extra_fields = False
42     username = UniqueUsername(not_empty=True)
43     password = validators.String(if_missing=None)
44     confirm_password = validators.String(if_missing=None)
45     name = validators.String(not_empty=False)
46     resident = validators.StringBoolean(not_empty=True)
47     chained_validators = [
48         validators.FieldsMatch('password', 'confirm_password'),
49         ]
50
51
52 class UserController(BaseController):
53     def email(self):
54         c.title = 'User Settings'
55         return render('/user/email.mako')
56
57     @authenticate_form
58     @validate(schema=EmailSchema(), form='index')
59     def update(self):
60         new_email = self.form_result['new_email']
61         request.environ['user'].email = new_email
62         meta.Session.commit()
63         if new_email is None:
64             h.flash("Removed email address.")
65         else:
66             h.flash("Updated email address to '%s'." % new_email)
67         return h.redirect_to('/')
68
69     def new(self):
70         c.title = 'Register a New User'
71         return render('/user/new.mako')
72
73     @authenticate_form
74     @validate(schema=NewUserSchema(), form='new')
75     def create(self):
76         u = model.User(username=self.form_result['username'],
77                        resident=self.form_result['resident'])
78
79         if self.form_result['name']:
80             u.name = self.form_result['name']
81         else:
82             u.name = self.form_result['username']
83
84         if self.form_result['password'] is not None:
85             u.password = self.form_result['password']
86
87         meta.Session.save(u)
88         meta.Session.commit()
89
90         h.flash('Successfully created new user %s' % u.username)
91         return h.redirect_to('/')