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