Reverting "Always activate testing in every test module ever."
[mediagoblin.git] / mediagoblin / tests / test_auth.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
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.
8 #
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.
13 #
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/>.
16
17 import urlparse
18 import datetime
19
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
25
26
27 ########################
28 # Test bcrypt auth funcs
29 ########################
30
31 def test_bcrypt_check_password():
32 # Check known 'lollerskates' password against check function
33 assert auth_lib.bcrypt_check_password(
34 'lollerskates',
35 '$2a$12$PXU03zfrVCujBhVeICTwtOaHTUs5FFwsscvSSTJkqx/2RQ0Lhy/nO')
36
37 assert not auth_lib.bcrypt_check_password(
38 'notthepassword',
39 '$2a$12$PXU03zfrVCujBhVeICTwtOaHTUs5FFwsscvSSTJkqx/2RQ0Lhy/nO')
40
41 # Same thing, but with extra fake salt.
42 assert not auth_lib.bcrypt_check_password(
43 'notthepassword',
44 '$2a$12$ELVlnw3z1FMu6CEGs/L8XO8vl0BuWSlUHgh0rUrry9DUXGMUNWwl6',
45 '3><7R45417')
46
47
48 def test_bcrypt_gen_password_hash():
49 pw = 'youwillneverguessthis'
50
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(
54 pw, hashed_pw)
55 assert not auth_lib.bcrypt_check_password(
56 'notthepassword', hashed_pw)
57
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')
64
65
66 def test_register_views(test_app):
67 """
68 Massive test function that all our registration-related views all work.
69 """
70 # Test doing a simple GET on the page
71 # -----------------------------------
72
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
76
77 # Try to register without providing anything, should error
78 # --------------------------------------------------------
79
80 template.clear_test_template_context()
81 test_app.post(
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.']
88
89 # Try to register with fields that are known to be invalid
90 # --------------------------------------------------------
91
92 ## too short
93 template.clear_test_template_context()
94 test_app.post(
95 '/auth/register/', {
96 'username': 'l',
97 'password': 'o',
98 'email': 'l'})
99 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
100 form = context['register_form']
101
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.']
104
105 ## bad form
106 template.clear_test_template_context()
107 test_app.post(
108 '/auth/register/', {
109 'username': '@_@',
110 'email': 'lollerskates'})
111 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
112 form = context['register_form']
113
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.']
116
117 ## At this point there should be no users in the database ;)
118 assert User.query.count() == 0
119
120 # Successful register
121 # -------------------
122 template.clear_test_template_context()
123 response = test_app.post(
124 '/auth/register/', {
125 'username': u'happygirl',
126 'password': 'iamsohappy',
127 'email': 'happygrrl@example.org'})
128 response.follow()
129
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
133
134 ## Make sure user is in place
135 new_user = mg_globals.database.User.find_one(
136 {'username': u'happygirl'})
137 assert new_user
138 assert new_user.status == u'needs_email_verification'
139 assert new_user.email_verified == False
140
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)
145
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)
153
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)
158
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]
164
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(
169 new_user.id))
170 response.follow()
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'})
177 assert new_user
178 assert new_user.status == u'needs_email_verification'
179 assert new_user.email_verified == False
180
181 ## Verify the email activation works
182 template.clear_test_template_context()
183 response = test_app.get("%s?%s" % (path, get_params))
184 response.follow()
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'})
191 assert new_user
192 assert new_user.status == u'active'
193 assert new_user.email_verified == True
194
195 # Uniqueness checks
196 # -----------------
197 ## We shouldn't be able to register with that user twice
198 template.clear_test_template_context()
199 response = test_app.post(
200 '/auth/register/', {
201 'username': u'happygirl',
202 'password': 'iamsohappy2',
203 'email': 'happygrrl2@example.org'})
204
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.']
210
211 ## TODO: Also check for double instances of an email address?
212
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'})
219 response.follow()
220
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
224
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)
233
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)
238
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]
243
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
247
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"
254
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()
260 new_user.save()
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
264 new_user.save()
265
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
270
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']})
278 response.follow()
279 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
280
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(
284 '/auth/login/', {
285 'username': u'happygirl',
286 'password': 'iamveryveryhappy'})
287
288 # User should be redirected
289 response.follow()
290 assert urlparse.urlsplit(response.location)[2] == '/'
291 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
292
293
294 def test_authentication_views(test_app):
295 """
296 Test logging in and logging out
297 """
298 # Make a new user
299 test_user = fixture_add_user(active_user=False)
300
301 # Get login
302 # ---------
303 test_app.get('/auth/login/')
304 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
305
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.']
314
315 # Failed login - blank user
316 # -------------------------
317 template.clear_test_template_context()
318 response = test_app.post(
319 '/auth/login/', {
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.']
324
325 # Failed login - blank password
326 # -----------------------------
327 template.clear_test_template_context()
328 response = test_app.post(
329 '/auth/login/', {
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.']
334
335 # Failed login - bad user
336 # -----------------------
337 template.clear_test_template_context()
338 response = test_app.post(
339 '/auth/login/', {
340 'username': u'steve',
341 'password': 'toast'})
342 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
343 assert context['login_failed']
344
345 # Failed login - bad password
346 # ---------------------------
347 template.clear_test_template_context()
348 response = test_app.post(
349 '/auth/login/', {
350 'username': u'chris',
351 'password': 'jam_and_ham'})
352 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
353 assert context['login_failed']
354
355 # Successful login
356 # ----------------
357 template.clear_test_template_context()
358 response = test_app.post(
359 '/auth/login/', {
360 'username': u'chris',
361 'password': 'toast'})
362
363 # User should be redirected
364 response.follow()
365 assert urlparse.urlsplit(response.location)[2] == '/'
366 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
367
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)
372
373 # Successful logout
374 # -----------------
375 template.clear_test_template_context()
376 response = test_app.get('/auth/logout/')
377
378 # Should be redirected to index page
379 response.follow()
380 assert urlparse.urlsplit(response.location)[2] == '/'
381 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
382
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
387
388 # User is redirected to custom URL if POST['next'] is set
389 # -------------------------------------------------------
390 template.clear_test_template_context()
391 response = test_app.post(
392 '/auth/login/', {
393 'username': u'chris',
394 'password': 'toast',
395 'next' : '/u/chris/'})
396 assert urlparse.urlsplit(response.location)[2] == '/u/chris/'