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
import mg_globals
23 from mediagoblin
.auth
import lib
as auth_lib
24 from mediagoblin
.db
.models
import User
25 from mediagoblin
.tests
.tools
import setup_fresh_app
, get_app
, fixture_add_user
26 from mediagoblin
.tools
import template
, mail
29 ########################
30 # Test bcrypt auth funcs
31 ########################
33 def test_bcrypt_check_password():
34 # Check known 'lollerskates' password against check function
35 assert auth_lib
.bcrypt_check_password(
37 '$2a$12$PXU03zfrVCujBhVeICTwtOaHTUs5FFwsscvSSTJkqx/2RQ0Lhy/nO')
39 assert not auth_lib
.bcrypt_check_password(
41 '$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
)
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')
64 assert not auth_lib
.bcrypt_check_password(
65 'notthepassword', hashed_pw
, '3><7R45417')
69 def test_register_views(test_app
):
71 Massive test function that all our registration-related views all work.
73 # Test doing a simple GET on the page
74 # -----------------------------------
76 test_app
.get('/auth/register/')
77 # Make sure it rendered with the appropriate template
78 assert 'mediagoblin/auth/register.html' in template
.TEMPLATE_TEST_CONTEXT
80 # Try to register without providing anything, should error
81 # --------------------------------------------------------
83 template
.clear_test_template_context()
85 '/auth/register/', {})
86 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
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.']
90 assert form
.email
.errors
== [u
'This field is required.']
92 # Try to register with fields that are known to be invalid
93 # --------------------------------------------------------
96 template
.clear_test_template_context()
102 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
103 form
= context
['register_form']
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.'])
109 template
.clear_test_template_context()
113 'email': 'lollerskates'})
114 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
115 form
= context
['register_form']
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.'])
120 ## At this point there should be no users in the database ;)
121 assert_equal(User
.query
.count(), 0)
123 # Successful register
124 # -------------------
125 template
.clear_test_template_context()
126 response
= test_app
.post(
128 'username': u
'happygirl',
129 'password': 'iamsohappy',
130 'email': 'happygrrl@example.org'})
133 ## Did we redirect to the proper page? Use the right template?
135 urlparse
.urlsplit(response
.location
)[2],
137 assert 'mediagoblin/user_pages/user.html' in template
.TEMPLATE_TEST_CONTEXT
139 ## Make sure user is in place
140 new_user
= mg_globals
.database
.User
.find_one(
141 {'username': u
'happygirl'})
143 assert new_user
.status
== u
'needs_email_verification'
144 assert new_user
.email_verified
== False
146 ## Make sure user is logged in
147 request
= template
.TEMPLATE_TEST_CONTEXT
[
148 'mediagoblin/user_pages/user.html']['request']
149 assert request
.session
['user_id'] == unicode(new_user
.id)
151 ## Make sure we get email confirmation, and try verifying
152 assert len(mail
.EMAIL_TEST_INBOX
) == 1
153 message
= mail
.EMAIL_TEST_INBOX
.pop()
154 assert message
['To'] == 'happygrrl@example.org'
155 email_context
= template
.TEMPLATE_TEST_CONTEXT
[
156 'mediagoblin/auth/verification_email.txt']
157 assert email_context
['verification_url'] in message
.get_payload(decode
=True)
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
)
164 ### user should have these same parameters
165 assert parsed_get_params
['userid'] == [
166 unicode(new_user
.id)]
167 assert parsed_get_params
['token'] == [
168 new_user
.verification_key
]
170 ## Try verifying with bs verification key, shouldn't work
171 template
.clear_test_template_context()
172 response
= test_app
.get(
173 "/auth/verify_email/?userid=%s&token=total_bs" % unicode(
176 context
= template
.TEMPLATE_TEST_CONTEXT
[
177 'mediagoblin/user_pages/user.html']
178 # assert context['verification_successful'] == True
179 # TODO: Would be good to test messages here when we can do so...
180 new_user
= mg_globals
.database
.User
.find_one(
181 {'username': u
'happygirl'})
183 assert new_user
.status
== u
'needs_email_verification'
184 assert new_user
.email_verified
== False
186 ## Verify the email activation works
187 template
.clear_test_template_context()
188 response
= test_app
.get("%s?%s" % (path
, get_params
))
190 context
= template
.TEMPLATE_TEST_CONTEXT
[
191 'mediagoblin/user_pages/user.html']
192 # assert context['verification_successful'] == True
193 # TODO: Would be good to test messages here when we can do so...
194 new_user
= mg_globals
.database
.User
.find_one(
195 {'username': u
'happygirl'})
197 assert new_user
.status
== u
'active'
198 assert new_user
.email_verified
== True
202 ## We shouldn't be able to register with that user twice
203 template
.clear_test_template_context()
204 response
= test_app
.post(
206 'username': u
'happygirl',
207 'password': 'iamsohappy2',
208 'email': 'happygrrl2@example.org'})
210 context
= template
.TEMPLATE_TEST_CONTEXT
[
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.']
216 ## TODO: Also check for double instances of an email address?
218 ### Oops, forgot the password
219 # -------------------
220 template
.clear_test_template_context()
221 response
= test_app
.post(
222 '/auth/forgot_password/',
223 {'username': u
'happygirl'})
226 ## Did we redirect to the proper page? Use the right template?
228 urlparse
.urlsplit(response
.location
)[2],
230 assert 'mediagoblin/auth/login.html' in template
.TEMPLATE_TEST_CONTEXT
232 ## Make sure link to change password is sent by email
233 assert len(mail
.EMAIL_TEST_INBOX
) == 1
234 message
= mail
.EMAIL_TEST_INBOX
.pop()
235 assert message
['To'] == 'happygrrl@example.org'
236 email_context
= template
.TEMPLATE_TEST_CONTEXT
[
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)
241 path
= urlparse
.urlsplit(email_context
['verification_url'])[2]
242 get_params
= urlparse
.urlsplit(email_context
['verification_url'])[3]
243 assert path
== u
'/auth/forgot_password/verify/'
244 parsed_get_params
= urlparse
.parse_qs(get_params
)
246 # user should have matching parameters
247 new_user
= mg_globals
.database
.User
.find_one({'username': u
'happygirl'})
248 assert parsed_get_params
['userid'] == [unicode(new_user
.id)]
249 assert parsed_get_params
['token'] == [new_user
.fp_verification_key
]
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...
253 assert (new_user
.fp_token_expire
- datetime
.datetime
.now()).days
== 9
255 ## Try using a bs password-changing verification key, shouldn't work
256 template
.clear_test_template_context()
257 response
= test_app
.get(
258 "/auth/forgot_password/verify/?userid=%s&token=total_bs" % unicode(
259 new_user
.id), status
=404)
260 assert_equal(response
.status
.split()[0], u
'404') # status="404 NOT FOUND"
262 ## Try using an expired token to change password, shouldn't work
263 template
.clear_test_template_context()
264 new_user
= mg_globals
.database
.User
.find_one({'username': u
'happygirl'})
265 real_token_expiration
= new_user
.fp_token_expire
266 new_user
.fp_token_expire
= datetime
.datetime
.now()
268 response
= test_app
.get("%s?%s" % (path
, get_params
), status
=404)
269 assert_equal(response
.status
.split()[0], u
'404') # status="404 NOT FOUND"
270 new_user
.fp_token_expire
= real_token_expiration
273 ## Verify step 1 of password-change works -- can see form to change password
274 template
.clear_test_template_context()
275 response
= test_app
.get("%s?%s" % (path
, get_params
))
276 assert 'mediagoblin/auth/change_fp.html' in template
.TEMPLATE_TEST_CONTEXT
278 ## Verify step 2.1 of password-change works -- report success to user
279 template
.clear_test_template_context()
280 response
= test_app
.post(
281 '/auth/forgot_password/verify/', {
282 'userid': parsed_get_params
['userid'],
283 'password': 'iamveryveryhappy',
284 'token': parsed_get_params
['token']})
286 assert 'mediagoblin/auth/login.html' in template
.TEMPLATE_TEST_CONTEXT
288 ## Verify step 2.2 of password-change works -- login w/ new password success
289 template
.clear_test_template_context()
290 response
= test_app
.post(
292 'username': u
'happygirl',
293 'password': 'iamveryveryhappy'})
295 # User should be redirected
298 urlparse
.urlsplit(response
.location
)[2],
300 assert 'mediagoblin/root.html' in template
.TEMPLATE_TEST_CONTEXT
303 def test_authentication_views():
305 Test logging in and logging out
307 test_app
= get_app(dump_old_app
=False)
309 test_user
= fixture_add_user(active_user
=False)
313 test_app
.get('/auth/login/')
314 assert 'mediagoblin/auth/login.html' in template
.TEMPLATE_TEST_CONTEXT
316 # Failed login - blank form
317 # -------------------------
318 template
.clear_test_template_context()
319 response
= test_app
.post('/auth/login/')
320 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
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.']
325 # Failed login - blank user
326 # -------------------------
327 template
.clear_test_template_context()
328 response
= test_app
.post(
330 'password': u
'toast'})
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.']
335 # Failed login - blank password
336 # -----------------------------
337 template
.clear_test_template_context()
338 response
= test_app
.post(
340 'username': u
'chris'})
341 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
342 form
= context
['login_form']
343 assert form
.password
.errors
== [u
'This field is required.']
345 # Failed login - bad user
346 # -----------------------
347 template
.clear_test_template_context()
348 response
= test_app
.post(
350 'username': u
'steve',
351 'password': 'toast'})
352 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
353 assert context
['login_failed']
355 # Failed login - bad password
356 # ---------------------------
357 template
.clear_test_template_context()
358 response
= test_app
.post(
360 'username': u
'chris',
361 'password': 'jam_and_ham'})
362 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
363 assert context
['login_failed']
367 template
.clear_test_template_context()
368 response
= test_app
.post(
370 'username': u
'chris',
371 'password': 'toast'})
373 # User should be redirected
376 urlparse
.urlsplit(response
.location
)[2],
378 assert 'mediagoblin/root.html' in template
.TEMPLATE_TEST_CONTEXT
380 # Make sure user is in the session
381 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/root.html']
382 session
= context
['request'].session
383 assert session
['user_id'] == unicode(test_user
.id)
387 template
.clear_test_template_context()
388 response
= test_app
.get('/auth/logout/')
390 # Should be redirected to index page
393 urlparse
.urlsplit(response
.location
)[2],
395 assert 'mediagoblin/root.html' in template
.TEMPLATE_TEST_CONTEXT
397 # Make sure the user is not in the session
398 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/root.html']
399 session
= context
['request'].session
400 assert 'user_id' not in session
402 # User is redirected to custom URL if POST['next'] is set
403 # -------------------------------------------------------
404 template
.clear_test_template_context()
405 response
= test_app
.post(
407 'username': u
'chris',
409 'next' : '/u/chris/'})
411 urlparse
.urlsplit(response
.location
)[2],