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