1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 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
, fixture_add_user
24 from mediagoblin
import mg_globals
25 from mediagoblin
.tools
import template
, mail
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
.email
.errors
== [u
'This field is required.']
94 # Try to register with fields that are known to be invalid
95 # --------------------------------------------------------
98 template
.clear_test_template_context()
104 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
105 form
= context
['register_form']
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.']
113 template
.clear_test_template_context()
117 'email': 'lollerskates'})
118 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
119 form
= context
['register_form']
121 assert form
.username
.errors
== [
123 assert form
.email
.errors
== [
124 u
'Invalid email address.']
126 ## At this point there should be no users in the database ;)
127 assert not mg_globals
.database
.User
.find().count()
129 # Successful register
130 # -------------------
131 template
.clear_test_template_context()
132 response
= test_app
.post(
134 'username': 'happygirl',
135 'password': 'iamsohappy',
136 'email': 'happygrrl@example.org'})
139 ## Did we redirect to the proper page? Use the right template?
141 urlparse
.urlsplit(response
.location
)[2],
143 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
144 'mediagoblin/user_pages/user.html')
146 ## Make sure user is in place
147 new_user
= mg_globals
.database
.User
.find_one(
148 {'username': 'happygirl'})
150 assert new_user
.status
== u
'needs_email_verification'
151 assert new_user
.email_verified
== False
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
)
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)
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
)
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
]
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(
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'})
190 assert new_user
.status
== u
'needs_email_verification'
191 assert new_user
.email_verified
== False
193 ## Verify the email activation works
194 template
.clear_test_template_context()
195 response
= test_app
.get("%s?%s" % (path
, get_params
))
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'})
204 assert new_user
.status
== u
'active'
205 assert new_user
.email_verified
== True
209 ## We shouldn't be able to register with that user twice
210 template
.clear_test_template_context()
211 response
= test_app
.post(
213 'username': 'happygirl',
214 'password': 'iamsohappy2',
215 'email': 'happygrrl2@example.org'})
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.']
223 ## TODO: Also check for double instances of an email address?
225 ### Oops, forgot the password
226 # -------------------
227 template
.clear_test_template_context()
228 response
= test_app
.post(
229 '/auth/forgot_password/',
230 {'username': 'happygirl'})
233 ## Did we redirect to the proper page? Use the right template?
235 urlparse
.urlsplit(response
.location
)[2],
237 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
238 'mediagoblin/auth/login.html')
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)
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
)
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
]
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
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')
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()
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
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')
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']})
293 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
294 'mediagoblin/auth/login.html')
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(
300 'username': u
'happygirl',
301 'password': 'iamveryveryhappy'})
303 # User should be redirected
306 urlparse
.urlsplit(response
.location
)[2],
308 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
309 'mediagoblin/root.html')
313 def test_authentication_views(test_app
):
315 Test logging in and logging out
318 test_user
= fixture_add_user(active_user
=False)
322 test_app
.get('/auth/login/')
323 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
324 'mediagoblin/auth/login.html')
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.']
335 # Failed login - blank user
336 # -------------------------
337 template
.clear_test_template_context()
338 response
= test_app
.post(
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.']
345 # Failed login - blank password
346 # -----------------------------
347 template
.clear_test_template_context()
348 response
= test_app
.post(
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.']
355 # Failed login - bad user
356 # -----------------------
357 template
.clear_test_template_context()
358 response
= test_app
.post(
360 'username': u
'steve',
361 'password': 'toast'})
362 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
363 assert context
['login_failed']
365 # Failed login - bad password
366 # ---------------------------
367 template
.clear_test_template_context()
368 response
= test_app
.post(
370 'username': u
'chris',
372 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
373 assert context
['login_failed']
377 template
.clear_test_template_context()
378 response
= test_app
.post(
380 'username': u
'chris',
381 'password': 'toast'})
383 # User should be redirected
386 urlparse
.urlsplit(response
.location
)[2],
388 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
389 'mediagoblin/root.html')
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
)
398 template
.clear_test_template_context()
399 response
= test_app
.get('/auth/logout/')
401 # Should be redirected to index page
404 urlparse
.urlsplit(response
.location
)[2],
406 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
407 'mediagoblin/root.html')
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
414 # User is redirected to custom URL if POST['next'] is set
415 # -------------------------------------------------------
416 template
.clear_test_template_context()
417 response
= test_app
.post(
419 'username': u
'chris',
421 'next' : '/u/chris/'})
423 urlparse
.urlsplit(response
.location
)[2],