Files @ fdde16d7cea0
Branch filter:

Location: kallithea/kallithea/tests/functional/test_login.py - annotation

mads
celery: fix send_email to work with JSON encoding (Issue #363)

Long time ago, c935bcaf7086 introduced an optional User object parameter to the
send_email task and used the computed full_name_or_username property. Due to the
magic of pickle, that also worked when using Celery to run the task async.

Now, Celery 4 changed the default encoding from Pickle to JSON, which we
anticipated in e539db6cc0da. That broke send_email in some cases, for example
when a user comments on another user's changeset.

Fixed by passing the "From" name as string instead of passing the whole User
object.

Thanks to vyom for reporting.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
d1addaf7a91e
3d3bec370fa5
f629e9a0c376
7e9d3865b4f9
3d3bec370fa5
bbbfee57fb96
0a277465fddf
f629e9a0c376
bbbfee57fb96
0a277465fddf
0a277465fddf
d1addaf7a91e
0a277465fddf
d1addaf7a91e
a33d1337db05
d1addaf7a91e
f629e9a0c376
e527cc2ce8dc
0a277465fddf
d1addaf7a91e
9f8a1212177e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
be1d366f461c
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
e527cc2ce8dc
e527cc2ce8dc
09100b3b8f42
be1d366f461c
e527cc2ce8dc
81d8affd08f4
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
e527cc2ce8dc
e527cc2ce8dc
09100b3b8f42
d1addaf7a91e
be1d366f461c
e527cc2ce8dc
81d8affd08f4
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
b24e015a4174
e527cc2ce8dc
e527cc2ce8dc
e527cc2ce8dc
09100b3b8f42
b24e015a4174
be1d366f461c
e527cc2ce8dc
81d8affd08f4
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
e527cc2ce8dc
e527cc2ce8dc
09100b3b8f42
be1d366f461c
d1addaf7a91e
d1addaf7a91e
be1d366f461c
dacdea9fda2a
d1addaf7a91e
3d3bec370fa5
e527cc2ce8dc
e527cc2ce8dc
e527cc2ce8dc
9c2fc1390291
09100b3b8f42
3d3bec370fa5
be1d366f461c
3d3bec370fa5
be1d366f461c
3d3bec370fa5
3d3bec370fa5
e527cc2ce8dc
e527cc2ce8dc
e527cc2ce8dc
9c2fc1390291
09100b3b8f42
3d3bec370fa5
be1d366f461c
3d3bec370fa5
be1d366f461c
3d3bec370fa5
17281153a4c0
e527cc2ce8dc
e527cc2ce8dc
e527cc2ce8dc
09100b3b8f42
17281153a4c0
17281153a4c0
e527cc2ce8dc
17281153a4c0
be1d366f461c
17281153a4c0
17281153a4c0
17281153a4c0
17281153a4c0
e527cc2ce8dc
be1d366f461c
17281153a4c0
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
12b47803189f
12b47803189f
a0a9ae753cc4
38d1c99cd000
38d1c99cd000
38d1c99cd000
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
e527cc2ce8dc
e527cc2ce8dc
09100b3b8f42
a0a9ae753cc4
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
e527cc2ce8dc
9c2fc1390291
09100b3b8f42
be1d366f461c
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
9c2fc1390291
09100b3b8f42
d1addaf7a91e
b75f1d0753d6
d1addaf7a91e
fefd7279e798
e527cc2ce8dc
e527cc2ce8dc
9c2fc1390291
09100b3b8f42
fefd7279e798
fefd7279e798
fefd7279e798
4c5c59b96adc
4c5c59b96adc
e527cc2ce8dc
43ee4d4d68f2
e63bcce18fef
4c5c59b96adc
43ee4d4d68f2
4c5c59b96adc
e527cc2ce8dc
e527cc2ce8dc
4c5c59b96adc
be1d366f461c
7e9d3865b4f9
7e9d3865b4f9
7172f3b0042b
4c5c59b96adc
e527cc2ce8dc
4c5c59b96adc
e63bcce18fef
4c5c59b96adc
4c5c59b96adc
4c5c59b96adc
e527cc2ce8dc
e527cc2ce8dc
7e9d3865b4f9
4c5c59b96adc
be1d366f461c
4c5c59b96adc
e527cc2ce8dc
4c5c59b96adc
e63bcce18fef
4c5c59b96adc
4c5c59b96adc
4c5c59b96adc
e527cc2ce8dc
e527cc2ce8dc
e527cc2ce8dc
e527cc2ce8dc
09100b3b8f42
be1d366f461c
4c5c59b96adc
be1d366f461c
4c5c59b96adc
e527cc2ce8dc
4c5c59b96adc
e63bcce18fef
4c5c59b96adc
4c5c59b96adc
4c5c59b96adc
e527cc2ce8dc
e527cc2ce8dc
4c5c59b96adc
9c2fc1390291
09100b3b8f42
4c5c59b96adc
b75f1d0753d6
7e9d3865b4f9
4c5c59b96adc
be1d366f461c
4c5c59b96adc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
12b47803189f
d1addaf7a91e
9c2fc1390291
09100b3b8f42
d1addaf7a91e
9f8a1212177e
9f8a1212177e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
9c2fc1390291
09100b3b8f42
d1addaf7a91e
9f8a1212177e
9f8a1212177e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
9c2fc1390291
09100b3b8f42
9f8a1212177e
9f8a1212177e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
9c2fc1390291
09100b3b8f42
be1d366f461c
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
9c2fc1390291
09100b3b8f42
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
82ea8d67fc62
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
9c2fc1390291
09100b3b8f42
d1addaf7a91e
d1addaf7a91e
9f8a1212177e
9f8a1212177e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
9c2fc1390291
09100b3b8f42
d1addaf7a91e
9f8a1212177e
9f8a1212177e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
9c2fc1390291
09100b3b8f42
9f8a1212177e
9f8a1212177e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
12b47803189f
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
9c2fc1390291
09100b3b8f42
be1d366f461c
38e418408c58
d1addaf7a91e
d1addaf7a91e
be1d366f461c
be1d366f461c
be1d366f461c
be1d366f461c
be1d366f461c
48a00daba2f2
be1d366f461c
d1addaf7a91e
f629e9a0c376
f629e9a0c376
f629e9a0c376
f629e9a0c376
d1addaf7a91e
ab01e0a5d240
d1addaf7a91e
e527cc2ce8dc
9c2fc1390291
09100b3b8f42
d1addaf7a91e
ab01e0a5d240
d1addaf7a91e
d1addaf7a91e
e527cc2ce8dc
d1addaf7a91e
be1d366f461c
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
12b47803189f
e63bcce18fef
e63bcce18fef
f629e9a0c376
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
9a02f9ef28d7
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
fdde16d7cea0
bbbfee57fb96
bbbfee57fb96
cec84c4675ce
cec84c4675ce
8f468d08f463
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
d1addaf7a91e
f629e9a0c376
d1addaf7a91e
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
7e9d3865b4f9
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
d1addaf7a91e
d1addaf7a91e
f629e9a0c376
f629e9a0c376
bbbfee57fb96
d1addaf7a91e
e527cc2ce8dc
f629e9a0c376
f629e9a0c376
f629e9a0c376
f629e9a0c376
f629e9a0c376
bbbfee57fb96
09100b3b8f42
f629e9a0c376
be1d366f461c
f629e9a0c376
f629e9a0c376
f629e9a0c376
f629e9a0c376
bbbfee57fb96
be1d366f461c
f629e9a0c376
8f468d08f463
8b47181750a8
bbbfee57fb96
bbbfee57fb96
bbbfee57fb96
d1addaf7a91e
8b47181750a8
e527cc2ce8dc
f629e9a0c376
f629e9a0c376
f629e9a0c376
f629e9a0c376
f629e9a0c376
f629e9a0c376
09100b3b8f42
f629e9a0c376
be1d366f461c
f629e9a0c376
d1addaf7a91e
d1addaf7a91e
d1addaf7a91e
f629e9a0c376
f629e9a0c376
f629e9a0c376
f629e9a0c376
aa2542a6538b
aa2542a6538b
9cf90371d0f1
9cf90371d0f1
9cf90371d0f1
9cf90371d0f1
9cf90371d0f1
aa2542a6538b
aa2542a6538b
aa2542a6538b
aa2542a6538b
9cf90371d0f1
aa2542a6538b
aa2542a6538b
aa2542a6538b
aa2542a6538b
9cf90371d0f1
aa2542a6538b
e527cc2ce8dc
e527cc2ce8dc
aa2542a6538b
aa2542a6538b
e527cc2ce8dc
e527cc2ce8dc
9cf90371d0f1
9cf90371d0f1
9cf90371d0f1
e527cc2ce8dc
aa2542a6538b
aa2542a6538b
aa2542a6538b
06398585de03
06398585de03
aa2542a6538b
d1addaf7a91e
0e3e0864f210
0e3e0864f210
d1addaf7a91e
d1addaf7a91e
e63bcce18fef
0e3e0864f210
0e3e0864f210
d1addaf7a91e
d1addaf7a91e
e63bcce18fef
0e3e0864f210
0e3e0864f210
0e3e0864f210
0e3e0864f210
0e3e0864f210
# -*- coding: utf-8 -*-
import re
import time
import urllib.parse

import mock
from tg.util.webtest import test_context

import kallithea.lib.celerylib.tasks
from kallithea.lib import helpers as h
from kallithea.lib.auth import check_password
from kallithea.lib.utils2 import generate_api_key
from kallithea.model import validators
from kallithea.model.api_key import ApiKeyModel
from kallithea.model.db import User
from kallithea.model.meta import Session
from kallithea.model.user import UserModel
from kallithea.tests import base
from kallithea.tests.fixture import Fixture


fixture = Fixture()


class TestLoginController(base.TestController):

    def test_index(self):
        response = self.app.get(base.url(controller='login', action='index'))
        assert response.status == '200 OK'
        # Test response...

    def test_login_admin_ok(self):
        response = self.app.post(base.url(controller='login', action='index'),
                                 {'username': base.TEST_USER_ADMIN_LOGIN,
                                  'password': base.TEST_USER_ADMIN_PASS,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})
        assert response.status == '302 Found'
        self.assert_authenticated_user(response, base.TEST_USER_ADMIN_LOGIN)

        response = response.follow()
        response.mustcontain('/%s' % base.HG_REPO)

    def test_login_regular_ok(self):
        response = self.app.post(base.url(controller='login', action='index'),
                                 {'username': base.TEST_USER_REGULAR_LOGIN,
                                  'password': base.TEST_USER_REGULAR_PASS,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})

        assert response.status == '302 Found'
        self.assert_authenticated_user(response, base.TEST_USER_REGULAR_LOGIN)

        response = response.follow()
        response.mustcontain('/%s' % base.HG_REPO)

    def test_login_regular_email_ok(self):
        response = self.app.post(base.url(controller='login', action='index'),
                                 {'username': base.TEST_USER_REGULAR_EMAIL,
                                  'password': base.TEST_USER_REGULAR_PASS,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})

        assert response.status == '302 Found'
        self.assert_authenticated_user(response, base.TEST_USER_REGULAR_LOGIN)

        response = response.follow()
        response.mustcontain('/%s' % base.HG_REPO)

    def test_login_ok_came_from(self):
        test_came_from = '/_admin/users'
        response = self.app.post(base.url(controller='login', action='index',
                                     came_from=test_came_from),
                                 {'username': base.TEST_USER_ADMIN_LOGIN,
                                  'password': base.TEST_USER_ADMIN_PASS,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})
        assert response.status == '302 Found'
        response = response.follow()

        assert response.status == '200 OK'
        response.mustcontain('Users Administration')

    def test_login_do_not_remember(self):
        response = self.app.post(base.url(controller='login', action='index'),
                                 {'username': base.TEST_USER_REGULAR_LOGIN,
                                  'password': base.TEST_USER_REGULAR_PASS,
                                  'remember': False,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})

        assert 'Set-Cookie' in response.headers
        for cookie in response.headers.getall('Set-Cookie'):
            assert not re.search(r';\s+(Max-Age|Expires)=', cookie, re.IGNORECASE), 'Cookie %r has expiration date, but should be a session cookie' % cookie

    def test_login_remember(self):
        response = self.app.post(base.url(controller='login', action='index'),
                                 {'username': base.TEST_USER_REGULAR_LOGIN,
                                  'password': base.TEST_USER_REGULAR_PASS,
                                  'remember': True,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})

        assert 'Set-Cookie' in response.headers
        for cookie in response.headers.getall('Set-Cookie'):
            assert re.search(r';\s+(Max-Age|Expires)=', cookie, re.IGNORECASE), 'Cookie %r should have expiration date, but is a session cookie' % cookie

    def test_logout(self):
        response = self.app.post(base.url(controller='login', action='index'),
                                 {'username': base.TEST_USER_REGULAR_LOGIN,
                                  'password': base.TEST_USER_REGULAR_PASS,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})

        # Verify that a login session has been established.
        response = self.app.get(base.url(controller='login', action='index'))
        response = response.follow()
        assert 'authuser' in response.session

        response.click('Log Out')

        # Verify that the login session has been terminated.
        response = self.app.get(base.url(controller='login', action='index'))
        assert 'authuser' not in response.session

    @base.parametrize('url_came_from', [
          ('data:text/html,<script>window.alert("xss")</script>',),
          ('mailto:test@example.com',),
          ('file:///etc/passwd',),
          ('ftp://ftp.example.com',),
          ('http://other.example.com/bl%C3%A5b%C3%A6rgr%C3%B8d',),
          ('//evil.example.com/',),
          ('/\r\nX-Header-Injection: boo',),
          ('/invälid_url_bytes',),
          ('non-absolute-path',),
    ])
    def test_login_bad_came_froms(self, url_came_from):
        response = self.app.post(base.url(controller='login', action='index',
                                     came_from=url_came_from),
                                 {'username': base.TEST_USER_ADMIN_LOGIN,
                                  'password': base.TEST_USER_ADMIN_PASS,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()},
                                 status=400)

    def test_login_short_password(self):
        response = self.app.post(base.url(controller='login', action='index'),
                                 {'username': base.TEST_USER_ADMIN_LOGIN,
                                  'password': 'as',
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})
        assert response.status == '200 OK'

        response.mustcontain('Enter 3 characters or more')

    def test_login_wrong_username_password(self):
        response = self.app.post(base.url(controller='login', action='index'),
                                 {'username': 'error',
                                  'password': 'test12',
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})

        response.mustcontain('Invalid username or password')

    def test_login_non_ascii(self):
        response = self.app.post(base.url(controller='login', action='index'),
                                 {'username': base.TEST_USER_REGULAR_LOGIN,
                                  'password': 'blåbærgrød',
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})

        response.mustcontain('>Invalid username or password<')

    # verify that get arguments are correctly passed along login redirection

    @base.parametrize('args', [
        {'foo':'one', 'bar':'two'},
        {'blue': 'blå', 'green': 'grøn'},
    ])
    def test_redirection_to_login_form_preserves_get_args(self, args):
        with fixture.anon_access(False):
            response = self.app.get(base.url(controller='summary', action='index',
                                        repo_name=base.HG_REPO,
                                        **args))
            assert response.status == '302 Found'
            came_from = urllib.parse.parse_qs(urllib.parse.urlparse(response.location).query)['came_from'][0]
            came_from_qs = urllib.parse.parse_qsl(urllib.parse.urlparse(came_from).query)
            assert sorted(came_from_qs) == sorted(args.items())

    @base.parametrize('args,args_encoded', [
        ({'foo':'one', 'bar':'two'}, ('foo=one', 'bar=two')),
        ({'blue': 'blå', 'green':'grøn'},
             ('blue=bl%C3%A5', 'green=gr%C3%B8n')),
    ])
    def test_login_form_preserves_get_args(self, args, args_encoded):
        response = self.app.get(base.url(controller='login', action='index',
                                    came_from=base.url('/_admin/users', **args)))
        came_from = urllib.parse.parse_qs(urllib.parse.urlparse(response.form.action).query)['came_from'][0]
        for encoded in args_encoded:
            assert encoded in came_from

    @base.parametrize('args,args_encoded', [
        ({'foo':'one', 'bar':'two'}, ('foo=one', 'bar=two')),
        ({'blue': 'blå', 'green':'grøn'},
             ('blue=bl%C3%A5', 'green=gr%C3%B8n')),
    ])
    def test_redirection_after_successful_login_preserves_get_args(self, args, args_encoded):
        response = self.app.post(base.url(controller='login', action='index',
                                     came_from=base.url('/_admin/users', **args)),
                                 {'username': base.TEST_USER_ADMIN_LOGIN,
                                  'password': base.TEST_USER_ADMIN_PASS,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})
        assert response.status == '302 Found'
        for encoded in args_encoded:
            assert encoded in response.location

    @base.parametrize('args,args_encoded', [
        ({'foo':'one', 'bar':'two'}, ('foo=one', 'bar=two')),
        ({'blue': 'blå', 'green':'grøn'},
             ('blue=bl%C3%A5', 'green=gr%C3%B8n')),
    ])
    def test_login_form_after_incorrect_login_preserves_get_args(self, args, args_encoded):
        response = self.app.post(base.url(controller='login', action='index',
                                     came_from=base.url('/_admin/users', **args)),
                                 {'username': 'error',
                                  'password': 'test12',
                                  '_session_csrf_secret_token': self.session_csrf_secret_token()})

        response.mustcontain('Invalid username or password')
        came_from = urllib.parse.parse_qs(urllib.parse.urlparse(response.form.action).query)['came_from'][0]
        for encoded in args_encoded:
            assert encoded in came_from

    #==========================================================================
    # REGISTRATIONS
    #==========================================================================
    def test_register(self):
        response = self.app.get(base.url(controller='login', action='register'))
        response.mustcontain('Sign Up')

    def test_register_err_same_username(self):
        uname = base.TEST_USER_ADMIN_LOGIN
        response = self.app.post(base.url(controller='login', action='register'),
                                            {'username': uname,
                                             'password': 'test12',
                                             'password_confirmation': 'test12',
                                             'email': 'goodmail@example.com',
                                             'firstname': 'test',
                                             'lastname': 'test',
                                             '_session_csrf_secret_token': self.session_csrf_secret_token()})

        with test_context(self.app):
            msg = validators.ValidUsername()._messages['username_exists']
        msg = h.html_escape(msg % {'username': uname})
        response.mustcontain(msg)

    def test_register_err_same_email(self):
        response = self.app.post(base.url(controller='login', action='register'),
                                            {'username': 'test_admin_0',
                                             'password': 'test12',
                                             'password_confirmation': 'test12',
                                             'email': base.TEST_USER_ADMIN_EMAIL,
                                             'firstname': 'test',
                                             'lastname': 'test',
                                             '_session_csrf_secret_token': self.session_csrf_secret_token()})

        with test_context(self.app):
            msg = validators.UniqSystemEmail()()._messages['email_taken']
        response.mustcontain(msg)

    def test_register_err_same_email_case_sensitive(self):
        response = self.app.post(base.url(controller='login', action='register'),
                                            {'username': 'test_admin_1',
                                             'password': 'test12',
                                             'password_confirmation': 'test12',
                                             'email': base.TEST_USER_ADMIN_EMAIL.title(),
                                             'firstname': 'test',
                                             'lastname': 'test',
                                             '_session_csrf_secret_token': self.session_csrf_secret_token()})
        with test_context(self.app):
            msg = validators.UniqSystemEmail()()._messages['email_taken']
        response.mustcontain(msg)

    def test_register_err_wrong_data(self):
        response = self.app.post(base.url(controller='login', action='register'),
                                            {'username': 'xs',
                                             'password': 'test',
                                             'password_confirmation': 'test',
                                             'email': 'goodmailm',
                                             'firstname': 'test',
                                             'lastname': 'test',
                                             '_session_csrf_secret_token': self.session_csrf_secret_token()})
        assert response.status == '200 OK'
        response.mustcontain('An email address must contain a single @')
        response.mustcontain('Enter a value 6 characters long or more')

    def test_register_err_username(self):
        response = self.app.post(base.url(controller='login', action='register'),
                                            {'username': 'error user',
                                             'password': 'test12',
                                             'password_confirmation': 'test12',
                                             'email': 'goodmailm',
                                             'firstname': 'test',
                                             'lastname': 'test',
                                             '_session_csrf_secret_token': self.session_csrf_secret_token()})

        response.mustcontain('An email address must contain a single @')
        response.mustcontain('Username may only contain '
                'alphanumeric characters underscores, '
                'periods or dashes and must begin with an '
                'alphanumeric character')

    def test_register_err_case_sensitive(self):
        usr = base.TEST_USER_ADMIN_LOGIN.title()
        response = self.app.post(base.url(controller='login', action='register'),
                                            {'username': usr,
                                             'password': 'test12',
                                             'password_confirmation': 'test12',
                                             'email': 'goodmailm',
                                             'firstname': 'test',
                                             'lastname': 'test',
                                             '_session_csrf_secret_token': self.session_csrf_secret_token()})

        response.mustcontain('An email address must contain a single @')
        with test_context(self.app):
            msg = validators.ValidUsername()._messages['username_exists']
        msg = h.html_escape(msg % {'username': usr})
        response.mustcontain(msg)

    def test_register_special_chars(self):
        response = self.app.post(base.url(controller='login', action='register'),
                                        {'username': 'xxxaxn',
                                         'password': 'ąćźżąśśśś',
                                         'password_confirmation': 'ąćźżąśśśś',
                                         'email': 'goodmailm@test.plx',
                                         'firstname': 'test',
                                         'lastname': 'test',
                                         '_session_csrf_secret_token': self.session_csrf_secret_token()})

        with test_context(self.app):
            msg = validators.ValidPassword()._messages['invalid_password']
        response.mustcontain(msg)

    def test_register_password_mismatch(self):
        response = self.app.post(base.url(controller='login', action='register'),
                                            {'username': 'xs',
                                             'password': '123qwe',
                                             'password_confirmation': 'qwe123',
                                             'email': 'goodmailm@test.plxa',
                                             'firstname': 'test',
                                             'lastname': 'test',
                                             '_session_csrf_secret_token': self.session_csrf_secret_token()})
        with test_context(self.app):
            msg = validators.ValidPasswordsMatch('password', 'password_confirmation')._messages['password_mismatch']
        response.mustcontain(msg)

    def test_register_ok(self):
        username = 'test_regular4'
        password = 'qweqwe'
        email = 'user4@example.com'
        name = 'testname'
        lastname = 'testlastname'

        response = self.app.post(base.url(controller='login', action='register'),
                                            {'username': username,
                                             'password': password,
                                             'password_confirmation': password,
                                             'email': email,
                                             'firstname': name,
                                             'lastname': lastname,
                                             'admin': True,
                                             '_session_csrf_secret_token': self.session_csrf_secret_token()})  # This should be overridden
        assert response.status == '302 Found'
        self.checkSessionFlash(response, 'You have successfully registered with Kallithea')

        ret = Session().query(User).filter(User.username == 'test_regular4').one()
        assert ret.username == username
        assert check_password(password, ret.password) == True
        assert ret.email == email
        assert ret.name == name
        assert ret.lastname == lastname
        assert ret.api_key is not None
        assert ret.admin == False

    #==========================================================================
    # PASSWORD RESET
    #==========================================================================

    def test_forgot_password_wrong_mail(self):
        bad_email = 'username%wrongmail.org'
        response = self.app.post(
                        base.url(controller='login', action='password_reset'),
                            {'email': bad_email,
                             '_session_csrf_secret_token': self.session_csrf_secret_token()})

        response.mustcontain('An email address must contain a single @')

    def test_forgot_password(self):
        response = self.app.get(base.url(controller='login',
                                    action='password_reset'))
        assert response.status == '200 OK'

        username = 'test_password_reset_1'
        password = 'qweqwe'
        email = 'username@example.com'
        name = 'passwd'
        lastname = 'reset'
        timestamp = int(time.time())

        new = User()
        new.username = username
        new.password = password
        new.email = email
        new.name = name
        new.lastname = lastname
        new.api_key = generate_api_key()
        Session().add(new)
        Session().commit()

        token = UserModel().get_reset_password_token(
            User.get_by_username(username), timestamp, self.session_csrf_secret_token())

        collected = []
        def mock_send_email(recipients, subject, body='', html_body='', headers=None, from_name=None):
            collected.append((recipients, subject, body, html_body))

        with mock.patch.object(kallithea.lib.celerylib.tasks, 'send_email', mock_send_email), \
                mock.patch.object(time, 'time', lambda: timestamp):
            response = self.app.post(base.url(controller='login',
                                         action='password_reset'),
                                     {'email': email,
                                      '_session_csrf_secret_token': self.session_csrf_secret_token()})

        self.checkSessionFlash(response, 'A password reset confirmation code has been sent')

        ((recipients, subject, body, html_body),) = collected
        assert recipients == ['username@example.com']
        assert subject == 'Password reset link'
        assert '\n%s\n' % token in body
        (confirmation_url,) = (line for line in body.splitlines() if line.startswith('http://'))
        assert ' href="%s"' % confirmation_url.replace('&', '&amp;').replace('@', '%40') in html_body

        d = urllib.parse.parse_qs(urllib.parse.urlparse(confirmation_url).query)
        assert d['token'] == [token]
        assert d['timestamp'] == [str(timestamp)]
        assert d['email'] == [email]

        response = response.follow()

        # BAD TOKEN

        bad_token = "bad"

        response = self.app.post(base.url(controller='login',
                                     action='password_reset_confirmation'),
                                 {'email': email,
                                  'timestamp': timestamp,
                                  'password': "p@ssw0rd",
                                  'password_confirm': "p@ssw0rd",
                                  'token': bad_token,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token(),
                                 })
        assert response.status == '200 OK'
        response.mustcontain('Invalid password reset token')

        # GOOD TOKEN

        response = self.app.get(confirmation_url)
        assert response.status == '200 OK'
        response.mustcontain("You are about to set a new password for the email address %s" % email)
        response.mustcontain('<form action="%s" method="post">' % base.url(controller='login', action='password_reset_confirmation'))
        response.mustcontain('value="%s"' % self.session_csrf_secret_token())
        response.mustcontain('value="%s"' % token)
        response.mustcontain('value="%s"' % timestamp)
        response.mustcontain('value="username@example.com"')

        # fake a submit of that form
        response = self.app.post(base.url(controller='login',
                                     action='password_reset_confirmation'),
                                 {'email': email,
                                  'timestamp': timestamp,
                                  'password': "p@ssw0rd",
                                  'password_confirm': "p@ssw0rd",
                                  'token': token,
                                  '_session_csrf_secret_token': self.session_csrf_secret_token(),
                                 })
        assert response.status == '302 Found'
        self.checkSessionFlash(response, 'Successfully updated password')

        response = response.follow()

    #==========================================================================
    # API
    #==========================================================================

    def _api_key_test(self, api_key, status):
        """Verifies HTTP status code for accessing an auth-requiring page,
        using the given api_key URL parameter as well as using the API key
        with bearer authentication.

        If api_key is None, no api_key is passed at all. If api_key is True,
        a real, working API key is used.
        """
        with fixture.anon_access(False):
            if api_key is None:
                params = {}
                headers = {}
            else:
                if api_key is True:
                    api_key = User.get_first_admin().api_key
                params = {'api_key': api_key}
                headers = {'Authorization': 'Bearer ' + str(api_key)}

            self.app.get(base.url(controller='changeset', action='changeset_raw',
                             repo_name=base.HG_REPO, revision='tip', **params),
                         status=status)

            self.app.get(base.url(controller='changeset', action='changeset_raw',
                             repo_name=base.HG_REPO, revision='tip'),
                         headers=headers,
                         status=status)

    @base.parametrize('test_name,api_key,code', [
        ('none', None, 302),
        ('empty_string', '', 403),
        ('fake_number', '123456', 403),
        ('fake_not_alnum', 'a-z', 403),
        ('fake_api_key', '0123456789abcdef0123456789ABCDEF01234567', 403),
        ('proper_api_key', True, 200)
    ])
    def test_access_page_via_api_key(self, test_name, api_key, code):
        self._api_key_test(api_key, code)

    def test_access_page_via_extra_api_key(self):
        new_api_key = ApiKeyModel().create(base.TEST_USER_ADMIN_LOGIN, 'test')
        Session().commit()
        self._api_key_test(new_api_key.api_key, status=200)

    def test_access_page_via_expired_api_key(self):
        new_api_key = ApiKeyModel().create(base.TEST_USER_ADMIN_LOGIN, 'test')
        Session().commit()
        # patch the API key and make it expired
        new_api_key.expires = 0
        Session().commit()
        self._api_key_test(new_api_key.api_key, status=403)