Merge remote branch 'remotes/gullydwarf-cfdv/b503_remove_inert_prev_nav_buttons'
[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 import uuid
18
19 from webob import exc
20
21 from mediagoblin import messages
22 from mediagoblin import mg_globals
23 from mediagoblin.util import render_to_response, redirect, render_404
24 from mediagoblin.util import pass_to_ugettext as _
25 from mediagoblin.db.util import ObjectId
26 from mediagoblin.auth import lib as auth_lib
27 from mediagoblin.auth import forms as auth_forms
28 from mediagoblin.auth.lib import send_verification_email
29
30
31 def register(request):
32 """
33 Your classic registration view!
34 """
35 # Redirects to indexpage if registrations are disabled
36 if not mg_globals.app_config["allow_registration"]:
37 messages.add_message(
38 request,
39 messages.WARNING,
40 _('Sorry, registration is disabled on this instance.'))
41 return redirect(request, "index")
42
43 register_form = auth_forms.RegistrationForm(request.POST)
44
45 if request.method == 'POST' and register_form.validate():
46 # TODO: Make sure the user doesn't exist already
47 username = unicode(request.POST['username'].lower())
48 email = unicode(request.POST['email'].lower())
49 users_with_username = request.db.User.find(
50 {'username': username}).count()
51 users_with_email = request.db.User.find(
52 {'email': email}).count()
53
54 extra_validation_passes = True
55
56 if users_with_username:
57 register_form.username.errors.append(
58 _(u'Sorry, a user with that name already exists.'))
59 extra_validation_passes = False
60 if users_with_email:
61 register_form.email.errors.append(
62 _(u'Sorry, that email address has already been taken.'))
63 extra_validation_passes = False
64
65 if extra_validation_passes:
66 # Create the user
67 user = request.db.User()
68 user['username'] = username
69 user['email'] = email
70 user['pw_hash'] = auth_lib.bcrypt_gen_password_hash(
71 request.POST['password'])
72 user.save(validate=True)
73
74 # log the user in
75 request.session['user_id'] = unicode(user['_id'])
76 request.session.save()
77
78 # send verification email
79 send_verification_email(user, request)
80
81 # redirect the user to their homepage... there will be a
82 # message waiting for them to verify their email
83 return redirect(
84 request, 'mediagoblin.user_pages.user_home',
85 user=user['username'])
86
87 return render_to_response(
88 request,
89 'mediagoblin/auth/register.html',
90 {'register_form': register_form})
91
92
93 def login(request):
94 """
95 MediaGoblin login view.
96
97 If you provide the POST with 'next', it'll redirect to that view.
98 """
99 login_form = auth_forms.LoginForm(request.POST)
100
101 login_failed = False
102
103 if request.method == 'POST' and login_form.validate():
104 user = request.db.User.one(
105 {'username': request.POST['username'].lower()})
106
107 if user and user.check_login(request.POST['password']):
108 # set up login in session
109 request.session['user_id'] = unicode(user['_id'])
110 request.session.save()
111
112 if request.POST.get('next'):
113 return exc.HTTPFound(location=request.POST['next'])
114 else:
115 return redirect(request, "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 return render_to_response(
124 request,
125 'mediagoblin/auth/login.html',
126 {'login_form': login_form,
127 'next': request.GET.get('next') or request.POST.get('next'),
128 'login_failed': login_failed,
129 'allow_registration': mg_globals.app_config["allow_registration"]})
130
131
132 def logout(request):
133 # Maybe deleting the user_id parameter would be enough?
134 request.session.delete()
135
136 return redirect(request, "index")
137
138
139 def verify_email(request):
140 """
141 Email verification view
142
143 validates GET parameters against database and unlocks the user account, if
144 you are lucky :)
145 """
146 # If we don't have userid and token parameters, we can't do anything; 404
147 if not request.GET.has_key('userid') or not request.GET.has_key('token'):
148 return render_404(request)
149
150 user = request.db.User.find_one(
151 {'_id': ObjectId(unicode(request.GET['userid']))})
152
153 if user and user['verification_key'] == unicode(request.GET['token']):
154 user['status'] = u'active'
155 user['email_verified'] = True
156 user.save()
157 messages.add_message(
158 request,
159 messages.SUCCESS,
160 _("Your email address has been verified. "
161 "You may now login, edit your profile, and submit images!"))
162 else:
163 messages.add_message(
164 request,
165 messages.ERROR,
166 _('The verification key or user id is incorrect'))
167
168 return redirect(
169 request, 'mediagoblin.user_pages.user_home',
170 user=user['username'])
171
172
173 def resend_activation(request):
174 """
175 The reactivation view
176
177 Resend the activation email.
178 """
179 request.user['verification_key'] = unicode(uuid.uuid4())
180 request.user.save()
181
182 send_verification_email(request.user, request)
183
184 messages.add_message(
185 request,
186 messages.INFO,
187 _('Resent your verification email.'))
188 return redirect(
189 request, 'mediagoblin.user_pages.user_home',
190 user=request.user['username'])