Merge branch 'master' into sqlmigrate
[mediagoblin.git] / mediagoblin / tests / test_auth.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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 urlparse
18 import datetime
19
20 from nose.tools import assert_equal
21
22 from mediagoblin.auth import lib as auth_lib
23 from mediagoblin.tests.tools import setup_fresh_app, fixture_add_user
24 from mediagoblin import mg_globals
25 from mediagoblin.tools import template, mail
26
27
28 ########################
29 # Test bcrypt auth funcs
30 ########################
31
32 def test_bcrypt_check_password():
33 # Check known 'lollerskates' password against check function
34 assert auth_lib.bcrypt_check_password(
35 'lollerskates',
36 '$2a$12$PXU03zfrVCujBhVeICTwtOaHTUs5FFwsscvSSTJkqx/2RQ0Lhy/nO')
37
38 assert not auth_lib.bcrypt_check_password(
39 'notthepassword',
40 '$2a$12$PXU03zfrVCujBhVeICTwtOaHTUs5FFwsscvSSTJkqx/2RQ0Lhy/nO')
41
42
43 # Same thing, but with extra fake salt.
44 assert not auth_lib.bcrypt_check_password(
45 'notthepassword',
46 '$2a$12$ELVlnw3z1FMu6CEGs/L8XO8vl0BuWSlUHgh0rUrry9DUXGMUNWwl6',
47 '3><7R45417')
48
49
50 def test_bcrypt_gen_password_hash():
51 pw = 'youwillneverguessthis'
52
53 # Normal password hash generation, and check on that hash
54 hashed_pw = auth_lib.bcrypt_gen_password_hash(pw)
55 assert auth_lib.bcrypt_check_password(
56 pw, hashed_pw)
57 assert not auth_lib.bcrypt_check_password(
58 'notthepassword', hashed_pw)
59
60
61 # Same thing, extra salt.
62 hashed_pw = auth_lib.bcrypt_gen_password_hash(pw, '3><7R45417')
63 assert auth_lib.bcrypt_check_password(
64 pw, hashed_pw, '3><7R45417')
65 assert not auth_lib.bcrypt_check_password(
66 'notthepassword', hashed_pw, '3><7R45417')
67
68
69 @setup_fresh_app
70 def test_register_views(test_app):
71 """
72 Massive test function that all our registration-related views all work.
73 """
74 # Test doing a simple GET on the page
75 # -----------------------------------
76
77 test_app.get('/auth/register/')
78 # Make sure it rendered with the appropriate template
79 assert template.TEMPLATE_TEST_CONTEXT.has_key(
80 'mediagoblin/auth/register.html')
81
82 # Try to register without providing anything, should error
83 # --------------------------------------------------------
84
85 template.clear_test_template_context()
86 test_app.post(
87 '/auth/register/', {})
88 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
89 form = context['register_form']
90 assert form.username.errors == [u'This field is required.']
91 assert form.password.errors == [u'This field is required.']
92 assert form.email.errors == [u'This field is required.']
93
94 # Try to register with fields that are known to be invalid
95 # --------------------------------------------------------
96
97 ## too short
98 template.clear_test_template_context()
99 test_app.post(
100 '/auth/register/', {
101 'username': 'l',
102 'password': 'o',
103 'email': 'l'})
104 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
105 form = context['register_form']
106
107 assert form.username.errors == [
108 u'Field must be between 3 and 30 characters long.']
109 assert form.password.errors == [
110 u'Field must be between 6 and 30 characters long.']
111
112 ## bad form
113 template.clear_test_template_context()
114 test_app.post(
115 '/auth/register/', {
116 'username': '@_@',
117 'email': 'lollerskates'})
118 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
119 form = context['register_form']
120
121 assert form.username.errors == [
122 u'Invalid input.']
123 assert form.email.errors == [
124 u'Invalid email address.']
125
126 ## At this point there should be no users in the database ;)
127 assert not mg_globals.database.User.find().count()
128
129 # Successful register
130 # -------------------
131 template.clear_test_template_context()
132 response = test_app.post(
133 '/auth/register/', {
134 'username': 'happygirl',
135 'password': 'iamsohappy',
136 'email': 'happygrrl@example.org'})
137 response.follow()
138
139 ## Did we redirect to the proper page? Use the right template?
140 assert_equal(
141 urlparse.urlsplit(response.location)[2],
142 '/u/happygirl/')
143 assert template.TEMPLATE_TEST_CONTEXT.has_key(
144 'mediagoblin/user_pages/user.html')
145
146 ## Make sure user is in place
147 new_user = mg_globals.database.User.find_one(
148 {'username': 'happygirl'})
149 assert new_user
150 assert new_user.status == u'needs_email_verification'
151 assert new_user.email_verified == False
152
153 ## Make sure user is logged in
154 request = template.TEMPLATE_TEST_CONTEXT[
155 'mediagoblin/user_pages/user.html']['request']
156 assert request.session['user_id'] == unicode(new_user._id)
157
158 ## Make sure we get email confirmation, and try verifying
159 assert len(mail.EMAIL_TEST_INBOX) == 1
160 message = mail.EMAIL_TEST_INBOX.pop()
161 assert message['To'] == 'happygrrl@example.org'
162 email_context = template.TEMPLATE_TEST_CONTEXT[
163 'mediagoblin/auth/verification_email.txt']
164 assert email_context['verification_url'] in message.get_payload(decode=True)
165
166 path = urlparse.urlsplit(email_context['verification_url'])[2]
167 get_params = urlparse.urlsplit(email_context['verification_url'])[3]
168 assert path == u'/auth/verify_email/'
169 parsed_get_params = urlparse.parse_qs(get_params)
170
171 ### user should have these same parameters
172 assert parsed_get_params['userid'] == [
173 unicode(new_user._id)]
174 assert parsed_get_params['token'] == [
175 new_user.verification_key]
176
177 ## Try verifying with bs verification key, shouldn't work
178 template.clear_test_template_context()
179 response = test_app.get(
180 "/auth/verify_email/?userid=%s&token=total_bs" % unicode(
181 new_user._id))
182 response.follow()
183 context = template.TEMPLATE_TEST_CONTEXT[
184 'mediagoblin/user_pages/user.html']
185 # assert context['verification_successful'] == True
186 # TODO: Would be good to test messages here when we can do so...
187 new_user = mg_globals.database.User.find_one(
188 {'username': 'happygirl'})
189 assert new_user
190 assert new_user.status == u'needs_email_verification'
191 assert new_user.email_verified == False
192
193 ## Verify the email activation works
194 template.clear_test_template_context()
195 response = test_app.get("%s?%s" % (path, get_params))
196 response.follow()
197 context = template.TEMPLATE_TEST_CONTEXT[
198 'mediagoblin/user_pages/user.html']
199 # assert context['verification_successful'] == True
200 # TODO: Would be good to test messages here when we can do so...
201 new_user = mg_globals.database.User.find_one(
202 {'username': 'happygirl'})
203 assert new_user
204 assert new_user.status == u'active'
205 assert new_user.email_verified == True
206
207 # Uniqueness checks
208 # -----------------
209 ## We shouldn't be able to register with that user twice
210 template.clear_test_template_context()
211 response = test_app.post(
212 '/auth/register/', {
213 'username': 'happygirl',
214 'password': 'iamsohappy2',
215 'email': 'happygrrl2@example.org'})
216
217 context = template.TEMPLATE_TEST_CONTEXT[
218 'mediagoblin/auth/register.html']
219 form = context['register_form']
220 assert form.username.errors == [
221 u'Sorry, a user with that name already exists.']
222
223 ## TODO: Also check for double instances of an email address?
224
225 ### Oops, forgot the password
226 # -------------------
227 template.clear_test_template_context()
228 response = test_app.post(
229 '/auth/forgot_password/',
230 {'username': 'happygirl'})
231 response.follow()
232
233 ## Did we redirect to the proper page? Use the right template?
234 assert_equal(
235 urlparse.urlsplit(response.location)[2],
236 '/auth/login/')
237 assert template.TEMPLATE_TEST_CONTEXT.has_key(
238 'mediagoblin/auth/login.html')
239
240 ## Make sure link to change password is sent by email
241 assert len(mail.EMAIL_TEST_INBOX) == 1
242 message = mail.EMAIL_TEST_INBOX.pop()
243 assert message['To'] == 'happygrrl@example.org'
244 email_context = template.TEMPLATE_TEST_CONTEXT[
245 'mediagoblin/auth/fp_verification_email.txt']
246 #TODO - change the name of verification_url to something forgot-password-ish
247 assert email_context['verification_url'] in message.get_payload(decode=True)
248
249 path = urlparse.urlsplit(email_context['verification_url'])[2]
250 get_params = urlparse.urlsplit(email_context['verification_url'])[3]
251 assert path == u'/auth/forgot_password/verify/'
252 parsed_get_params = urlparse.parse_qs(get_params)
253
254 # user should have matching parameters
255 new_user = mg_globals.database.User.find_one({'username': 'happygirl'})
256 assert parsed_get_params['userid'] == [unicode(new_user._id)]
257 assert parsed_get_params['token'] == [new_user.fp_verification_key]
258
259 ### The forgotten password token should be set to expire in ~ 10 days
260 # A few ticks have expired so there are only 9 full days left...
261 assert (new_user.fp_token_expire - datetime.datetime.now()).days == 9
262
263 ## Try using a bs password-changing verification key, shouldn't work
264 template.clear_test_template_context()
265 response = test_app.get(
266 "/auth/forgot_password/verify/?userid=%s&token=total_bs" % unicode(
267 new_user._id), status=404)
268 assert_equal(response.status, '404 Not Found')
269
270 ## Try using an expired token to change password, shouldn't work
271 template.clear_test_template_context()
272 real_token_expiration = new_user.fp_token_expire
273 new_user.fp_token_expire = datetime.datetime.now()
274 new_user.save()
275 response = test_app.get("%s?%s" % (path, get_params), status=404)
276 assert_equal(response.status, '404 Not Found')
277 new_user.fp_token_expire = real_token_expiration
278 new_user.save()
279
280 ## Verify step 1 of password-change works -- can see form to change password
281 template.clear_test_template_context()
282 response = test_app.get("%s?%s" % (path, get_params))
283 assert template.TEMPLATE_TEST_CONTEXT.has_key('mediagoblin/auth/change_fp.html')
284
285 ## Verify step 2.1 of password-change works -- report success to user
286 template.clear_test_template_context()
287 response = test_app.post(
288 '/auth/forgot_password/verify/', {
289 'userid': parsed_get_params['userid'],
290 'password': 'iamveryveryhappy',
291 'token': parsed_get_params['token']})
292 response.follow()
293 assert template.TEMPLATE_TEST_CONTEXT.has_key(
294 'mediagoblin/auth/login.html')
295
296 ## Verify step 2.2 of password-change works -- login w/ new password success
297 template.clear_test_template_context()
298 response = test_app.post(
299 '/auth/login/', {
300 'username': u'happygirl',
301 'password': 'iamveryveryhappy'})
302
303 # User should be redirected
304 response.follow()
305 assert_equal(
306 urlparse.urlsplit(response.location)[2],
307 '/')
308 assert template.TEMPLATE_TEST_CONTEXT.has_key(
309 'mediagoblin/root.html')
310
311
312 @setup_fresh_app
313 def test_authentication_views(test_app):
314 """
315 Test logging in and logging out
316 """
317 # Make a new user
318 test_user = fixture_add_user(active_user=False)
319
320 # Get login
321 # ---------
322 test_app.get('/auth/login/')
323 assert template.TEMPLATE_TEST_CONTEXT.has_key(
324 'mediagoblin/auth/login.html')
325
326 # Failed login - blank form
327 # -------------------------
328 template.clear_test_template_context()
329 response = test_app.post('/auth/login/')
330 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
331 form = context['login_form']
332 assert form.username.errors == [u'This field is required.']
333 assert form.password.errors == [u'This field is required.']
334
335 # Failed login - blank user
336 # -------------------------
337 template.clear_test_template_context()
338 response = test_app.post(
339 '/auth/login/', {
340 'password': u'toast'})
341 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
342 form = context['login_form']
343 assert form.username.errors == [u'This field is required.']
344
345 # Failed login - blank password
346 # -----------------------------
347 template.clear_test_template_context()
348 response = test_app.post(
349 '/auth/login/', {
350 'username': u'chris'})
351 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
352 form = context['login_form']
353 assert form.password.errors == [u'This field is required.']
354
355 # Failed login - bad user
356 # -----------------------
357 template.clear_test_template_context()
358 response = test_app.post(
359 '/auth/login/', {
360 'username': u'steve',
361 'password': 'toast'})
362 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
363 assert context['login_failed']
364
365 # Failed login - bad password
366 # ---------------------------
367 template.clear_test_template_context()
368 response = test_app.post(
369 '/auth/login/', {
370 'username': u'chris',
371 'password': 'jam'})
372 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
373 assert context['login_failed']
374
375 # Successful login
376 # ----------------
377 template.clear_test_template_context()
378 response = test_app.post(
379 '/auth/login/', {
380 'username': u'chris',
381 'password': 'toast'})
382
383 # User should be redirected
384 response.follow()
385 assert_equal(
386 urlparse.urlsplit(response.location)[2],
387 '/')
388 assert template.TEMPLATE_TEST_CONTEXT.has_key(
389 'mediagoblin/root.html')
390
391 # Make sure user is in the session
392 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html']
393 session = context['request'].session
394 assert session['user_id'] == unicode(test_user._id)
395
396 # Successful logout
397 # -----------------
398 template.clear_test_template_context()
399 response = test_app.get('/auth/logout/')
400
401 # Should be redirected to index page
402 response.follow()
403 assert_equal(
404 urlparse.urlsplit(response.location)[2],
405 '/')
406 assert template.TEMPLATE_TEST_CONTEXT.has_key(
407 'mediagoblin/root.html')
408
409 # Make sure the user is not in the session
410 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html']
411 session = context['request'].session
412 assert session.has_key('user_id') == False
413
414 # User is redirected to custom URL if POST['next'] is set
415 # -------------------------------------------------------
416 template.clear_test_template_context()
417 response = test_app.post(
418 '/auth/login/', {
419 'username': u'chris',
420 'password': 'toast',
421 'next' : '/u/chris/'})
422 assert_equal(
423 urlparse.urlsplit(response.location)[2],
424 '/u/chris/')
425