Merge remote-tracking branch 'refs/remotes/joar/notifications'
[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 ## Try verifying with bs verification key, shouldn't work
160 template.clear_test_template_context()
161 response = test_app.get(
162 "/auth/verify_email/?token=total_bs")
163 response.follow()
164
165 # Correct redirect?
166 assert urlparse.urlsplit(response.location)[2] == '/'
167
168 # assert context['verification_successful'] == True
169 # TODO: Would be good to test messages here when we can do so...
170 new_user = mg_globals.database.User.find_one(
171 {'username': u'happygirl'})
172 assert new_user
173 assert new_user.status == u'needs_email_verification'
174 assert new_user.email_verified == False
175
176 ## Verify the email activation works
177 template.clear_test_template_context()
178 response = test_app.get("%s?%s" % (path, get_params))
179 response.follow()
180 context = template.TEMPLATE_TEST_CONTEXT[
181 'mediagoblin/user_pages/user.html']
182 # assert context['verification_successful'] == True
183 # TODO: Would be good to test messages here when we can do so...
184 new_user = mg_globals.database.User.find_one(
185 {'username': u'happygirl'})
186 assert new_user
187 assert new_user.status == u'active'
188 assert new_user.email_verified == True
189
190 # Uniqueness checks
191 # -----------------
192 ## We shouldn't be able to register with that user twice
193 template.clear_test_template_context()
194 response = test_app.post(
195 '/auth/register/', {
196 'username': u'happygirl',
197 'password': 'iamsohappy2',
198 'email': 'happygrrl2@example.org'})
199
200 context = template.TEMPLATE_TEST_CONTEXT[
201 'mediagoblin/auth/register.html']
202 form = context['register_form']
203 assert form.username.errors == [
204 u'Sorry, a user with that name already exists.']
205
206 ## TODO: Also check for double instances of an email address?
207
208 ### Oops, forgot the password
209 # -------------------
210 template.clear_test_template_context()
211 response = test_app.post(
212 '/auth/forgot_password/',
213 {'username': u'happygirl'})
214 response.follow()
215
216 ## Did we redirect to the proper page? Use the right template?
217 assert urlparse.urlsplit(response.location)[2] == '/auth/login/'
218 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
219
220 ## Make sure link to change password is sent by email
221 assert len(mail.EMAIL_TEST_INBOX) == 1
222 message = mail.EMAIL_TEST_INBOX.pop()
223 assert message['To'] == 'happygrrl@example.org'
224 email_context = template.TEMPLATE_TEST_CONTEXT[
225 'mediagoblin/auth/fp_verification_email.txt']
226 #TODO - change the name of verification_url to something forgot-password-ish
227 assert email_context['verification_url'] in message.get_payload(decode=True)
228
229 path = urlparse.urlsplit(email_context['verification_url'])[2]
230 get_params = urlparse.urlsplit(email_context['verification_url'])[3]
231 parsed_get_params = urlparse.parse_qs(get_params)
232 assert path == u'/auth/forgot_password/verify/'
233
234 ## Try using a bs password-changing verification key, shouldn't work
235 template.clear_test_template_context()
236 response = test_app.get(
237 "/auth/forgot_password/verify/?token=total_bs")
238 response.follow()
239
240 # Correct redirect?
241 assert urlparse.urlsplit(response.location)[2] == '/'
242
243 ## Verify step 1 of password-change works -- can see form to change password
244 template.clear_test_template_context()
245 response = test_app.get("%s?%s" % (path, get_params))
246 assert 'mediagoblin/auth/change_fp.html' in template.TEMPLATE_TEST_CONTEXT
247
248 ## Verify step 2.1 of password-change works -- report success to user
249 template.clear_test_template_context()
250 response = test_app.post(
251 '/auth/forgot_password/verify/', {
252 'password': 'iamveryveryhappy',
253 'token': parsed_get_params['token']})
254 response.follow()
255 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
256
257 ## Verify step 2.2 of password-change works -- login w/ new password success
258 template.clear_test_template_context()
259 response = test_app.post(
260 '/auth/login/', {
261 'username': u'happygirl',
262 'password': 'iamveryveryhappy'})
263
264 # User should be redirected
265 response.follow()
266 assert urlparse.urlsplit(response.location)[2] == '/'
267 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
268
269
270 def test_authentication_views(test_app):
271 """
272 Test logging in and logging out
273 """
274 # Make a new user
275 test_user = fixture_add_user(active_user=False)
276
277 # Get login
278 # ---------
279 test_app.get('/auth/login/')
280 assert 'mediagoblin/auth/login.html' in template.TEMPLATE_TEST_CONTEXT
281
282 # Failed login - blank form
283 # -------------------------
284 template.clear_test_template_context()
285 response = test_app.post('/auth/login/')
286 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
287 form = context['login_form']
288 assert form.username.errors == [u'This field is required.']
289 assert form.password.errors == [u'This field is required.']
290
291 # Failed login - blank user
292 # -------------------------
293 template.clear_test_template_context()
294 response = test_app.post(
295 '/auth/login/', {
296 'password': u'toast'})
297 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
298 form = context['login_form']
299 assert form.username.errors == [u'This field is required.']
300
301 # Failed login - blank password
302 # -----------------------------
303 template.clear_test_template_context()
304 response = test_app.post(
305 '/auth/login/', {
306 'username': u'chris'})
307 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
308 form = context['login_form']
309 assert form.password.errors == [u'This field is required.']
310
311 # Failed login - bad user
312 # -----------------------
313 template.clear_test_template_context()
314 response = test_app.post(
315 '/auth/login/', {
316 'username': u'steve',
317 'password': 'toast'})
318 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
319 assert context['login_failed']
320
321 # Failed login - bad password
322 # ---------------------------
323 template.clear_test_template_context()
324 response = test_app.post(
325 '/auth/login/', {
326 'username': u'chris',
327 'password': 'jam_and_ham'})
328 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html']
329 assert context['login_failed']
330
331 # Successful login
332 # ----------------
333 template.clear_test_template_context()
334 response = test_app.post(
335 '/auth/login/', {
336 'username': u'chris',
337 'password': 'toast'})
338
339 # User should be redirected
340 response.follow()
341 assert urlparse.urlsplit(response.location)[2] == '/'
342 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
343
344 # Make sure user is in the session
345 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html']
346 session = context['request'].session
347 assert session['user_id'] == unicode(test_user.id)
348
349 # Successful logout
350 # -----------------
351 template.clear_test_template_context()
352 response = test_app.get('/auth/logout/')
353
354 # Should be redirected to index page
355 response.follow()
356 assert urlparse.urlsplit(response.location)[2] == '/'
357 assert 'mediagoblin/root.html' in template.TEMPLATE_TEST_CONTEXT
358
359 # Make sure the user is not in the session
360 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html']
361 session = context['request'].session
362 assert 'user_id' not in session
363
364 # User is redirected to custom URL if POST['next'] is set
365 # -------------------------------------------------------
366 template.clear_test_template_context()
367 response = test_app.post(
368 '/auth/login/', {
369 'username': u'chris',
370 'password': 'toast',
371 'next' : '/u/chris/'})
372 assert urlparse.urlsplit(response.location)[2] == '/u/chris/'