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 mediagoblin
import mg_globals
21 from mediagoblin
.auth
import lib
as auth_lib
22 from mediagoblin
.db
.models
import User
23 from mediagoblin
.tests
.tools
import fixture_add_user
24 from mediagoblin
.tools
import template
, mail
27 ########################
28 # Test bcrypt auth funcs
29 ########################
31 def test_bcrypt_check_password():
32 # Check known 'lollerskates' password against check function
33 assert auth_lib
.bcrypt_check_password(
35 '$2a$12$PXU03zfrVCujBhVeICTwtOaHTUs5FFwsscvSSTJkqx/2RQ0Lhy/nO')
37 assert not auth_lib
.bcrypt_check_password(
39 '$2a$12$PXU03zfrVCujBhVeICTwtOaHTUs5FFwsscvSSTJkqx/2RQ0Lhy/nO')
41 # Same thing, but with extra fake salt.
42 assert not auth_lib
.bcrypt_check_password(
44 '$2a$12$ELVlnw3z1FMu6CEGs/L8XO8vl0BuWSlUHgh0rUrry9DUXGMUNWwl6',
48 def test_bcrypt_gen_password_hash():
49 pw
= 'youwillneverguessthis'
51 # Normal password hash generation, and check on that hash
52 hashed_pw
= auth_lib
.bcrypt_gen_password_hash(pw
)
53 assert auth_lib
.bcrypt_check_password(
55 assert not auth_lib
.bcrypt_check_password(
56 'notthepassword', hashed_pw
)
58 # Same thing, extra salt.
59 hashed_pw
= auth_lib
.bcrypt_gen_password_hash(pw
, '3><7R45417')
60 assert auth_lib
.bcrypt_check_password(
61 pw
, hashed_pw
, '3><7R45417')
62 assert not auth_lib
.bcrypt_check_password(
63 'notthepassword', hashed_pw
, '3><7R45417')
66 def test_register_views(test_app
):
68 Massive test function that all our registration-related views all work.
70 # Test doing a simple GET on the page
71 # -----------------------------------
73 test_app
.get('/auth/register/')
74 # Make sure it rendered with the appropriate template
75 assert 'mediagoblin/auth/register.html' in template
.TEMPLATE_TEST_CONTEXT
77 # Try to register without providing anything, should error
78 # --------------------------------------------------------
80 template
.clear_test_template_context()
82 '/auth/register/', {})
83 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
84 form
= context
['register_form']
85 assert form
.username
.errors
== [u
'This field is required.']
86 assert form
.password
.errors
== [u
'This field is required.']
87 assert form
.email
.errors
== [u
'This field is required.']
89 # Try to register with fields that are known to be invalid
90 # --------------------------------------------------------
93 template
.clear_test_template_context()
99 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
100 form
= context
['register_form']
102 assert form
.username
.errors
== [u
'Field must be between 3 and 30 characters long.']
103 assert form
.password
.errors
== [u
'Field must be between 5 and 1024 characters long.']
106 template
.clear_test_template_context()
110 'email': 'lollerskates'})
111 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/register.html']
112 form
= context
['register_form']
114 assert form
.username
.errors
== [u
'This field does not take email addresses.']
115 assert form
.email
.errors
== [u
'This field requires an email address.']
117 ## At this point there should be no users in the database ;)
118 assert User
.query
.count() == 0
120 # Successful register
121 # -------------------
122 template
.clear_test_template_context()
123 response
= test_app
.post(
125 'username': u
'happygirl',
126 'password': 'iamsohappy',
127 'email': 'happygrrl@example.org'})
130 ## Did we redirect to the proper page? Use the right template?
131 assert urlparse
.urlsplit(response
.location
)[2] == '/u/happygirl/'
132 assert 'mediagoblin/user_pages/user.html' in template
.TEMPLATE_TEST_CONTEXT
134 ## Make sure user is in place
135 new_user
= mg_globals
.database
.User
.find_one(
136 {'username': u
'happygirl'})
138 assert new_user
.status
== u
'needs_email_verification'
139 assert new_user
.email_verified
== False
141 ## Make sure user is logged in
142 request
= template
.TEMPLATE_TEST_CONTEXT
[
143 'mediagoblin/user_pages/user.html']['request']
144 assert request
.session
['user_id'] == unicode(new_user
.id)
146 ## Make sure we get email confirmation, and try verifying
147 assert len(mail
.EMAIL_TEST_INBOX
) == 1
148 message
= mail
.EMAIL_TEST_INBOX
.pop()
149 assert message
['To'] == 'happygrrl@example.org'
150 email_context
= template
.TEMPLATE_TEST_CONTEXT
[
151 'mediagoblin/auth/verification_email.txt']
152 assert email_context
['verification_url'] in message
.get_payload(decode
=True)
154 path
= urlparse
.urlsplit(email_context
['verification_url'])[2]
155 get_params
= urlparse
.urlsplit(email_context
['verification_url'])[3]
156 assert path
== u
'/auth/verify_email/'
157 parsed_get_params
= urlparse
.parse_qs(get_params
)
159 ### user should have these same parameters
160 assert parsed_get_params
['userid'] == [
161 unicode(new_user
.id)]
162 assert parsed_get_params
['token'] == [
163 new_user
.verification_key
]
165 ## Try verifying with bs verification key, shouldn't work
166 template
.clear_test_template_context()
167 response
= test_app
.get(
168 "/auth/verify_email/?userid=%s&token=total_bs" % unicode(
171 context
= template
.TEMPLATE_TEST_CONTEXT
[
172 'mediagoblin/user_pages/user.html']
173 # assert context['verification_successful'] == True
174 # TODO: Would be good to test messages here when we can do so...
175 new_user
= mg_globals
.database
.User
.find_one(
176 {'username': u
'happygirl'})
178 assert new_user
.status
== u
'needs_email_verification'
179 assert new_user
.email_verified
== False
181 ## Verify the email activation works
182 template
.clear_test_template_context()
183 response
= test_app
.get("%s?%s" % (path
, get_params
))
185 context
= template
.TEMPLATE_TEST_CONTEXT
[
186 'mediagoblin/user_pages/user.html']
187 # assert context['verification_successful'] == True
188 # TODO: Would be good to test messages here when we can do so...
189 new_user
= mg_globals
.database
.User
.find_one(
190 {'username': u
'happygirl'})
192 assert new_user
.status
== u
'active'
193 assert new_user
.email_verified
== True
197 ## We shouldn't be able to register with that user twice
198 template
.clear_test_template_context()
199 response
= test_app
.post(
201 'username': u
'happygirl',
202 'password': 'iamsohappy2',
203 'email': 'happygrrl2@example.org'})
205 context
= template
.TEMPLATE_TEST_CONTEXT
[
206 'mediagoblin/auth/register.html']
207 form
= context
['register_form']
208 assert form
.username
.errors
== [
209 u
'Sorry, a user with that name already exists.']
211 ## TODO: Also check for double instances of an email address?
213 ### Oops, forgot the password
214 # -------------------
215 template
.clear_test_template_context()
216 response
= test_app
.post(
217 '/auth/forgot_password/',
218 {'username': u
'happygirl'})
221 ## Did we redirect to the proper page? Use the right template?
222 assert urlparse
.urlsplit(response
.location
)[2] == '/auth/login/'
223 assert 'mediagoblin/auth/login.html' in template
.TEMPLATE_TEST_CONTEXT
225 ## Make sure link to change password is sent by email
226 assert len(mail
.EMAIL_TEST_INBOX
) == 1
227 message
= mail
.EMAIL_TEST_INBOX
.pop()
228 assert message
['To'] == 'happygrrl@example.org'
229 email_context
= template
.TEMPLATE_TEST_CONTEXT
[
230 'mediagoblin/auth/fp_verification_email.txt']
231 #TODO - change the name of verification_url to something forgot-password-ish
232 assert email_context
['verification_url'] in message
.get_payload(decode
=True)
234 path
= urlparse
.urlsplit(email_context
['verification_url'])[2]
235 get_params
= urlparse
.urlsplit(email_context
['verification_url'])[3]
236 assert path
== u
'/auth/forgot_password/verify/'
237 parsed_get_params
= urlparse
.parse_qs(get_params
)
239 # user should have matching parameters
240 new_user
= mg_globals
.database
.User
.find_one({'username': u
'happygirl'})
241 assert parsed_get_params
['userid'] == [unicode(new_user
.id)]
242 assert parsed_get_params
['token'] == [new_user
.fp_verification_key
]
244 ### The forgotten password token should be set to expire in ~ 10 days
245 # A few ticks have expired so there are only 9 full days left...
246 assert (new_user
.fp_token_expire
- datetime
.datetime
.now()).days
== 9
248 ## Try using a bs password-changing verification key, shouldn't work
249 template
.clear_test_template_context()
250 response
= test_app
.get(
251 "/auth/forgot_password/verify/?userid=%s&token=total_bs" % unicode(
252 new_user
.id), status
=404)
253 assert response
.status
.split()[0] == u
'404' # status="404 NOT FOUND"
255 ## Try using an expired token to change password, shouldn't work
256 template
.clear_test_template_context()
257 new_user
= mg_globals
.database
.User
.find_one({'username': u
'happygirl'})
258 real_token_expiration
= new_user
.fp_token_expire
259 new_user
.fp_token_expire
= datetime
.datetime
.now()
261 response
= test_app
.get("%s?%s" % (path
, get_params
), status
=404)
262 assert response
.status
.split()[0] == u
'404' # status="404 NOT FOUND"
263 new_user
.fp_token_expire
= real_token_expiration
266 ## Verify step 1 of password-change works -- can see form to change password
267 template
.clear_test_template_context()
268 response
= test_app
.get("%s?%s" % (path
, get_params
))
269 assert 'mediagoblin/auth/change_fp.html' in template
.TEMPLATE_TEST_CONTEXT
271 ## Verify step 2.1 of password-change works -- report success to user
272 template
.clear_test_template_context()
273 response
= test_app
.post(
274 '/auth/forgot_password/verify/', {
275 'userid': parsed_get_params
['userid'],
276 'password': 'iamveryveryhappy',
277 'token': parsed_get_params
['token']})
279 assert 'mediagoblin/auth/login.html' in template
.TEMPLATE_TEST_CONTEXT
281 ## Verify step 2.2 of password-change works -- login w/ new password success
282 template
.clear_test_template_context()
283 response
= test_app
.post(
285 'username': u
'happygirl',
286 'password': 'iamveryveryhappy'})
288 # User should be redirected
290 assert urlparse
.urlsplit(response
.location
)[2] == '/'
291 assert 'mediagoblin/root.html' in template
.TEMPLATE_TEST_CONTEXT
294 def test_authentication_views(test_app
):
296 Test logging in and logging out
299 test_user
= fixture_add_user(active_user
=False)
303 test_app
.get('/auth/login/')
304 assert 'mediagoblin/auth/login.html' in template
.TEMPLATE_TEST_CONTEXT
306 # Failed login - blank form
307 # -------------------------
308 template
.clear_test_template_context()
309 response
= test_app
.post('/auth/login/')
310 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
311 form
= context
['login_form']
312 assert form
.username
.errors
== [u
'This field is required.']
313 assert form
.password
.errors
== [u
'This field is required.']
315 # Failed login - blank user
316 # -------------------------
317 template
.clear_test_template_context()
318 response
= test_app
.post(
320 'password': u
'toast'})
321 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
322 form
= context
['login_form']
323 assert form
.username
.errors
== [u
'This field is required.']
325 # Failed login - blank password
326 # -----------------------------
327 template
.clear_test_template_context()
328 response
= test_app
.post(
330 'username': u
'chris'})
331 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
332 form
= context
['login_form']
333 assert form
.password
.errors
== [u
'This field is required.']
335 # Failed login - bad user
336 # -----------------------
337 template
.clear_test_template_context()
338 response
= test_app
.post(
340 'username': u
'steve',
341 'password': 'toast'})
342 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
343 assert context
['login_failed']
345 # Failed login - bad password
346 # ---------------------------
347 template
.clear_test_template_context()
348 response
= test_app
.post(
350 'username': u
'chris',
351 'password': 'jam_and_ham'})
352 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/auth/login.html']
353 assert context
['login_failed']
357 template
.clear_test_template_context()
358 response
= test_app
.post(
360 'username': u
'chris',
361 'password': 'toast'})
363 # User should be redirected
365 assert urlparse
.urlsplit(response
.location
)[2] == '/'
366 assert 'mediagoblin/root.html' in template
.TEMPLATE_TEST_CONTEXT
368 # Make sure user is in the session
369 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/root.html']
370 session
= context
['request'].session
371 assert session
['user_id'] == unicode(test_user
.id)
375 template
.clear_test_template_context()
376 response
= test_app
.get('/auth/logout/')
378 # Should be redirected to index page
380 assert urlparse
.urlsplit(response
.location
)[2] == '/'
381 assert 'mediagoblin/root.html' in template
.TEMPLATE_TEST_CONTEXT
383 # Make sure the user is not in the session
384 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/root.html']
385 session
= context
['request'].session
386 assert 'user_id' not in session
388 # User is redirected to custom URL if POST['next'] is set
389 # -------------------------------------------------------
390 template
.clear_test_template_context()
391 response
= test_app
.post(
393 'username': u
'chris',
395 'next' : '/u/chris/'})
396 assert urlparse
.urlsplit(response
.location
)[2] == '/u/chris/'