min=0 makes more sense than min=-1
[mediagoblin.git] / mediagoblin / auth / views.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 Free Software Foundation, Inc
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17
18 from webob import Response, exc
19
20 from mediagoblin.auth import lib as auth_lib
21 from mediagoblin.auth import forms as auth_forms
22 from mediagoblin.util import send_email
23 from mediagoblin import globals as mgoblin_globals
24
25
26 def register(request):
27 """
28 Your classic registration view!
29 """
30 register_form = auth_forms.RegistrationForm(request.POST)
31
32 if request.method == 'POST' and register_form.validate():
33 # TODO: Make sure the user doesn't exist already
34 users_with_username = \
35 request.db.User.find({'username': request.POST['username']}).count()
36
37 if users_with_username:
38 register_form.username.errors.append(
39 u'Sorry, a user with that name already exists.')
40
41 else:
42 # Create the user
43 entry = request.db.User()
44 entry['username'] = request.POST['username']
45 entry['email'] = request.POST['email']
46 entry['pw_hash'] = auth_lib.bcrypt_gen_password_hash(
47 request.POST['password'])
48 entry.save(validate=True)
49
50 email_template = request.template_env.get_template(
51 'mediagoblin/auth/verification_email.txt')
52
53 # TODO: There is no error handling in place
54 send_email(
55 mgoblin_globals.email_sender_address,
56 [entry['email']],
57 # TODO
58 # Due to the distributed nature of GNU MediaGoblin, we should
59 # find a way to send some additional information about the
60 # specific GNU MediaGoblin instance in the subject line. For
61 # example "GNU MediaGoblin @ Wandborg - [...]".
62 'GNU MediaGoblin - Verify email',
63 email_template.render(
64 username=entry['username'],
65 verification_url='http://{host}{uri}?userid={userid}&token={verification_key}'.format(
66 host=request.host,
67 uri=request.urlgen('mediagoblin.auth.verify_email'),
68 userid=unicode(entry['_id']),
69 verification_key=entry['verification_key'])))
70
71 # Redirect to register_success
72 return exc.HTTPFound(
73 location=request.urlgen("mediagoblin.auth.register_success"))
74
75 # render
76 template = request.template_env.get_template(
77 'mediagoblin/auth/register.html')
78 return Response(
79 template.render(
80 {'request': request,
81 'register_form': register_form}))
82
83
84 def register_success(request):
85 template = request.template_env.get_template(
86 'mediagoblin/auth/register_success.html')
87 return Response(
88 template.render(
89 {'request': request}))
90
91
92 def login(request):
93 """
94 MediaGoblin login view.
95
96 If you provide the POST with 'next', it'll redirect to that view.
97 """
98 login_form = auth_forms.LoginForm(request.POST)
99
100 login_failed = False
101
102 if request.method == 'POST' and login_form.validate():
103 user = request.db.User.one(
104 {'username': request.POST['username']})
105
106 if user and user.check_login(request.POST['password']):
107 # set up login in session
108 request.session['user_id'] = unicode(user['_id'])
109 request.session.save()
110
111 if request.POST.get('next'):
112 return exc.HTTPFound(location=request.POST['next'])
113 else:
114 return exc.HTTPFound(
115 location=request.urlgen("index"))
116
117 else:
118 # Prevent detecting who's on this system by testing login
119 # attempt timings
120 auth_lib.fake_login_attempt()
121 login_failed = True
122
123 # render
124 template = request.template_env.get_template(
125 'mediagoblin/auth/login.html')
126 return Response(
127 template.render(
128 {'request': request,
129 'login_form': login_form,
130 'next': request.GET.get('next') or request.POST.get('next'),
131 'login_failed': login_failed}))
132
133
134 def logout(request):
135 # Maybe deleting the user_id parameter would be enough?
136 request.session.delete()
137
138 return exc.HTTPFound(
139 location=request.urlgen("index"))
140
141 def verify_email(request):
142 """
143 Email verification view
144
145 validates GET parameters against database and unlocks the user account, if
146 you are lucky :)
147 """
148 import bson.objectid
149 user = request.db.User.find_one(
150 {'_id': bson.objectid.ObjectId(unicode(request.GET.get('userid')))})
151
152 verification_successful = bool
153
154 if user and user['verification_key'] == unicode(request.GET.get('token')):
155 user['status'] = u'active'
156 user['email_verified'] = True
157 verification_successful = True
158 user.save()
159 else:
160 verification_successful = False
161
162 template = request.template_env.get_template(
163 'mediagoblin/auth/verify_email.html')
164 return Response(
165 template.render(
166 {'request': request,
167 'user': user,
168 'verification_successful': verification_successful}))