f00456c4aa501122174907776fe660404d286623
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 MediaGoblin contributors. See AUTHORS.
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.
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.
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/>.
20 from nose
.tools
import assert_equal
22 from mediagoblin
.auth
import lib
as auth_lib
23 from mediagoblin
.tests
.tools
import setup_fresh_app
24 from mediagoblin
import mg_globals
25 from mediagoblin
.tools
import template
28 ########################
29 # Test bcrypt auth funcs
30 ########################
32 def test_bcrypt_check_password():
33 # Check known 'lollerskates' password against check function
34 assert auth_lib
.bcrypt_check_password(
36 '$2a$12$PXU03zfrVCujBhVeICTwtOaHTUs5FFwsscvSSTJkqx/2RQ0Lhy/nO')
38 assert not auth_lib
.bcrypt_check_password(
40 '$2a$12$PXU03zfrVCujBhVeICTwtOaHTUs5FFwsscvSSTJkqx/2RQ0Lhy/nO')
43 # Same thing, but with extra fake salt.
44 assert not auth_lib
.bcrypt_check_password(
46 '$2a$12$ELVlnw3z1FMu6CEGs/L8XO8vl0BuWSlUHgh0rUrry9DUXGMUNWwl6',
50 def test_bcrypt_gen_password_hash():
51 pw
= 'youwillneverguessthis'
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(
57 assert not auth_lib
.bcrypt_check_password(
58 'notthepassword', hashed_pw
)
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')
70 def test_register_views(test_app
):
72 Massive test function that all our registration-related views all work.
74 # Test doing a simple GET on the page
75 # -----------------------------------
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')
82 # Try to register without providing anything, should error
83 # --------------------------------------------------------
85 template
.clear_test_template_context()
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
.confirm_password
.errors
== [u
'This field is required.']
93 assert form
.email
.errors
== [u
'This field is required.']
95 # Try to register with fields that are known to be invalid
96 # --------------------------------------------------------
99 template
.clear_test_template_context()
104 'confirm_password': 'o',
106 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
107 form
= context
['register_form']
109 assert form
.username
.errors
== [
110 u
'Field must be between 3 and 30 characters long.']
111 assert form
.password
.errors
== [
112 u
'Field must be between 6 and 30 characters long.']
115 template
.clear_test_template_context()
119 'email': 'lollerskates'})
120 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
121 form
= context
['register_form']
123 assert form
.username
.errors
== [
125 assert form
.email
.errors
== [
126 u
'Invalid email address.']
128 ## mismatching passwords
129 template
.clear_test_template_context()
132 'password': 'herpderp',
133 'confirm_password': 'derpherp'})
134 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
135 form
= context
['register_form']
137 assert form
.password
.errors
== [
138 u
'Passwords must match.']
140 ## At this point there should be no users in the database ;)
141 assert not mg_globals
.database
.User
.find().count()
143 # Successful register
144 # -------------------
145 template
.clear_test_template_context()
146 response
= test_app
.post(
148 'username': 'happygirl',
149 'password': 'iamsohappy',
150 'confirm_password': 'iamsohappy',
151 'email': 'happygrrl@example.org'})
154 ## Did we redirect to the proper page? Use the right template?
156 urlparse
.urlsplit(response
.location
)[2],
158 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
159 'mediagoblin/user_pages/user.html')
161 ## Make sure user is in place
162 new_user
= mg_globals
.database
.User
.find_one(
163 {'username': 'happygirl'})
165 assert new_user
['status'] == u
'needs_email_verification'
166 assert new_user
['email_verified'] == False
168 ## Make sure user is logged in
169 request
= template
.TEMPLATE_TEST_CONTEXT
[
170 'mediagoblin/user_pages/user.html']['request']
171 assert request
.session
['user_id'] == unicode(new_user
['_id'])
173 ## Make sure we get email confirmation, and try verifying
174 assert len(template
.EMAIL_TEST_INBOX
) == 1
175 message
= template
.EMAIL_TEST_INBOX
.pop()
176 assert message
['To'] == 'happygrrl@example.org'
177 email_context
= template
.TEMPLATE_TEST_CONTEXT
[
178 'mediagoblin/auth/verification_email.txt']
179 assert email_context
['verification_url'] in message
.get_payload(decode
=True)
181 path
= urlparse
.urlsplit(email_context
['verification_url'])[2]
182 get_params
= urlparse
.urlsplit(email_context
['verification_url'])[3]
183 assert path
== u
'/auth/verify_email/'
184 parsed_get_params
= urlparse
.parse_qs(get_params
)
186 ### user should have these same parameters
187 assert parsed_get_params
['userid'] == [
188 unicode(new_user
['_id'])]
189 assert parsed_get_params
['token'] == [
190 new_user
['verification_key']]
192 ## Try verifying with bs verification key, shouldn't work
193 template
.clear_test_template_context()
194 response
= test_app
.get(
195 "/auth/verify_email/?userid=%s&token=total_bs" % unicode(
198 context
= template
.TEMPLATE_TEST_CONTEXT
[
199 'mediagoblin/user_pages/user.html']
200 # assert context['verification_successful'] == True
201 # TODO: Would be good to test messages here when we can do so...
202 new_user
= mg_globals
.database
.User
.find_one(
203 {'username': 'happygirl'})
205 assert new_user
['status'] == u
'needs_email_verification'
206 assert new_user
['email_verified'] == False
208 ## Verify the email activation works
209 template
.clear_test_template_context()
210 response
= test_app
.get("%s?%s" % (path
, get_params
))
212 context
= template
.TEMPLATE_TEST_CONTEXT
[
213 'mediagoblin/user_pages/user.html']
214 # assert context['verification_successful'] == True
215 # TODO: Would be good to test messages here when we can do so...
216 new_user
= mg_globals
.database
.User
.find_one(
217 {'username': 'happygirl'})
219 assert new_user
['status'] == u
'active'
220 assert new_user
['email_verified'] == True
224 ## We shouldn't be able to register with that user twice
225 template
.clear_test_template_context()
226 response
= test_app
.post(
228 'username': 'happygirl',
229 'password': 'iamsohappy2',
230 'confirm_password': 'iamsohappy2',
231 'email': 'happygrrl2@example.org'})
233 context
= template
.TEMPLATE_TEST_CONTEXT
[
234 'mediagoblin/auth/register.html']
235 form
= context
['register_form']
236 assert form
.username
.errors
== [
237 u
'Sorry, a user with that name already exists.']
239 ## TODO: Also check for double instances of an email address?
241 ### Oops, forgot the password
242 # -------------------
243 template
.clear_test_template_context()
244 response
= test_app
.post(
245 '/auth/forgot_password/',
246 {'username': 'happygirl'})
249 ## Did we redirect to the proper page? Use the right template?
251 urlparse
.urlsplit(response
.location
)[2],
252 '/auth/forgot_password/email_sent/')
253 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
254 'mediagoblin/auth/fp_email_sent.html')
256 ## Make sure link to change password is sent by email
257 assert len(template
.EMAIL_TEST_INBOX
) == 1
258 message
= template
.EMAIL_TEST_INBOX
.pop()
259 assert message
['To'] == 'happygrrl@example.org'
260 email_context
= template
.TEMPLATE_TEST_CONTEXT
[
261 'mediagoblin/auth/fp_verification_email.txt']
262 #TODO - change the name of verification_url to something forgot-password-ish
263 assert email_context
['verification_url'] in message
.get_payload(decode
=True)
265 path
= urlparse
.urlsplit(email_context
['verification_url'])[2]
266 get_params
= urlparse
.urlsplit(email_context
['verification_url'])[3]
267 assert path
== u
'/auth/forgot_password/verify/'
268 parsed_get_params
= urlparse
.parse_qs(get_params
)
270 # user should have matching parameters
271 new_user
= mg_globals
.database
.User
.find_one({'username': 'happygirl'})
272 assert parsed_get_params
['userid'] == [unicode(new_user
['_id'])]
273 assert parsed_get_params
['token'] == [new_user
['fp_verification_key']]
275 ### The forgotten password token should be set to expire in ~ 10 days
276 # A few ticks have expired so there are only 9 full days left...
277 assert (new_user
['fp_token_expire'] - datetime
.datetime
.now()).days
== 9
279 ## Try using a bs password-changing verification key, shouldn't work
280 template
.clear_test_template_context()
281 response
= test_app
.get(
282 "/auth/forgot_password/verify/?userid=%s&token=total_bs" % unicode(
283 new_user
['_id']), status
=400)
284 assert response
.status
== '400 Bad Request'
286 ## Try using an expired token to change password, shouldn't work
287 template
.clear_test_template_context()
288 real_token_expiration
= new_user
['fp_token_expire']
289 new_user
['fp_token_expire'] = datetime
.datetime
.now()
291 response
= test_app
.get("%s?%s" % (path
, get_params
), status
=400)
292 assert response
.status
== '400 Bad Request'
293 new_user
['fp_token_expire'] = real_token_expiration
296 ## Verify step 1 of password-change works -- can see form to change password
297 template
.clear_test_template_context()
298 response
= test_app
.get("%s?%s" % (path
, get_params
))
299 assert template
.TEMPLATE_TEST_CONTEXT
.has_key('mediagoblin/auth/change_fp.html')
301 ## Verify step 2.1 of password-change works -- report success to user
302 template
.clear_test_template_context()
303 response
= test_app
.post(
304 '/auth/forgot_password/verify/', {
305 'userid': parsed_get_params
['userid'],
306 'password': 'iamveryveryhappy',
307 'confirm_password': 'iamveryveryhappy',
308 'token': parsed_get_params
['token']})
310 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
311 'mediagoblin/auth/fp_changed_success.html')
313 ## Verify step 2.2 of password-change works -- login w/ new password success
314 template
.clear_test_template_context()
315 response
= test_app
.post(
317 'username': u
'happygirl',
318 'password': 'iamveryveryhappy'})
320 # User should be redirected
323 urlparse
.urlsplit(response
.location
)[2],
325 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
326 'mediagoblin/root.html')
330 def test_authentication_views(test_app
):
332 Test logging in and logging out
335 test_user
= mg_globals
.database
.User()
336 test_user
['username'] = u
'chris'
337 test_user
['email'] = u
'chris@example.com'
338 test_user
['pw_hash'] = auth_lib
.bcrypt_gen_password_hash('toast')
343 test_app
.get('/auth/login/')
344 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
345 'mediagoblin/auth/login.html')
347 # Failed login - blank form
348 # -------------------------
349 template
.clear_test_template_context()
350 response
= test_app
.post('/auth/login/')
351 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
352 form
= context
['login_form']
353 assert form
.username
.errors
== [u
'This field is required.']
354 assert form
.password
.errors
== [u
'This field is required.']
356 # Failed login - blank user
357 # -------------------------
358 template
.clear_test_template_context()
359 response
= test_app
.post(
361 'password': u
'toast'})
362 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
363 form
= context
['login_form']
364 assert form
.username
.errors
== [u
'This field is required.']
366 # Failed login - blank password
367 # -----------------------------
368 template
.clear_test_template_context()
369 response
= test_app
.post(
371 'username': u
'chris'})
372 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
373 form
= context
['login_form']
374 assert form
.password
.errors
== [u
'This field is required.']
376 # Failed login - bad user
377 # -----------------------
378 template
.clear_test_template_context()
379 response
= test_app
.post(
381 'username': u
'steve',
382 'password': 'toast'})
383 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
384 assert context
['login_failed']
386 # Failed login - bad password
387 # ---------------------------
388 template
.clear_test_template_context()
389 response
= test_app
.post(
391 'username': u
'chris',
393 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
394 assert context
['login_failed']
398 template
.clear_test_template_context()
399 response
= test_app
.post(
401 'username': u
'chris',
402 'password': 'toast'})
404 # User should be redirected
407 urlparse
.urlsplit(response
.location
)[2],
409 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
410 'mediagoblin/root.html')
412 # Make sure user is in the session
413 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/root.html']
414 session
= context
['request'].session
415 assert session
['user_id'] == unicode(test_user
['_id'])
419 template
.clear_test_template_context()
420 response
= test_app
.get('/auth/logout/')
422 # Should be redirected to index page
425 urlparse
.urlsplit(response
.location
)[2],
427 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
428 'mediagoblin/root.html')
430 # Make sure the user is not in the session
431 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/root.html']
432 session
= context
['request'].session
433 assert session
.has_key('user_id') == False
435 # User is redirected to custom URL if POST['next'] is set
436 # -------------------------------------------------------
437 template
.clear_test_template_context()
438 response
= test_app
.post(
440 'username': u
'chris',
442 'next' : '/u/chris/'})
444 urlparse
.urlsplit(response
.location
)[2],