It's 2012 all up in here
[mediagoblin.git] / mediagoblin / tests / test_auth.py
CommitLineData
8e1e744d 1# GNU MediaGoblin -- federated, autonomous media hosting
cf29e8a8 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
4b5f4e87
CAW
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
1972a888 17import urlparse
65a83047 18import datetime
4b5f4e87 19
1972a888 20from nose.tools import assert_equal
4b5f4e87 21
1972a888 22from mediagoblin.auth import lib as auth_lib
9754802d 23from mediagoblin.tests.tools import setup_fresh_app, fixture_add_user
6e7ce8d1 24from mediagoblin import mg_globals
152a3bfa 25from mediagoblin.tools import template, mail
460ce564 26
4b5f4e87
CAW
27
28########################
29# Test bcrypt auth funcs
30########################
31
32def 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
db780024
CAW
38 assert not auth_lib.bcrypt_check_password(
39 'notthepassword',
40 '$2a$12$PXU03zfrVCujBhVeICTwtOaHTUs5FFwsscvSSTJkqx/2RQ0Lhy/nO')
41
42
4b5f4e87 43 # Same thing, but with extra fake salt.
db780024
CAW
44 assert not auth_lib.bcrypt_check_password(
45 'notthepassword',
4b5f4e87
CAW
46 '$2a$12$ELVlnw3z1FMu6CEGs/L8XO8vl0BuWSlUHgh0rUrry9DUXGMUNWwl6',
47 '3><7R45417')
48
49
50def 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)
db780024
CAW
57 assert not auth_lib.bcrypt_check_password(
58 'notthepassword', hashed_pw)
59
4b5f4e87
CAW
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')
db780024
CAW
65 assert not auth_lib.bcrypt_check_password(
66 'notthepassword', hashed_pw, '3><7R45417')
460ce564
CAW
67
68
3aa4c668
CAW
69@setup_fresh_app
70def test_register_views(test_app):
2fecc29d
CAW
71 """
72 Massive test function that all our registration-related views all work.
73 """
460ce564 74 # Test doing a simple GET on the page
651403f0
CAW
75 # -----------------------------------
76
460ce564
CAW
77 test_app.get('/auth/register/')
78 # Make sure it rendered with the appropriate template
ae3bc7fa 79 assert template.TEMPLATE_TEST_CONTEXT.has_key(
460ce564 80 'mediagoblin/auth/register.html')
757690cc 81
460ce564 82 # Try to register without providing anything, should error
651403f0
CAW
83 # --------------------------------------------------------
84
ae3bc7fa 85 template.clear_test_template_context()
460ce564
CAW
86 test_app.post(
87 '/auth/register/', {})
ae3bc7fa 88 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
460ce564
CAW
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.']
460ce564 92 assert form.email.errors == [u'This field is required.']
651403f0
CAW
93
94 # Try to register with fields that are known to be invalid
95 # --------------------------------------------------------
96
97 ## too short
ae3bc7fa 98 template.clear_test_template_context()
651403f0
CAW
99 test_app.post(
100 '/auth/register/', {
101 'username': 'l',
102 'password': 'o',
651403f0 103 'email': 'l'})
ae3bc7fa 104 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
651403f0
CAW
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
ae3bc7fa 113 template.clear_test_template_context()
651403f0
CAW
114 test_app.post(
115 '/auth/register/', {
116 'username': '@_@',
117 'email': 'lollerskates'})
ae3bc7fa 118 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
651403f0
CAW
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
651403f0 126 ## At this point there should be no users in the database ;)
6e7ce8d1 127 assert not mg_globals.database.User.find().count()
651403f0
CAW
128
129 # Successful register
130 # -------------------
ae3bc7fa 131 template.clear_test_template_context()
1972a888
CAW
132 response = test_app.post(
133 '/auth/register/', {
134 'username': 'happygirl',
135 'password': 'iamsohappy',
1972a888
CAW
136 'email': 'happygrrl@example.org'})
137 response.follow()
138
651403f0 139 ## Did we redirect to the proper page? Use the right template?
1972a888
CAW
140 assert_equal(
141 urlparse.urlsplit(response.location)[2],
0bc03620 142 '/u/happygirl/')
ae3bc7fa 143 assert template.TEMPLATE_TEST_CONTEXT.has_key(
0bc03620 144 'mediagoblin/user_pages/user.html')
1972a888 145
651403f0 146 ## Make sure user is in place
6e7ce8d1 147 new_user = mg_globals.database.User.find_one(
1972a888
CAW
148 {'username': 'happygirl'})
149 assert new_user
7a3d00ec 150 assert new_user.status == u'needs_email_verification'
4facc7a0 151 assert new_user.email_verified == False
1972a888 152
f73f4c4b 153 ## Make sure user is logged in
ae3bc7fa 154 request = template.TEMPLATE_TEST_CONTEXT[
f73f4c4b 155 'mediagoblin/user_pages/user.html']['request']
eabe6b67 156 assert request.session['user_id'] == unicode(new_user._id)
f73f4c4b 157
1972a888 158 ## Make sure we get email confirmation, and try verifying
152a3bfa
AW
159 assert len(mail.EMAIL_TEST_INBOX) == 1
160 message = mail.EMAIL_TEST_INBOX.pop()
1972a888 161 assert message['To'] == 'happygrrl@example.org'
ae3bc7fa 162 email_context = template.TEMPLATE_TEST_CONTEXT[
1972a888
CAW
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'] == [
eabe6b67 173 unicode(new_user._id)]
1972a888 174 assert parsed_get_params['token'] == [
00bb9550 175 new_user.verification_key]
757690cc 176
7b1e17ed 177 ## Try verifying with bs verification key, shouldn't work
ae3bc7fa 178 template.clear_test_template_context()
a656ccd5 179 response = test_app.get(
7b1e17ed 180 "/auth/verify_email/?userid=%s&token=total_bs" % unicode(
eabe6b67 181 new_user._id))
a656ccd5 182 response.follow()
ae3bc7fa 183 context = template.TEMPLATE_TEST_CONTEXT[
e054ae9b 184 'mediagoblin/user_pages/user.html']
a656ccd5
CAW
185 # assert context['verification_successful'] == True
186 # TODO: Would be good to test messages here when we can do so...
6e7ce8d1 187 new_user = mg_globals.database.User.find_one(
7b1e17ed
CAW
188 {'username': 'happygirl'})
189 assert new_user
7a3d00ec 190 assert new_user.status == u'needs_email_verification'
4facc7a0 191 assert new_user.email_verified == False
7b1e17ed
CAW
192
193 ## Verify the email activation works
ae3bc7fa 194 template.clear_test_template_context()
a656ccd5
CAW
195 response = test_app.get("%s?%s" % (path, get_params))
196 response.follow()
ae3bc7fa 197 context = template.TEMPLATE_TEST_CONTEXT[
e054ae9b 198 'mediagoblin/user_pages/user.html']
a656ccd5
CAW
199 # assert context['verification_successful'] == True
200 # TODO: Would be good to test messages here when we can do so...
6e7ce8d1 201 new_user = mg_globals.database.User.find_one(
7b1e17ed
CAW
202 {'username': 'happygirl'})
203 assert new_user
7a3d00ec 204 assert new_user.status == u'active'
4facc7a0 205 assert new_user.email_verified == True
1972a888 206
cb9bac0c
CAW
207 # Uniqueness checks
208 # -----------------
209 ## We shouldn't be able to register with that user twice
ae3bc7fa 210 template.clear_test_template_context()
8a869db8
CAW
211 response = test_app.post(
212 '/auth/register/', {
213 'username': 'happygirl',
214 'password': 'iamsohappy2',
8a869db8 215 'email': 'happygrrl2@example.org'})
757690cc 216
ae3bc7fa 217 context = template.TEMPLATE_TEST_CONTEXT[
8a869db8
CAW
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.']
651403f0 222
8a869db8 223 ## TODO: Also check for double instances of an email address?
757690cc 224
65a83047
CFD
225 ### Oops, forgot the password
226 # -------------------
ae3bc7fa 227 template.clear_test_template_context()
f03fef4e
CAW
228 response = test_app.post(
229 '/auth/forgot_password/',
230 {'username': 'happygirl'})
65a83047
CFD
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],
4601c30c 236 '/auth/login/')
ae3bc7fa 237 assert template.TEMPLATE_TEST_CONTEXT.has_key(
4601c30c 238 'mediagoblin/auth/login.html')
65a83047
CFD
239
240 ## Make sure link to change password is sent by email
152a3bfa
AW
241 assert len(mail.EMAIL_TEST_INBOX) == 1
242 message = mail.EMAIL_TEST_INBOX.pop()
65a83047 243 assert message['To'] == 'happygrrl@example.org'
ae3bc7fa 244 email_context = template.TEMPLATE_TEST_CONTEXT[
65a83047
CFD
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]
f03fef4e 251 assert path == u'/auth/forgot_password/verify/'
65a83047
CFD
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'})
eabe6b67 256 assert parsed_get_params['userid'] == [unicode(new_user._id)]
dc39e455 257 assert parsed_get_params['token'] == [new_user.fp_verification_key]
65a83047
CFD
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...
2d540fed 261 assert (new_user.fp_token_expire - datetime.datetime.now()).days == 9
65a83047
CFD
262
263 ## Try using a bs password-changing verification key, shouldn't work
ae3bc7fa 264 template.clear_test_template_context()
65a83047 265 response = test_app.get(
f03fef4e 266 "/auth/forgot_password/verify/?userid=%s&token=total_bs" % unicode(
93e46224
E
267 new_user._id), status=404)
268 assert_equal(response.status, '404 Not Found')
65a83047 269
4bcaf9f3 270 ## Try using an expired token to change password, shouldn't work
ae3bc7fa 271 template.clear_test_template_context()
2d540fed
E
272 real_token_expiration = new_user.fp_token_expire
273 new_user.fp_token_expire = datetime.datetime.now()
4bcaf9f3 274 new_user.save()
93e46224
E
275 response = test_app.get("%s?%s" % (path, get_params), status=404)
276 assert_equal(response.status, '404 Not Found')
2d540fed 277 new_user.fp_token_expire = real_token_expiration
4bcaf9f3
CFD
278 new_user.save()
279
65a83047 280 ## Verify step 1 of password-change works -- can see form to change password
ae3bc7fa 281 template.clear_test_template_context()
65a83047 282 response = test_app.get("%s?%s" % (path, get_params))
ae3bc7fa 283 assert template.TEMPLATE_TEST_CONTEXT.has_key('mediagoblin/auth/change_fp.html')
65a83047
CFD
284
285 ## Verify step 2.1 of password-change works -- report success to user
ae3bc7fa 286 template.clear_test_template_context()
65a83047 287 response = test_app.post(
f03fef4e 288 '/auth/forgot_password/verify/', {
65a83047
CFD
289 'userid': parsed_get_params['userid'],
290 'password': 'iamveryveryhappy',
65a83047
CFD
291 'token': parsed_get_params['token']})
292 response.follow()
ae3bc7fa 293 assert template.TEMPLATE_TEST_CONTEXT.has_key(
445d8110 294 'mediagoblin/auth/login.html')
65a83047
CFD
295
296 ## Verify step 2.2 of password-change works -- login w/ new password success
ae3bc7fa 297 template.clear_test_template_context()
65a83047
CFD
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 '/')
ae3bc7fa 308 assert template.TEMPLATE_TEST_CONTEXT.has_key(
65a83047
CFD
309 'mediagoblin/root.html')
310
757690cc
CM
311
312@setup_fresh_app
313def test_authentication_views(test_app):
314 """
315 Test logging in and logging out
316 """
317 # Make a new user
9754802d 318 test_user = fixture_add_user(active_user=False)
757690cc
CM
319
320 # Get login
0a4cecdc 321 # ---------
757690cc 322 test_app.get('/auth/login/')
ae3bc7fa 323 assert template.TEMPLATE_TEST_CONTEXT.has_key(
757690cc
CM
324 'mediagoblin/auth/login.html')
325
0a4cecdc
CM
326 # Failed login - blank form
327 # -------------------------
ae3bc7fa 328 template.clear_test_template_context()
0a4cecdc 329 response = test_app.post('/auth/login/')
ae3bc7fa 330 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
0a4cecdc
CM
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 # -------------------------
ae3bc7fa 337 template.clear_test_template_context()
0a4cecdc
CM
338 response = test_app.post(
339 '/auth/login/', {
340 'password': u'toast'})
ae3bc7fa 341 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
0a4cecdc
CM
342 form = context['login_form']
343 assert form.username.errors == [u'This field is required.']
344
345 # Failed login - blank password
346 # -----------------------------
ae3bc7fa 347 template.clear_test_template_context()
0a4cecdc
CM
348 response = test_app.post(
349 '/auth/login/', {
350 'username': u'chris'})
ae3bc7fa 351 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
0a4cecdc
CM
352 form = context['login_form']
353 assert form.password.errors == [u'This field is required.']
354
355 # Failed login - bad user
356 # -----------------------
ae3bc7fa 357 template.clear_test_template_context()
0a4cecdc
CM
358 response = test_app.post(
359 '/auth/login/', {
360 'username': u'steve',
361 'password': 'toast'})
ae3bc7fa 362 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
0a4cecdc
CM
363 assert context['login_failed']
364
365 # Failed login - bad password
366 # ---------------------------
ae3bc7fa 367 template.clear_test_template_context()
0a4cecdc
CM
368 response = test_app.post(
369 '/auth/login/', {
370 'username': u'chris',
371 'password': 'jam'})
ae3bc7fa 372 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
0a4cecdc
CM
373 assert context['login_failed']
374
375 # Successful login
376 # ----------------
ae3bc7fa 377 template.clear_test_template_context()
757690cc
CM
378 response = test_app.post(
379 '/auth/login/', {
380 'username': u'chris',
381 'password': 'toast'})
0a4cecdc
CM
382
383 # User should be redirected
757690cc
CM
384 response.follow()
385 assert_equal(
386 urlparse.urlsplit(response.location)[2],
387 '/')
ae3bc7fa 388 assert template.TEMPLATE_TEST_CONTEXT.has_key(
757690cc
CM
389 'mediagoblin/root.html')
390
0a4cecdc 391 # Make sure user is in the session
ae3bc7fa 392 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html']
0a4cecdc 393 session = context['request'].session
eabe6b67 394 assert session['user_id'] == unicode(test_user._id)
757690cc 395
0a4cecdc
CM
396 # Successful logout
397 # -----------------
ae3bc7fa 398 template.clear_test_template_context()
0a4cecdc
CM
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 '/')
ae3bc7fa 406 assert template.TEMPLATE_TEST_CONTEXT.has_key(
0a4cecdc
CM
407 'mediagoblin/root.html')
408
409 # Make sure the user is not in the session
ae3bc7fa 410 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html']
0a4cecdc
CM
411 session = context['request'].session
412 assert session.has_key('user_id') == False
757690cc 413
12c231c8
CM
414 # User is redirected to custom URL if POST['next'] is set
415 # -------------------------------------------------------
ae3bc7fa 416 template.clear_test_template_context()
12c231c8
CM
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