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