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': u
'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': u
'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': u
'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': u
'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': u
'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': u
'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': u
'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 new_user
= mg_globals
.database
.User
.find_one({'username': u
'happygirl'})
273 real_token_expiration
= new_user
.fp_token_expire
274 new_user
.fp_token_expire
= datetime
.datetime
.now()
276 response
= test_app
.get("%s?%s" % (path
, get_params
), status
=404)
277 assert_equal(response
.status
, '404 Not Found')
278 new_user
.fp_token_expire
= real_token_expiration
281 ## Verify step 1 of password-change works -- can see form to change password
282 template
.clear_test_template_context()
283 response
= test_app
.get("%s?%s" % (path
, get_params
))
284 assert template
.TEMPLATE_TEST_CONTEXT
.has_key('mediagoblin/auth/change_fp.html')
286 ## Verify step 2.1 of password-change works -- report success to user
287 template
.clear_test_template_context()
288 response
= test_app
.post(
289 '/auth/forgot_password/verify/', {
290 'userid': parsed_get_params
['userid'],
291 'password': 'iamveryveryhappy',
292 'token': parsed_get_params
['token']})
294 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
295 'mediagoblin/auth/login.html')
297 ## Verify step 2.2 of password-change works -- login w/ new password success
298 template
.clear_test_template_context()
299 response
= test_app
.post(
301 'username': u
'happygirl',
302 'password': 'iamveryveryhappy'})
304 # User should be redirected
307 urlparse
.urlsplit(response
.location
)[2],
309 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
310 'mediagoblin/root.html')
314 def test_authentication_views(test_app
):
316 Test logging in and logging out
319 test_user
= fixture_add_user(active_user
=False)
323 test_app
.get('/auth/login/')
324 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
325 'mediagoblin/auth/login.html')
327 # Failed login - blank form
328 # -------------------------
329 template
.clear_test_template_context()
330 response
= test_app
.post('/auth/login/')
331 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
332 form
= context
['login_form']
333 assert form
.username
.errors
== [u
'This field is required.']
334 assert form
.password
.errors
== [u
'This field is required.']
336 # Failed login - blank user
337 # -------------------------
338 template
.clear_test_template_context()
339 response
= test_app
.post(
341 'password': u
'toast'})
342 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
343 form
= context
['login_form']
344 assert form
.username
.errors
== [u
'This field is required.']
346 # Failed login - blank password
347 # -----------------------------
348 template
.clear_test_template_context()
349 response
= test_app
.post(
351 'username': u
'chris'})
352 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
353 form
= context
['login_form']
354 assert form
.password
.errors
== [u
'This field is required.']
356 # Failed login - bad user
357 # -----------------------
358 template
.clear_test_template_context()
359 response
= test_app
.post(
361 'username': u
'steve',
362 'password': 'toast'})
363 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
364 assert context
['login_failed']
366 # Failed login - bad password
367 # ---------------------------
368 template
.clear_test_template_context()
369 response
= test_app
.post(
371 'username': u
'chris',
373 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
374 assert context
['login_failed']
378 template
.clear_test_template_context()
379 response
= test_app
.post(
381 'username': u
'chris',
382 'password': 'toast'})
384 # User should be redirected
387 urlparse
.urlsplit(response
.location
)[2],
389 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
390 'mediagoblin/root.html')
392 # Make sure user is in the session
393 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/root.html']
394 session
= context
['request'].session
395 assert session
['user_id'] == unicode(test_user
._id
)
399 template
.clear_test_template_context()
400 response
= test_app
.get('/auth/logout/')
402 # Should be redirected to index page
405 urlparse
.urlsplit(response
.location
)[2],
407 assert template
.TEMPLATE_TEST_CONTEXT
.has_key(
408 'mediagoblin/root.html')
410 # Make sure the user is not in the session
411 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/root.html']
412 session
= context
['request'].session
413 assert session
.has_key('user_id') == False
415 # User is redirected to custom URL if POST['next'] is set
416 # -------------------------------------------------------
417 template
.clear_test_template_context()
418 response
= test_app
.post(
420 'username': u
'chris',
422 'next' : '/u/chris/'})
424 urlparse
.urlsplit(response
.location
)[2],