no need for check_login with the new check_login_simple function
[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 import urlparse
17 import datetime
18 import pkg_resources
19 import pytest
20
21 from mediagoblin import mg_globals
22 from mediagoblin.db.models import User
23 from mediagoblin.tests.tools import get_app, fixture_add_user
24 from mediagoblin.tools import template, mail
25 from mediagoblin.auth.tools import AuthError
26 from mediagoblin.auth import tools as auth_tools
27 from mediagoblin import auth
28
29
30 def test_register_views(test_app):
31 """
32 Massive test function that all our registration-related views all work.
33 """
34 # Test doing a simple GET on the page
35 # -----------------------------------
36
37 test_app.get('/auth/register/')
38 # Make sure it rendered with the appropriate template
39 assert 'mediagoblin/auth/register.html' in template.TEMPLATE_TEST_CONTEXT
40
41 # Try to register without providing anything, should error
42 # --------------------------------------------------------
43
44 template.clear_test_template_context()
45 test_app.post(
46 '/auth/register/', {})
47 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
48 form = context['register_form']
49 assert form.username.errors == [u'This field is required.']
50 assert form.password.errors == [u'This field is required.']
51 assert form.email.errors == [u'This field is required.']
52
53 # Try to register with fields that are known to be invalid
54 # --------------------------------------------------------
55
56 ## too short
57 template.clear_test_template_context()
58 test_app.post(
59 '/auth/register/', {
60 'username': 'l',
61 'password': 'o',
62 'email': 'l'})
63 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
64 form = context['register_form']
65
66 assert form.username.errors == [u'Field must be between 3 and 30 characters long.']
67 assert form.password.errors == [u'Field must be between 5 and 1024 characters long.']
68
69 ## bad form
70 template.clear_test_template_context()
71 test_app.post(
72 '/auth/register/', {
73 'username': '@_@',
74 'email': 'lollerskates'})
75 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/register.html']
76 form = context['register_form']
77
78 assert form.username.errors == [u'This field does not take email addresses.']
79 assert form.email.errors == [u'This field requires an email address.']
80
81 ## At this point there should be no users in the database ;)
82 assert User.query.count() == 0
83
84 # Successful register
85 # -------------------
86 template.clear_test_template_context()
87 response = test_app.post(
88 '/auth/register/', {
89 'username': u'happygirl',
90 'password': 'iamsohappy',
91 'email': 'happygrrl@example.org'})
92 response.follow()
93
94 ## Did we redirect to the proper page? Use the right template?
95 assert urlparse.urlsplit(response.location)[2] == '/u/happygirl/'
96 assert 'mediagoblin/user_pages/user.html' in template.TEMPLATE_TEST_CONTEXT
97
98 ## Make sure user is in place
99 new_user = mg_globals.database.User.find_one(
100 {'username': u'happygirl'})
101 assert new_user
102 assert new_user.status == u'needs_email_verification'
103 assert new_user.email_verified == False
104
105 ## Make sure user is logged in
106 request = template.TEMPLATE_TEST_CONTEXT[
107 'mediagoblin/user_pages/user.html']['request']
108 assert request.session['user_id'] == unicode(new_user.id)
109
110 ## Make sure we get email confirmation, and try verifying
111 assert len(mail.EMAIL_TEST_INBOX) == 1
112 message = mail.EMAIL_TEST_INBOX.pop()
113 assert message['To'] == 'happygrrl@example.org'
114 email_context = template.TEMPLATE_TEST_CONTEXT[
115 'mediagoblin/auth/verification_email.txt']
116 assert email_context['verification_url'] in message.get_payload(decode=True)
117
118 path = urlparse.urlsplit(email_context['verification_url'])[2]
119 get_params = urlparse.urlsplit(email_context['verification_url'])[3]
120 assert path == u'/auth/verify_email/'
121 parsed_get_params = urlparse.parse_qs(get_params)
122
123 ### user should have these same parameters
124 assert parsed_get_params['userid'] == [
125 unicode(new_user.id)]
126 assert parsed_get_params['token'] == [
127 new_user.verification_key]
128
129 ## Try verifying with bs verification key, shouldn't work
130 template.clear_test_template_context()
131 response = test_app.get(
132 "/auth/verify_email/?userid=%s&token=total_bs" % unicode(
133 new_user.id))
134 response.follow()
135 context = template.TEMPLATE_TEST_CONTEXT[
136 'mediagoblin/user_pages/user.html']
137 # assert context['verification_successful'] == True
138 # TODO: Would be good to test messages here when we can do so...
139 new_user = mg_globals.database.User.find_one(
140 {'username': u'happygirl'})
141 assert new_user
142 assert new_user.status == u'needs_email_verification'
143 assert new_user.email_verified == False
144
145 ## Verify the email activation works
146 template.clear_test_template_context()
147 response = test_app.get("%s?%s" % (path, get_params))
148 response.follow()
149 context = template.TEMPLATE_TEST_CONTEXT[
150 'mediagoblin/user_pages/user.html']
151 # assert context['verification_successful'] == True
152 # TODO: Would be good to test messages here when we can do so...
153 new_user = mg_globals.database.User.find_one(
154 {'username': u'happygirl'})
155 assert new_user
156 assert new_user.status == u'active'
157 assert new_user.email_verified == True
158
159 # Uniqueness checks
160 # -----------------
161 ## We shouldn't be able to register with that user twice
162 template.clear_test_template_context()
163 response = test_app.post(
164 '/auth/register/', {
165 'username': u'happygirl',
166 'password': 'iamsohappy2',
167 'email': 'happygrrl2@example.org'})
168
169 context = template.TEMPLATE_TEST_CONTEXT[
170 'mediagoblin/auth/register.html']
171 form = context['register_form']
172 assert form.username.errors == [
173 u'Sorry, a user with that name already exists.']
174
175 ## TODO: Also check for double instances of an email address?
176
177 ### Oops, forgot the password
178 # -------------------
179 template.clear_test_template_context()
180 response = test_app.post(
181 '/auth/forgot_password/',
182 {'username': u'happygirl'})
183 response.follow()
184
185 ## Did we redirect to the proper page? Use the right template?
186 assert urlparse.urlsplit(response.location)[2] == '/auth/login/'
187 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
188
189 ## Make sure link to change password is sent by email
190 assert len(mail.EMAIL_TEST_INBOX) == 1
191 message = mail.EMAIL_TEST_INBOX.pop()
192 assert message['To'] == 'happygrrl@example.org'
193 email_context = template.TEMPLATE_TEST_CONTEXT[
194 'mediagoblin/auth/fp_verification_email.txt']
195 #TODO - change the name of verification_url to something forgot-password-ish
196 assert email_context['verification_url'] in message.get_payload(decode=True)
197
198 path = urlparse.urlsplit(email_context['verification_url'])[2]
199 get_params = urlparse.urlsplit(email_context['verification_url'])[3]
200 assert path == u'/auth/forgot_password/verify/'
201 parsed_get_params = urlparse.parse_qs(get_params)
202
203 # user should have matching parameters
204 new_user = mg_globals.database.User.find_one({'username': u'happygirl'})
205 assert parsed_get_params['userid'] == [unicode(new_user.id)]
206 assert parsed_get_params['token'] == [new_user.fp_verification_key]
207
208 ### The forgotten password token should be set to expire in ~ 10 days
209 # A few ticks have expired so there are only 9 full days left...
210 assert (new_user.fp_token_expire - datetime.datetime.now()).days == 9
211
212 ## Try using a bs password-changing verification key, shouldn't work
213 template.clear_test_template_context()
214 response = test_app.get(
215 "/auth/forgot_password/verify/?userid=%s&token=total_bs" % unicode(
216 new_user.id), status=404)
217 assert response.status.split()[0] == u'404' # status="404 NOT FOUND"
218
219 ## Try using an expired token to change password, shouldn't work
220 template.clear_test_template_context()
221 new_user = mg_globals.database.User.find_one({'username': u'happygirl'})
222 real_token_expiration = new_user.fp_token_expire
223 new_user.fp_token_expire = datetime.datetime.now()
224 new_user.save()
225 response = test_app.get("%s?%s" % (path, get_params), status=404)
226 assert response.status.split()[0] == u'404' # status="404 NOT FOUND"
227 new_user.fp_token_expire = real_token_expiration
228 new_user.save()
229
230 ## Verify step 1 of password-change works -- can see form to change password
231 template.clear_test_template_context()
232 response = test_app.get("%s?%s" % (path, get_params))
233 assert 'mediagoblin/auth/change_fp.html' in template.TEMPLATE_TEST_CONTEXT
234
235 ## Verify step 2.1 of password-change works -- report success to user
236 template.clear_test_template_context()
237 response = test_app.post(
238 '/auth/forgot_password/verify/', {
239 'userid': parsed_get_params['userid'],
240 'password': 'iamveryveryhappy',
241 'token': parsed_get_params['token']})
242 response.follow()
243 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
244
245 ## Verify step 2.2 of password-change works -- login w/ new password success
246 template.clear_test_template_context()
247 response = test_app.post(
248 '/auth/login/', {
249 'username': u'happygirl',
250 'password': 'iamveryveryhappy'})
251
252 # User should be redirected
253 response.follow()
254 assert urlparse.urlsplit(response.location)[2] == '/'
255 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
256
257
258 def test_authentication_views(test_app):
259 """
260 Test logging in and logging out
261 """
262 # Make a new user
263 test_user = fixture_add_user(active_user=False)
264
265 # Get login
266 # ---------
267 test_app.get('/auth/login/')
268 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
269
270 # Failed login - blank form
271 # -------------------------
272 template.clear_test_template_context()
273 response = test_app.post('/auth/login/')
274 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
275 form = context['login_form']
276 assert form.username.errors == [u'This field is required.']
277 assert form.password.errors == [u'This field is required.']
278
279 # Failed login - blank user
280 # -------------------------
281 template.clear_test_template_context()
282 response = test_app.post(
283 '/auth/login/', {
284 'password': u'toast'})
285 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
286 form = context['login_form']
287 assert form.username.errors == [u'This field is required.']
288
289 # Failed login - blank password
290 # -----------------------------
291 template.clear_test_template_context()
292 response = test_app.post(
293 '/auth/login/', {
294 'username': u'chris'})
295 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
296 form = context['login_form']
297 assert form.password.errors == [u'This field is required.']
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'] == unicode(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
363 # App with no_auth=false and no auth plugin enabled
364 def no_auth_false_no_auth_plugin_app(request):
365 return get_app(
366 request,
367 mgoblin_config=pkg_resources.resource_filename(
368 'mediagoblin.tests.auth_configs',
369 'no_auth_false_no_auth_plugin_appconfig.ini'))
370
371
372 def test_no_auth_false_no_auth_plugin_raises(request):
373 with pytest.raises(AuthError):
374 no_auth_false_no_auth_plugin_app(request)
375
376
377 @pytest.fixture()
378 def no_auth_true_no_auth_plugin_app(request):
379 return get_app(
380 request,
381 mgoblin_config=pkg_resources.resource_filename(
382 'mediagoblin.tests.auth_configs',
383 'no_auth_true_no_auth_plugin_appconfig.ini'))
384
385
386 def test_no_auth_true_no_auth_plugin_app(no_auth_true_no_auth_plugin_app):
387 # app.auth should = false
388 assert mg_globals.app.auth is False
389
390 # Try to visit register page
391 template.clear_test_template_context()
392 response = no_auth_true_no_auth_plugin_app.get('/auth/register/')
393 response.follow()
394
395 # Correct redirect?
396 assert urlparse.urlsplit(response.location)[2] == '/'
397 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
398
399 # Try to vist login page
400 template.clear_test_template_context()
401 response = no_auth_true_no_auth_plugin_app.get('/auth/login/')
402 response.follow()
403
404 # Correct redirect?
405 assert urlparse.urlsplit(response.location)[2] == '/'
406 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
407
408 ## Test check_login_simple should return None
409 assert auth_tools.check_login_simple('test', 'simple') is None
410
411 # Try to visit the forgot password page
412 template.clear_test_template_context()
413 response = no_auth_true_no_auth_plugin_app.get('/auth/register/')
414 response.follow()
415
416 # Correct redirect?
417 assert urlparse.urlsplit(response.location)[2] == '/'
418 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT