Test with short and long username
[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 pkg_resources
18 import pytest
19
20 import six
21
22 import six.moves.urllib.parse as urlparse
23
24 from mediagoblin import mg_globals
25 from mediagoblin.db.models import User, LocalUser
26 from mediagoblin.tests.tools import get_app, fixture_add_user
27 from mediagoblin.tools import template, mail
28 from mediagoblin.auth import tools as auth_tools
29
30
31 def test_register_views(test_app):
32 """
33 Massive test function that all our registration-related views all work.
34 """
35 # Test doing a simple GET on the page
36 # -----------------------------------
37
38 test_app.get('/auth/register/')
39 # Make sure it rendered with the appropriate template
40 assert 'mediagoblin/auth/register.html' in template.TEMPLATE_TEST_CONTEXT
41
42 # Try to register without providing anything, should error
43 # --------------------------------------------------------
44
45 template.clear_test_template_context()
46 test_app.post(
47 '/auth/register/', {})
48 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
49 form = context['register_form']
50 assert form.username.errors == [u'This field is required.']
51 assert form.password.errors == [u'This field is required.']
52 assert form.email.errors == [u'This field is required.']
53
54 # Try to register with fields that are known to be invalid
55 # --------------------------------------------------------
56
57 ## too short
58 template.clear_test_template_context()
59 test_app.post(
60 '/auth/register/', {
61 'username': 'l',
62 'password': 'o',
63 'email': 'l'})
64 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
65 form = context['register_form']
66
67 assert form.username.errors == [u'Field must be between 3 and 30 characters long.']
68 assert form.password.errors == [u'Field must be between 5 and 1024 characters long.']
69
70 ## bad form
71 template.clear_test_template_context()
72 test_app.post(
73 '/auth/register/', {
74 'username': '@_@',
75 'email': 'lollerskates'})
76 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
77 form = context['register_form']
78
79 assert form.username.errors == [u'This field does not take email addresses.']
80 assert form.email.errors == [u'This field requires an email address.']
81
82 ## invalid characters
83 template.clear_test_template_context()
84 test_app.post(
85 '/auth/register/', {
86 'username': 'ampersand&invalid',
87 'email': 'easter@egg.com'})
88 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
89 form = context['register_form']
90
91 assert form.username.errors == [u'Invalid input.']
92
93 ## At this point there should be no users in the database ;)
94 assert User.query.count() == 0
95
96 ## mixture of characters from all valid ranges
97 template.clear_test_template_context()
98 test_app.post(
99 '/auth/register/', {
100 'username': 'Jean-Louis1_Le-Chat',
101 'password': 'iamsohappy',
102 'email': 'easter@egg.com'})
103
104 ## At this point there should on user in the database
105 assert User.query.count() == 1
106
107 # Successful register
108 # -------------------
109 template.clear_test_template_context()
110 response = test_app.post(
111 '/auth/register/', {
112 'username': u'angrygirl',
113 'password': 'iamsoangry',
114 'email': 'angrygrrl@example.org'})
115 response.follow()
116
117 ## Did we redirect to the proper page? Use the right template?
118 assert urlparse.urlsplit(response.location)[2] == '/u/angrygirl/'
119 assert 'mediagoblin/user_pages/user_nonactive.html' in template.TEMPLATE_TEST_CONTEXT
120
121 ## Make sure user is in place
122 new_user = mg_globals.database.LocalUser.query.filter(
123 LocalUser.username==u'angrygirl'
124 ).first()
125 assert new_user
126
127 ## Make sure that the proper privileges are granted on registration
128
129 assert new_user.has_privilege(u'commenter')
130 assert new_user.has_privilege(u'uploader')
131 assert new_user.has_privilege(u'reporter')
132 assert not new_user.has_privilege(u'active')
133 ## Make sure user is logged in
134 request = template.TEMPLATE_TEST_CONTEXT[
135 'mediagoblin/user_pages/user_nonactive.html']['request']
136 assert request.session['user_id'] == six.text_type(new_user.id)
137
138 ## Make sure we get email confirmation, and try verifying
139 assert len(mail.EMAIL_TEST_INBOX) == 2
140 message = mail.EMAIL_TEST_INBOX.pop()
141 assert message['To'] == 'angrygrrl@example.org'
142 email_context = template.TEMPLATE_TEST_CONTEXT[
143 'mediagoblin/auth/verification_email.txt']
144 assert email_context['verification_url'].encode('ascii') in message.get_payload(decode=True)
145
146 path = urlparse.urlsplit(email_context['verification_url'])[2]
147 get_params = urlparse.urlsplit(email_context['verification_url'])[3]
148 assert path == u'/auth/verify_email/'
149 parsed_get_params = urlparse.parse_qs(get_params)
150
151 ## Try verifying with bs verification key, shouldn't work
152 template.clear_test_template_context()
153 response = test_app.get(
154 "/auth/verify_email/?token=total_bs")
155 response.follow()
156
157 # Correct redirect?
158 assert urlparse.urlsplit(response.location)[2] == '/'
159
160 # assert context['verification_successful'] == True
161 # TODO: Would be good to test messages here when we can do so...
162 new_user = mg_globals.database.LocalUser.query.filter(
163 LocalUser.username==u'angrygirl'
164 ).first()
165 assert new_user
166
167 ## Verify the email activation works
168 template.clear_test_template_context()
169 response = test_app.get("%s?%s" % (path, get_params))
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.LocalUser.query.filter(
176 LocalUser.username==u'angrygirl'
177 ).first()
178 assert new_user
179
180 # Uniqueness checks
181 # -----------------
182 ## We shouldn't be able to register with that user twice
183 template.clear_test_template_context()
184 response = test_app.post(
185 '/auth/register/', {
186 'username': u'angrygirl',
187 'password': 'iamsoangry2',
188 'email': 'angrygrrl2@example.org'})
189
190 context = template.TEMPLATE_TEST_CONTEXT[
191 'mediagoblin/auth/register.html']
192 form = context['register_form']
193 assert form.username.errors == [
194 u'Sorry, a user with that name already exists.']
195
196 ## TODO: Also check for double instances of an email address?
197
198 ### Oops, forgot the password
199 # -------------------
200 template.clear_test_template_context()
201 response = test_app.post(
202 '/auth/forgot_password/',
203 {'username': u'angrygirl'})
204 response.follow()
205
206 ## Did we redirect to the proper page? Use the right template?
207 assert urlparse.urlsplit(response.location)[2] == '/auth/login/'
208 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
209
210 ## Make sure link to change password is sent by email
211 assert len(mail.EMAIL_TEST_INBOX) == 2
212 message = mail.EMAIL_TEST_INBOX.pop()
213 assert message['To'] == 'angrygrrl@example.org'
214 email_context = template.TEMPLATE_TEST_CONTEXT[
215 'mediagoblin/plugins/basic_auth/fp_verification_email.txt']
216 #TODO - change the name of verification_url to something forgot-password-ish
217 assert email_context['verification_url'].encode('ascii') in message.get_payload(decode=True)
218
219 path = urlparse.urlsplit(email_context['verification_url'])[2]
220 get_params = urlparse.urlsplit(email_context['verification_url'])[3]
221 parsed_get_params = urlparse.parse_qs(get_params)
222 assert path == u'/auth/forgot_password/verify/'
223
224 ## Try using a bs password-changing verification key, shouldn't work
225 template.clear_test_template_context()
226 response = test_app.get(
227 "/auth/forgot_password/verify/?token=total_bs")
228 response.follow()
229
230 # Correct redirect?
231 assert urlparse.urlsplit(response.location)[2] == '/'
232
233 ## Verify step 1 of password-change works -- can see form to change password
234 template.clear_test_template_context()
235 response = test_app.get("%s?%s" % (path, get_params))
236 assert 'mediagoblin/plugins/basic_auth/change_fp.html' in \
237 template.TEMPLATE_TEST_CONTEXT
238
239 ## Verify step 2.1 of password-change works -- report success to user
240 template.clear_test_template_context()
241 response = test_app.post(
242 '/auth/forgot_password/verify/', {
243 'password': 'iamveryveryangry',
244 'token': parsed_get_params['token']})
245 response.follow()
246 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
247
248 ## Verify step 2.2 of password-change works -- login w/ new password success
249 template.clear_test_template_context()
250 response = test_app.post(
251 '/auth/login/', {
252 'username': u'angrygirl',
253 'password': 'iamveryveryangry'})
254
255 # User should be redirected
256 response.follow()
257 assert urlparse.urlsplit(response.location)[2] == '/'
258 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
259
260 def test_authentication_views(test_app):
261 """
262 Test logging in and logging out
263 """
264 # Make a new user
265 test_user = fixture_add_user()
266
267
268 # Get login
269 # ---------
270 test_app.get('/auth/login/')
271 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
272
273 # Failed login - blank form
274 # -------------------------
275 template.clear_test_template_context()
276 response = test_app.post('/auth/login/')
277 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
278 form = context['login_form']
279 assert form.username.errors == [u'This field is required.']
280
281 # Failed login - blank user
282 # -------------------------
283 template.clear_test_template_context()
284 response = test_app.post(
285 '/auth/login/', {
286 'password': u'toast'})
287 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
288 form = context['login_form']
289 assert form.username.errors == [u'This field is required.']
290
291 # Failed login - blank password
292 # -----------------------------
293 template.clear_test_template_context()
294 response = test_app.post(
295 '/auth/login/', {
296 'username': u'chris'})
297 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
298
299 # Failed login - bad user
300 # -----------------------
301 template.clear_test_template_context()
302 response = test_app.post(
303 '/auth/login/', {
304 'username': u'steve',
305 'password': 'toast'})
306 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
307 assert context['login_failed']
308
309 # Failed login - bad password
310 # ---------------------------
311 template.clear_test_template_context()
312 response = test_app.post(
313 '/auth/login/', {
314 'username': u'chris',
315 'password': 'jam_and_ham'})
316 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
317 assert context['login_failed']
318
319 # Successful login
320 # ----------------
321 template.clear_test_template_context()
322 response = test_app.post(
323 '/auth/login/', {
324 'username': u'chris',
325 'password': 'toast'})
326
327 # User should be redirected
328 response.follow()
329 assert urlparse.urlsplit(response.location)[2] == '/'
330 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
331
332 # Make sure user is in the session
333 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html']
334 session = context['request'].session
335 assert session['user_id'] == six.text_type(test_user.id)
336
337 # Successful logout
338 # -----------------
339 template.clear_test_template_context()
340 response = test_app.get('/auth/logout/')
341
342 # Should be redirected to index page
343 response.follow()
344 assert urlparse.urlsplit(response.location)[2] == '/'
345 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
346
347 # Make sure the user is not in the session
348 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html']
349 session = context['request'].session
350 assert 'user_id' not in session
351
352 # User is redirected to custom URL if POST['next'] is set
353 # -------------------------------------------------------
354 template.clear_test_template_context()
355 response = test_app.post(
356 '/auth/login/', {
357 'username': u'chris',
358 'password': 'toast',
359 'next' : '/u/chris/'})
360 assert urlparse.urlsplit(response.location)[2] == '/u/chris/'
361
362 ## Verify that username is lowercased on login attempt
363 template.clear_test_template_context()
364 response = test_app.post(
365 '/auth/login/', {
366 'username': u'ANDREW',
367 'password': 'fuselage'})
368 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
369 form = context['login_form']
370
371 # Username should no longer be uppercased; it should be lowercased
372 assert not form.username.data == u'ANDREW'
373 assert form.username.data == u'andrew'
374
375 # Successful login with short user
376 # ----------------
377 short_user = fixture_add_user(username=u'me', password=u'sho')
378 template.clear_test_template_context()
379 response = test_app.post(
380 '/auth/login/', {
381 'username': u'me',
382 'password': 'sho'})
383
384 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
385 form = context['login_form']
386 # User should be redirected
387 print('errors are', form.username.errors)
388 response.follow()
389 assert urlparse.urlsplit(response.location)[2] == '/'
390 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
391
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'] == six.text_type(short_user.id)
396
397 # Successful login with long user
398 # ----------------
399 long_user = fixture_add_user(
400 username=u'realllylonguser@reallylongdomain.com.co', password=u'sho')
401 template.clear_test_template_context()
402 response = test_app.post(
403 '/auth/login/', {
404 'username': u'me',
405 'password': 'sho'})
406
407 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
408 form = context['login_form']
409 # User should be redirected
410 print('errors are', form.username.errors)
411 response.follow()
412 assert urlparse.urlsplit(response.location)[2] == '/'
413 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
414
415 # Make sure user is in the session
416 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html']
417 session = context['request'].session
418 assert session['user_id'] == six.text_type(short_user.id)
419
420 @pytest.fixture()
421 def authentication_disabled_app(request):
422 return get_app(
423 request,
424 mgoblin_config=pkg_resources.resource_filename(
425 'mediagoblin.tests.auth_configs',
426 'authentication_disabled_appconfig.ini'))
427
428
429 def test_authentication_disabled_app(authentication_disabled_app):
430 # app.auth should = false
431 assert mg_globals
432 assert mg_globals.app.auth is False
433
434 # Try to visit register page
435 template.clear_test_template_context()
436 response = authentication_disabled_app.get('/auth/register/')
437 response.follow()
438
439 # Correct redirect?
440 assert urlparse.urlsplit(response.location)[2] == '/'
441 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
442
443 # Try to vist login page
444 template.clear_test_template_context()
445 response = authentication_disabled_app.get('/auth/login/')
446 response.follow()
447
448 # Correct redirect?
449 assert urlparse.urlsplit(response.location)[2] == '/'
450 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
451
452 ## Test check_login_simple should return None
453 assert auth_tools.check_login_simple('test', 'simple') is None
454
455 # Try to visit the forgot password page
456 template.clear_test_template_context()
457 response = authentication_disabled_app.get('/auth/register/')
458 response.follow()
459
460 # Correct redirect?
461 assert urlparse.urlsplit(response.location)[2] == '/'
462 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT