tests.py 57.3 KB
Newer Older
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
# Copyright 2011 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.
33
from contextlib import contextmanager
34

35
import copy
36
import datetime
37
38
import functools

39
from snf_django.utils.testing import with_settings, override_settings
40
41
42

from django.test import TestCase, Client
from django.core import mail
43
44
from django.http import SimpleCookie, HttpRequest, QueryDict
from django.utils.importlib import import_module
45

46
from astakos.im.activation_backends import *
47
48
49
50
from astakos.im.target.shibboleth import Tokens as ShibbolethTokens
from astakos.im.models import *
from astakos.im import functions
from astakos.im import settings as astakos_settings
51
from astakos.im import forms
52
53

from urllib import quote
54
from datetime import timedelta
55

56
from astakos.im import messages
57
from astakos.im import auth_providers
58
59
from astakos.im import quotas

60
from django.conf import settings
61

62

63
# set some common settings
64
astakos_settings.EMAILCHANGE_ENABLED = True
65
66
67
astakos_settings.RECAPTCHA_ENABLED = False

settings.LOGGING_SETUP['disable_existing_loggers'] = False
68

69
70
71
72
73
74
# shortcut decorators to override provider settings
# e.g. shibboleth_settings(ENABLED=True) will set
# ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_ENABLED = True in global synnefo settings
prefixes = {'providers': 'AUTH_PROVIDER_',
            'shibboleth': 'ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_',
            'local': 'ASTAKOS_AUTH_PROVIDER_LOCAL_'}
75
im_settings = functools.partial(with_settings, astakos_settings)
76
shibboleth_settings = functools.partial(with_settings,
77
                                        settings,
78
                                        prefix=prefixes['shibboleth'])
79
localauth_settings = functools.partial(with_settings, settings,
80
81
                                       prefix=prefixes['local'])

82

83
84
85
class AstakosTestClient(Client):
    pass

86

87
class ShibbolethClient(AstakosTestClient):
88
89
90
    """
    A shibboleth agnostic client.
    """
91
92
    VALID_TOKENS = filter(lambda x: not x.startswith("_"),
                          dir(ShibbolethTokens))
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

    def __init__(self, *args, **kwargs):
        self.tokens = kwargs.pop('tokens', {})
        super(ShibbolethClient, self).__init__(*args, **kwargs)

    def set_tokens(self, **kwargs):
        for key, value in kwargs.iteritems():
            key = 'SHIB_%s' % key.upper()
            if not key in self.VALID_TOKENS:
                raise Exception('Invalid shibboleth token')

            self.tokens[key] = value

    def unset_tokens(self, *keys):
        for key in keys:
            key = 'SHIB_%s' % param.upper()
            if key in self.tokens:
                del self.tokens[key]

    def reset_tokens(self):
        self.tokens = {}

    def get_http_token(self, key):
        http_header = getattr(ShibbolethTokens, key)
        return http_header

    def request(self, **request):
        """
        Transform valid shibboleth tokens to http headers
        """
        for token, value in self.tokens.iteritems():
            request[self.get_http_token(token)] = value

        for param in request.keys():
            key = 'SHIB_%s' % param.upper()
            if key in self.VALID_TOKENS:
                request[self.get_http_token(key)] = request[param]
                del request[param]

        return super(ShibbolethClient, self).request(**request)


135
136
137
138
139
140
def get_user_client(username, password="password"):
    client = Client()
    client.login(username=username, password=password)
    return client


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
def get_local_user(username, **kwargs):
        try:
            return AstakosUser.objects.get(email=username)
        except:
            user_params = {
                'username': username,
                'email': username,
                'is_active': True,
                'activation_sent': datetime.now(),
                'email_verified': True,
                'provider': 'local'
            }
            user_params.update(kwargs)
            user = AstakosUser(**user_params)
            user.set_password(kwargs.get('password', 'password'))
            user.save()
            user.add_auth_provider('local', auth_backend='astakos')
            if kwargs.get('is_active', True):
                user.is_active = True
            else:
                user.is_active = False
            user.save()
            return user


def get_mailbox(email):
    mails = []
    for sent_email in mail.outbox:
        for recipient in sent_email.recipients():
            if email in recipient:
                mails.append(sent_email)
    return mails


class ShibbolethTests(TestCase):
    """
    Testing shibboleth authentication.
    """

    fixtures = ['groups']

    def setUp(self):
        self.client = ShibbolethClient()
184
185
        astakos_settings.IM_MODULES = ['local', 'shibboleth']
        astakos_settings.MODERATION_ENABLED = True
186

187
    @im_settings(FORCE_PROFILE_UPDATE=False)
188
    def test_create_account(self):
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
189

190
191
192
193
194
        client = ShibbolethClient()

        # shibboleth views validation
        # eepn required
        r = client.get('/im/login/shibboleth?', follow=True)
195
196
        self.assertContains(r, messages.SHIBBOLETH_MISSING_EPPN % {
            'domain': astakos_settings.BASEURL,
197
            'contact_email': settings.CONTACT_EMAIL
198
        })
199
        client.set_tokens(eppn="kpapeppn")
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
200

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
201
        astakos_settings.SHIBBOLETH_REQUIRE_NAME_INFO = True
202
203
        # shibboleth user info required
        r = client.get('/im/login/shibboleth?', follow=True)
204
        self.assertContains(r, messages.SHIBBOLETH_MISSING_NAME)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
205
        astakos_settings.SHIBBOLETH_REQUIRE_NAME_INFO = False
206
207

        # shibboleth logged us in
208
209
        client.set_tokens(mail="kpap@grnet.gr", eppn="kpapeppn",
                          cn="Kostas Papadimitriou",
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
210
                          ep_affiliation="Test Affiliation")
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
211
        r = client.get('/im/login/shibboleth?', follow=True)
212
213
        token = PendingThirdPartyUser.objects.get().token
        self.assertRedirects(r, '/im/signup?third_party_token=%s' % token)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
214
        self.assertEqual(r.status_code, 200)
215
216
217
218
219

        # a new pending user created
        pending_user = PendingThirdPartyUser.objects.get(
            third_party_identifier="kpapeppn")
        self.assertEqual(PendingThirdPartyUser.objects.count(), 1)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
220
        # keep the token for future use
221
222
223
224
        token = pending_user.token
        # from now on no shibboleth headers are sent to the server
        client.reset_tokens()

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
225
        # this is the old way, it should fail, to avoid pending user take over
226
227
228
        r = client.get('/im/shibboleth/signup/%s' % pending_user.username)
        self.assertEqual(r.status_code, 404)

229
230
        # this is the signup unique url associated with the pending user
        # created
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
231
        r = client.get('/im/signup/?third_party_token=%s' % token)
232
233
        identifier = pending_user.third_party_identifier
        post_data = {'third_party_identifier': identifier,
234
235
236
                     'first_name': 'Kostas',
                     'third_party_token': token,
                     'last_name': 'Mitroglou',
237
                     'provider': 'shibboleth'}
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
238

239
240
        signup_url = reverse('signup')

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
241
242
        # invlid email
        post_data['email'] = 'kpap'
243
        r = client.post(signup_url, post_data)
244
        self.assertContains(r, token)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
245
246
247
248

        # existing email
        existing_user = get_local_user('test@test.com')
        post_data['email'] = 'test@test.com'
249
        r = client.post(signup_url, post_data)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
250
251
252
253
        self.assertContains(r, messages.EMAIL_USED)
        existing_user.delete()

        # and finally a valid signup
254
        post_data['email'] = 'kpap@grnet.gr'
255
        r = client.post(signup_url, post_data, follow=True)
256
        self.assertContains(r, messages.NOTIFICATION_SENT)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
257
258

        # everything is ok in our db
259
260
        self.assertEqual(AstakosUser.objects.count(), 1)
        self.assertEqual(AstakosUserAuthProvider.objects.count(), 1)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
261
        self.assertEqual(PendingThirdPartyUser.objects.count(), 0)
262

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
263
264
265
266
        # provider info stored
        provider = AstakosUserAuthProvider.objects.get(module="shibboleth")
        self.assertEqual(provider.affiliation, 'Test Affiliation')
        self.assertEqual(provider.info, {u'email': u'kpap@grnet.gr',
267
268
                                         u'eppn': u'kpapeppn',
                                         u'name': u'Kostas Papadimitriou'})
269

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
270
        # lets login (not activated yet)
271
272
        client.set_tokens(mail="kpap@grnet.gr", eppn="kpapeppn",
                          cn="Kostas Papadimitriou", )
273
        r = client.get("/im/login/shibboleth?", follow=True)
274
        self.assertContains(r, 'is pending moderation')
275

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
276
277
        # admin activates our user
        u = AstakosUser.objects.get(username="kpap@grnet.gr")
278
279
280
        functions.activate(u)
        self.assertEqual(u.is_active, True)

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
281
282
        # we see our profile
        r = client.get("/im/login/shibboleth?", follow=True)
283
        self.assertRedirects(r, '/im/landing')
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
284
        self.assertEqual(r.status_code, 200)
285
286

    def test_existing(self):
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
287
288
289
290
291
        """
        Test adding of third party login to an existing account
        """

        # this is our existing user
292
        existing_user = get_local_user('kpap@grnet.gr')
293
294
295
296
297
298
299
300
301
302
        existing_inactive = get_local_user('kpap-inactive@grnet.gr')
        existing_inactive.is_active = False
        existing_inactive.save()

        existing_unverified = get_local_user('kpap-unverified@grnet.gr')
        existing_unverified.is_active = False
        existing_unverified.activation_sent = None
        existing_unverified.email_verified = False
        existing_unverified.is_verified = False
        existing_unverified.save()
303
304
305

        client = ShibbolethClient()
        # shibboleth logged us in, notice that we use different email
306
307
        client.set_tokens(mail="kpap@shibboleth.gr", eppn="kpapeppn",
                          cn="Kostas Papadimitriou", )
308
        r = client.get("/im/login/shibboleth?", follow=True)
309
310
311

        # a new pending user created
        pending_user = PendingThirdPartyUser.objects.get()
312
        token = pending_user.token
313
314
315
        self.assertEqual(PendingThirdPartyUser.objects.count(), 1)
        pending_key = pending_user.token
        client.reset_tokens()
316
        self.assertRedirects(r, "/im/signup?third_party_token=%s" % token)
317

318
319
320
321
322
323
        form = r.context['form']
        signupdata = copy.copy(form.initial)
        signupdata['email'] = 'kpap@grnet.gr'
        signupdata['third_party_token'] = token
        signupdata['provider'] = 'shibboleth'
        del signupdata['id']
324

325
326
327
328
329
330
331
332
333
334
335
        # the email exists to another user
        r = client.post("/im/signup", signupdata)
        self.assertContains(r, "There is already an account with this email "
                               "address")
        # change the case, still cannot create
        signupdata['email'] = 'KPAP@grnet.GR'
        r = client.post("/im/signup", signupdata)
        self.assertContains(r, "There is already an account with this email "
                               "address")
        # inactive user
        signupdata['email'] = 'KPAP-inactive@grnet.GR'
336
337
338
        r = client.post("/im/signup", signupdata)
        self.assertContains(r, "There is already an account with this email "
                               "address")
339

340
341
342
343
        # unverified user, this should pass, old entry will be deleted
        signupdata['email'] = 'KAPAP-unverified@grnet.GR'
        r = client.post("/im/signup", signupdata)

344
        post_data = {'password': 'password',
345
346
347
348
349
350
351
352
353
354
355
356
357
                     'username': 'kpap@grnet.gr'}
        r = client.post('/im/local', post_data, follow=True)
        self.assertTrue(r.context['request'].user.is_authenticated())
        client.set_tokens(mail="kpap@shibboleth.gr", eppn="kpapeppn",
                          cn="Kostas Papadimitriou", )
        r = client.get("/im/login/shibboleth?", follow=True)
        self.assertContains(r, "enabled for this account")
        client.reset_tokens()

        user = existing_user
        self.assertTrue(user.has_auth_provider('shibboleth'))
        self.assertTrue(user.has_auth_provider('local',
                                               auth_backend='astakos'))
358
359
360
        client.logout()

        # look Ma, i can login with both my shibboleth and local account
361
362
        client.set_tokens(mail="kpap@shibboleth.gr", eppn="kpapeppn",
                          cn="Kostas Papadimitriou")
363
364
365
        r = client.get("/im/login/shibboleth?", follow=True)
        self.assertTrue(r.context['request'].user.is_authenticated())
        self.assertTrue(r.context['request'].user.email == "kpap@grnet.gr")
366
        self.assertRedirects(r, '/im/landing')
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
367
        self.assertEqual(r.status_code, 200)
368
369
        client.logout()
        client.reset_tokens()
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
370
371

        # logged out
372
373
374
        r = client.get("/im/profile", follow=True)
        self.assertFalse(r.context['request'].user.is_authenticated())

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
375
        # login with local account also works
376
377
378
379
        post_data = {'password': 'password',
                     'username': 'kpap@grnet.gr'}
        r = self.client.post('/im/local', post_data, follow=True)
        self.assertTrue(r.context['request'].user.is_authenticated())
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
380
        self.assertTrue(r.context['request'].user.email == "kpap@grnet.gr")
381
        self.assertRedirects(r, '/im/landing')
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
382
        self.assertEqual(r.status_code, 200)
383

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
384
        # cannot add the same eppn
385
386
        client.set_tokens(mail="secondary@shibboleth.gr", eppn="kpapeppn",
                          cn="Kostas Papadimitriou", )
387
        r = client.get("/im/login/shibboleth?", follow=True)
388
        self.assertRedirects(r, '/im/landing')
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
389
390
        self.assertTrue(r.status_code, 200)
        self.assertEquals(existing_user.auth_providers.count(), 2)
391

392
        # only one allowed by default
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
393
        client.set_tokens(mail="secondary@shibboleth.gr", eppn="kpapeppn2",
394
                          cn="Kostas Papadimitriou", ep_affiliation="affil2")
395
        prov = auth_providers.get_provider('shibboleth')
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
396
        r = client.get("/im/login/shibboleth?", follow=True)
397
        self.assertContains(r, "Failed to add")
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
398
399
        self.assertRedirects(r, '/im/profile')
        self.assertTrue(r.status_code, 200)
400
        self.assertEquals(existing_user.auth_providers.count(), 2)
401
        client.logout()
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
402
403
404
        client.reset_tokens()

        # cannot login with another eppn
405
406
        client.set_tokens(mail="kpap@grnet.gr", eppn="kpapeppninvalid",
                          cn="Kostas Papadimitriou")
407
408
409
        r = client.get("/im/login/shibboleth?", follow=True)
        self.assertFalse(r.context['request'].user.is_authenticated())

410
411
        # cannot

412
413
414
        # lets remove local password
        user = AstakosUser.objects.get(username="kpap@grnet.gr",
                                       email="kpap@grnet.gr")
415
416
417
        remove_local_url = user.get_auth_provider('local').get_remove_url
        remove_shibbo_url = user.get_auth_provider('shibboleth',
                                                   'kpapeppn').get_remove_url
418
419
        client.set_tokens(mail="kpap@shibboleth.gr", eppn="kpapeppn",
                          cn="Kostas Papadimtriou")
420
421
        r = client.get("/im/login/shibboleth?", follow=True)
        client.reset_tokens()
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
422
423
424
425

        # TODO: this view should use POST
        r = client.get(remove_local_url)
        # 2 providers left
426
        self.assertEqual(user.auth_providers.count(), 1)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
427
428
        # cannot remove last provider
        r = client.get(remove_shibbo_url)
429
430
        self.assertEqual(r.status_code, 403)
        self.client.logout()
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
431
432

        # cannot login using local credentials (notice we use another client)
433
434
435
436
437
        post_data = {'password': 'password',
                     'username': 'kpap@grnet.gr'}
        r = self.client.post('/im/local', post_data, follow=True)
        self.assertFalse(r.context['request'].user.is_authenticated())

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
438
        # we can reenable the local provider by setting a password
439
        r = client.get("/im/password_change", follow=True)
440
        r = client.post("/im/password_change", {'new_password1': '111',
441
442
443
444
445
446
447
448
                                                'new_password2': '111'},
                        follow=True)
        user = r.context['request'].user
        self.assertTrue(user.has_auth_provider('local'))
        self.assertTrue(user.has_auth_provider('shibboleth'))
        self.assertTrue(user.check_password('111'))
        self.assertTrue(user.has_usable_password())
        self.client.logout()
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
449
450

        # now we can login
451
452
453
454
455
        post_data = {'password': '111',
                     'username': 'kpap@grnet.gr'}
        r = self.client.post('/im/local', post_data, follow=True)
        self.assertTrue(r.context['request'].user.is_authenticated())

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
456
        client.reset_tokens()
457

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
458
        # we cannot take over another shibboleth identifier
459
460
        user2 = get_local_user('another@grnet.gr')
        user2.add_auth_provider('shibboleth', identifier='existingeppn')
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
461
        # login
462
463
        client.set_tokens(mail="kpap@shibboleth.gr", eppn="kpapeppn",
                          cn="Kostas Papadimitriou")
464
        r = client.get("/im/login/shibboleth?", follow=True)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
465
        # try to assign existing shibboleth identifier of another user
466
467
        client.set_tokens(mail="kpap_second@shibboleth.gr",
                          eppn="existingeppn", cn="Kostas Papadimitriou")
468
        r = client.get("/im/login/shibboleth?", follow=True)
469
        self.assertContains(r, "this account is already assigned")
470

471

472
class TestLocal(TestCase):
473
474
475

    fixtures = ['groups']

476
477
478
    def setUp(self):
        settings.ADMINS = (('admin', 'support@cloud.grnet.gr'),)
        settings.SERVER_EMAIL = 'no-reply@grnet.gr'
479
480
481
482
483
        self._orig_moderation = astakos_settings.MODERATION_ENABLED
        settings.ASTAKOS_MODERATION_ENABLED = True

    def tearDown(self):
        settings.ASTAKOS_MODERATION_ENABLED = self._orig_moderation
484

485
    def test_no_moderation(self):
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
486
        # disable moderation
487
        astakos_settings.MODERATION_ENABLED = False
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
488
489

        # create a new user
490
491
        r = self.client.get("/im/signup")
        self.assertEqual(r.status_code, 200)
492
493
        data = {'email': 'kpap@grnet.gr', 'password1': 'password',
                'password2': 'password', 'first_name': 'Kostas',
494
495
                'last_name': 'Mitroglou', 'provider': 'local'}
        r = self.client.post("/im/signup", data)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
496
497

        # user created
498
499
500
501
502
503
504
        self.assertEqual(AstakosUser.objects.count(), 1)
        user = AstakosUser.objects.get(username="kpap@grnet.gr",
                                       email="kpap@grnet.gr")
        self.assertEqual(user.username, 'kpap@grnet.gr')
        self.assertEqual(user.has_auth_provider('local'), True)
        self.assertFalse(user.is_active)

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
505
        # user (but not admin) gets notified
506
507
508
        self.assertEqual(len(get_mailbox('support@cloud.grnet.gr')), 0)
        self.assertEqual(len(get_mailbox('kpap@grnet.gr')), 1)
        astakos_settings.MODERATION_ENABLED = True
509

510
511
    def test_email_case(self):
        data = {
512
513
514
            'email': 'kPap@grnet.gr',
            'password1': '1234',
            'password2': '1234'
515
516
517
518
519
520
521
        }

        form = forms.LocalUserCreationForm(data)
        self.assertTrue(form.is_valid())
        user = form.save()
        form.store_user(user, {})

522
        u = AstakosUser.objects.get()
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
        self.assertEqual(u.email, 'kPap@grnet.gr')
        self.assertEqual(u.username, 'kpap@grnet.gr')
        u.is_active = True
        u.email_verified = True
        u.save()

        data = {'username': 'kpap@grnet.gr', 'password': '1234'}
        login = forms.LoginForm(data=data)
        self.assertTrue(login.is_valid())

        data = {'username': 'KpaP@grnet.gr', 'password': '1234'}
        login = forms.LoginForm(data=data)
        self.assertTrue(login.is_valid())

        data = {
538
539
540
            'email': 'kpap@grnet.gr',
            'password1': '1234',
            'password2': '1234'
541
542
543
544
        }
        form = forms.LocalUserCreationForm(data)
        self.assertFalse(form.is_valid())

545
546
    @im_settings(HELPDESK=(('support', 'support@synnefo.org'),))
    @im_settings(FORCE_PROFILE_UPDATE=False)
547
    def test_local_provider(self):
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
548
        self.helpdesk_email = astakos_settings.HELPDESK[0][1]
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
549
        # enable moderation
550
        astakos_settings.MODERATION_ENABLED = True
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
551
552

        # create a user
553
554
        r = self.client.get("/im/signup")
        self.assertEqual(r.status_code, 200)
555
556
        data = {'email': 'kpap@grnet.gr', 'password1': 'password',
                'password2': 'password', 'first_name': 'Kostas',
557
558
                'last_name': 'Mitroglou', 'provider': 'local'}
        r = self.client.post("/im/signup", data)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
559
560

        # user created
561
562
563
564
565
        self.assertEqual(AstakosUser.objects.count(), 1)
        user = AstakosUser.objects.get(username="kpap@grnet.gr",
                                       email="kpap@grnet.gr")
        self.assertEqual(user.username, 'kpap@grnet.gr')
        self.assertEqual(user.has_auth_provider('local'), True)
566
567
568
        self.assertFalse(user.is_active)  # not activated
        self.assertFalse(user.email_verified)  # not verified
        self.assertFalse(user.activation_sent)  # activation automatically sent
569

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
570
        # admin gets notified and activates the user from the command line
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
571
        self.assertEqual(len(get_mailbox(self.helpdesk_email)), 1)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
572
        r = self.client.post('/im/local', {'username': 'kpap@grnet.gr',
573
574
                                           'password': 'password'})
        self.assertContains(r, messages.NOTIFICATION_SENT)
575
576
        functions.send_activation(user)

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
577
        # user activation fields updated and user gets notified via email
578
579
580
        user = AstakosUser.objects.get(pk=user.pk)
        self.assertTrue(user.activation_sent)
        self.assertFalse(user.email_verified)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
581
        self.assertFalse(user.is_active)
582
583
584
585
        self.assertEqual(len(get_mailbox('kpap@grnet.gr')), 1)

        # user forgot she got registered and tries to submit registration
        # form. Notice the upper case in email
586
587
        data = {'email': 'KPAP@grnet.gr', 'password1': 'password',
                'password2': 'password', 'first_name': 'Kostas',
588
                'last_name': 'Mitroglou', 'provider': 'local'}
589
590
591
592
        r = self.client.post("/im/signup", data, follow=True)
        self.assertRedirects(r, reverse('index'))
        self.assertContains(r, messages.NOTIFICATION_SENT)

593
594
595
        user = AstakosUser.objects.get()
        functions.send_activation(user)

596
597
598
599
        # previous user replaced
        self.assertTrue(user.activation_sent)
        self.assertFalse(user.email_verified)
        self.assertFalse(user.is_active)
600
        self.assertEqual(len(get_mailbox('KPAP@grnet.gr')), 1)
601

Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
602
        # hmmm, email exists; lets request a password change
603
604
        r = self.client.get('/im/local/password_reset')
        self.assertEqual(r.status_code, 200)
605
606
        data = {'email': 'kpap@grnet.gr'}
        r = self.client.post('/im/local/password_reset', data, follow=True)
607
        # she can't because account is not active yet
608
        self.assertContains(r, 'pending activation')
609

610
611
612
613
614
        # moderation is enabled and an activation email has already been sent
        # so user can trigger resend of the activation email
        r = self.client.get('/im/send/activation/%d' % user.pk, follow=True)
        self.assertContains(r, 'has been sent to your email address.')
        self.assertEqual(len(get_mailbox('KPAP@grnet.gr')), 2)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
615

616
        # also she cannot login
617
618
        data = {'username': 'kpap@grnet.gr', 'password': 'password'}
        r = self.client.post('/im/local', data, follow=True)
619
620
621
        self.assertContains(r, 'Resend activation')
        self.assertFalse(r.context['request'].user.is_authenticated())
        self.assertFalse('_pithos2_a' in self.client.cookies)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
622

623
        # user sees the message and resends activation
624
625
        r = self.client.get('/im/send/activation/%d' % user.pk, follow=True)
        self.assertEqual(len(get_mailbox('KPAP@grnet.gr')), 3)
626
627
628
629

        # switch back moderation setting
        astakos_settings.MODERATION_ENABLED = True
        r = self.client.get(user.get_activation_url(), follow=True)
630
631
632
633
634
635
        self.assertRedirects(r, "/im/landing")
        r = self.client.get('/im/profile', follow=True)
        self.assertTrue(r.context['request'].user.is_authenticated())
        self.assertTrue('_pithos2_a' in self.client.cookies)
        self.assertContains(r, "KPAP@grnet.gr")
        self.assertEqual(len(get_mailbox('KPAP@grnet.gr')), 4)
636
637
638
639
640
641

        user = AstakosUser.objects.get(pk=user.pk)
        # user activated and logged in, token cookie set
        self.assertTrue(r.context['request'].user.is_authenticated())
        self.assertTrue('_pithos2_a' in self.client.cookies)
        cookies = self.client.cookies
642
643
        self.assertTrue(quote(user.auth_token) in
                        cookies.get('_pithos2_a').value)
644
645
646
647
648
        r = self.client.get('/im/logout', follow=True)
        r = self.client.get('/im/')
        # user logged out, token cookie removed
        self.assertFalse(r.context['request'].user.is_authenticated())
        self.assertFalse(self.client.cookies.get('_pithos2_a').value)
649
650

        #https://docs.djangoproject.com/en/dev/topics/testing/#persistent-state
651
652
653
654
655
        del self.client.cookies['_pithos2_a']

        # user can login
        r = self.client.post('/im/local', {'username': 'kpap@grnet.gr',
                                           'password': 'password'},
656
                             follow=True)
657
658
659
        self.assertTrue(r.context['request'].user.is_authenticated())
        self.assertTrue('_pithos2_a' in self.client.cookies)
        cookies = self.client.cookies
660
661
        self.assertTrue(quote(user.auth_token) in
                        cookies.get('_pithos2_a').value)
662
663
664
665
666
667
668
669
670
671
        self.client.get('/im/logout', follow=True)

        # user forgot password
        old_pass = user.password
        r = self.client.get('/im/local/password_reset')
        self.assertEqual(r.status_code, 200)
        r = self.client.post('/im/local/password_reset', {'email':
                                                          'kpap@grnet.gr'})
        self.assertEqual(r.status_code, 302)
        # email sent
672
        self.assertEqual(len(get_mailbox('KPAP@grnet.gr')), 5)
673
674
675
676

        # user visits change password link
        r = self.client.get(user.get_password_reset_url())
        r = self.client.post(user.get_password_reset_url(),
677
678
                             {'new_password1': 'newpass',
                              'new_password2': 'newpass'})
679
680
681
682
683
684
685

        user = AstakosUser.objects.get(pk=user.pk)
        self.assertNotEqual(old_pass, user.password)

        # old pass is not usable
        r = self.client.post('/im/local', {'username': 'kpap@grnet.gr',
                                           'password': 'password'})
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
686
        self.assertContains(r, 'Please enter a correct username and password')
687
688
        r = self.client.post('/im/local', {'username': 'kpap@grnet.gr',
                                           'password': 'newpass'},
689
                             follow=True)
690
691
692
693
694
695
696
697
698
699
700
701
702
703
        self.assertTrue(r.context['request'].user.is_authenticated())
        self.client.logout()

        # tests of special local backends
        user = AstakosUser.objects.get(pk=user.pk)
        user.auth_providers.filter(module='local').update(auth_backend='ldap')
        user.save()

        # non astakos local backends do not support password reset
        r = self.client.get('/im/local/password_reset')
        self.assertEqual(r.status_code, 200)
        r = self.client.post('/im/local/password_reset', {'email':
                                                          'kpap@grnet.gr'})
        # she can't because account is not active yet
704
705
706
        self.assertContains(r, "Changing password is not")


707
708
709
710
class UserActionsTests(TestCase):

    def test_email_change(self):
        # to test existing email validation
711
        get_local_user('existing@grnet.gr')
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780

        # local user
        user = get_local_user('kpap@grnet.gr')

        # login as kpap
        self.client.login(username='kpap@grnet.gr', password='password')
        r = self.client.get('/im/profile', follow=True)
        user = r.context['request'].user
        self.assertTrue(user.is_authenticated())

        # change email is enabled
        r = self.client.get('/im/email_change')
        self.assertEqual(r.status_code, 200)
        self.assertFalse(user.email_change_is_pending())

        # request email change to an existing email fails
        data = {'new_email_address': 'existing@grnet.gr'}
        r = self.client.post('/im/email_change', data)
        self.assertContains(r, messages.EMAIL_USED)

        # proper email change
        data = {'new_email_address': 'kpap@gmail.com'}
        r = self.client.post('/im/email_change', data, follow=True)
        self.assertRedirects(r, '/im/profile')
        self.assertContains(r, messages.EMAIL_CHANGE_REGISTERED)
        change1 = EmailChange.objects.get()

        # user sees a warning
        r = self.client.get('/im/email_change')
        self.assertEqual(r.status_code, 200)
        self.assertContains(r, messages.PENDING_EMAIL_CHANGE_REQUEST)
        self.assertTrue(user.email_change_is_pending())

        # link was sent
        self.assertEqual(len(get_mailbox('kpap@grnet.gr')), 0)
        self.assertEqual(len(get_mailbox('kpap@gmail.com')), 1)

        # proper email change
        data = {'new_email_address': 'kpap@yahoo.com'}
        r = self.client.post('/im/email_change', data, follow=True)
        self.assertRedirects(r, '/im/profile')
        self.assertContains(r, messages.EMAIL_CHANGE_REGISTERED)
        self.assertEqual(len(get_mailbox('kpap@grnet.gr')), 0)
        self.assertEqual(len(get_mailbox('kpap@yahoo.com')), 1)
        change2 = EmailChange.objects.get()

        r = self.client.get(change1.get_url())
        self.assertEquals(r.status_code, 302)
        self.client.logout()

        r = self.client.post('/im/local?next=' + change2.get_url(),
                             {'username': 'kpap@grnet.gr',
                              'password': 'password',
                              'next': change2.get_url()},
                             follow=True)
        self.assertRedirects(r, '/im/profile')
        user = r.context['request'].user
        self.assertEquals(user.email, 'kpap@yahoo.com')
        self.assertEquals(user.username, 'kpap@yahoo.com')

        self.client.logout()
        r = self.client.post('/im/local?next=' + change2.get_url(),
                             {'username': 'kpap@grnet.gr',
                              'password': 'password',
                              'next': change2.get_url()},
                             follow=True)
        self.assertContains(r, "Please enter a correct username and password")
        self.assertEqual(user.emailchanges.count(), 0)

781

782
783
784
785
786
787
class TestAuthProviderViews(TestCase):

    @shibboleth_settings(CREATION_GROUPS_POLICY=['academic-login'])
    @shibboleth_settings(AUTOMODERATE_POLICY=True)
    @im_settings(IM_MODULES=['shibboleth', 'local'])
    @im_settings(MODERATION_ENABLED=True)
788
    @im_settings(FORCE_PROFILE_UPDATE=False)
789
790
791
792
793
    def test_user(self):
        Profile = AuthProviderPolicyProfile
        Pending = PendingThirdPartyUser
        User = AstakosUser

794
795
        User.objects.create(email="newuser@grnet.gr")
        get_local_user("olduser@grnet.gr")
796
        cl_olduser = ShibbolethClient()
797
798
        get_local_user("olduser2@grnet.gr")
        ShibbolethClient()
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
        cl_newuser = ShibbolethClient()
        cl_newuser2 = Client()

        academic_group, created = Group.objects.get_or_create(
            name='academic-login')
        academic_users = academic_group.user_set
        assert created
        policy_only_academic = Profile.objects.add_policy('academic_strict',
                                                          'shibboleth',
                                                          academic_group,
                                                          exclusive=True,
                                                          login=False,
                                                          add=False)


        # new academic user
        self.assertFalse(academic_users.filter(email='newuser@grnet.gr'))
        cl_newuser.set_tokens(eppn="newusereppn")
        r = cl_newuser.get('/im/login/shibboleth?', follow=True)
        pending = Pending.objects.get()
        identifier = pending.third_party_identifier
        signup_data = {'third_party_identifier': identifier,
                       'first_name': 'Academic',
                       'third_party_token': pending.token,
                       'last_name': 'New User',
                       'provider': 'shibboleth'}
        r = cl_newuser.post('/im/signup', signup_data)
        self.assertContains(r, "This field is required", )
        signup_data['email'] = 'olduser@grnet.gr'
        r = cl_newuser.post('/im/signup', signup_data)
        self.assertContains(r, "already an account with this email", )
        signup_data['email'] = 'newuser@grnet.gr'
        r = cl_newuser.post('/im/signup', signup_data, follow=True)
        r = cl_newuser.post('/im/signup', signup_data, follow=True)
        self.assertEqual(r.status_code, 404)
        newuser = User.objects.get(email="newuser@grnet.gr")
        activation_link = newuser.get_activation_url()
        self.assertTrue(academic_users.get(email='newuser@grnet.gr'))

        # new non-academic user
        signup_data = {'first_name': 'Non Academic',
                       'last_name': 'New User',
                       'provider': 'local',
                       'password1': 'password',
                       'password2': 'password'}
        signup_data['email'] = 'olduser@grnet.gr'
        r = cl_newuser2.post('/im/signup', signup_data)
        self.assertContains(r, 'There is already an account with this '
                               'email address')
        signup_data['email'] = 'newuser@grnet.gr'
        r = cl_newuser2.post('/im/signup/', signup_data)
        self.assertFalse(academic_users.filter(email='newuser@grnet.gr'))
        r = self.client.get(activation_link, follow=True)
        self.assertEqual(r.status_code, 400)
        newuser = User.objects.get(email="newuser@grnet.gr")
        self.assertFalse(newuser.activation_sent)
        r = self.client.get(newuser.get_activation_url(), follow=True)
        self.assertContains(r, "pending moderation")

        self.assertFalse(academic_users.filter(email='newuser@grnet.gr'))
        r = cl_newuser.get('/im/login/shibboleth?', follow=True)
        pending = Pending.objects.get()
        identifier = pending.third_party_identifier
        signup_data = {'third_party_identifier': identifier,
                       'first_name': 'Academic',
                       'third_party_token': pending.token,
                       'last_name': 'New User',
                       'provider': 'shibboleth'}
        signup_data['email'] = 'newuser@grnet.gr'
        r = cl_newuser.post('/im/signup', signup_data)
        newuser = User.objects.get(email="newuser@grnet.gr")
        self.assertTrue(newuser.activation_sent)
        activation_link = newuser.get_activation_url()
        self.assertTrue(academic_users.get(email='newuser@grnet.gr'))
        r = cl_newuser.get(newuser.get_activation_url(), follow=True)
        self.assertRedirects(r, '/im/landing')
        newuser = User.objects.get(email="newuser@grnet.gr")
        self.assertEqual(newuser.is_active, True)
        self.assertEqual(newuser.email_verified, True)
        cl_newuser.logout()

        # cannot reactivate if suspended
        newuser.is_active = False
        newuser.save()
        r = cl_newuser.get(newuser.get_activation_url())
        newuser = User.objects.get(email="newuser@grnet.gr")
        self.assertFalse(newuser.is_active)

        # release suspension
        newuser.is_active = True
        newuser.save()

        cl_newuser.get('/im/login/shibboleth?', follow=True)
        local = auth.get_provider('local', newuser)
        self.assertEqual(local.get_add_policy, False)
        self.assertEqual(local.get_login_policy, False)
        r = cl_newuser.get(local.get_add_url, follow=True)
        self.assertRedirects(r, '/im/profile')
        self.assertContains(r, 'disabled for your')

        cl_olduser.login(username='olduser@grnet.gr', password="password")
        r = cl_olduser.get('/im/profile', follow=True)
        self.assertEqual(r.status_code, 200)
        r = cl_olduser.get('/im/login/shibboleth?', follow=True)
        self.assertContains(r, 'Your request is missing a unique token')
        cl_olduser.set_tokens(eppn="newusereppn")
        r = cl_olduser.get('/im/login/shibboleth?', follow=True)
        self.assertContains(r, 'is already assigned to another user')
        cl_olduser.set_tokens(eppn="oldusereppn")
        r = cl_olduser.get('/im/login/shibboleth?', follow=True)
        self.assertContains(r, 'Academic login enabled for this account')

        user = User.objects.get(email="olduser@grnet.gr")
        shib_provider = user.get_auth_provider('shibboleth', 'oldusereppn')
        local_provider = user.get_auth_provider('local')
        self.assertEqual(shib_provider.get_remove_policy, True)
        self.assertEqual(local_provider.get_remove_policy, True)


        policy_only_academic = Profile.objects.add_policy('academic_strict2',
                                                          'shibboleth',
                                                          academic_group,
                                                          remove=False)
        user.groups.add(academic_group)
        shib_provider = user.get_auth_provider('shibboleth', 'oldusereppn')
        local_provider = user.get_auth_provider('local')
        self.assertEqual(shib_provider.get_remove_policy, False)
        self.assertEqual(local_provider.get_remove_policy, True)
        self.assertEqual(local_provider.get_login_policy, False)

        cl_olduser.logout()
        login_data = {'username': 'olduser@grnet.gr', 'password': 'password'}
        r = cl_olduser.post('/im/local', login_data, follow=True)
        self.assertContains(r, "href='/im/login/shibboleth'>Academic login")
933
934


935
936
937
938
939
940
class TestAuthProvidersAPI(TestCase):
    """
    Test auth_providers module API
    """

    @im_settings(IM_MODULES=['local', 'shibboleth'])
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
    def test_create(self):
        user = AstakosUser.objects.create(email="kpap@grnet.gr")
        user2 = AstakosUser.objects.create(email="kpap2@grnet.gr")

        module = 'shibboleth'
        identifier = 'SHIB_UUID'
        provider_params = {
            'affiliation': 'UNIVERSITY',
            'info': {'age': 27}
        }
        provider = auth.get_provider(module, user2, identifier,
                                     **provider_params)
        provider.add_to_user()
        provider = auth.get_provider(module, user, identifier,
                                     **provider_params)
        provider.add_to_user()
        user.email_verified = True
        user.save()
        self.assertRaises(Exception, provider.add_to_user)
        provider = user.get_auth_provider(module, identifier)
        self.assertEqual(user.get_auth_provider(
            module, identifier)._instance.info.get('age'), 27)

        module = 'local'
        identifier = None
        provider_params = {'auth_backend': 'ldap', 'info':
                          {'office': 'A1'}}
        provider = auth.get_provider(module, user, identifier,
                                     **provider_params)
        provider.add_to_user()
        self.assertFalse(provider.get_add_policy)
        self.assertRaises(Exception, provider.add_to_user)

        shib = user.get_auth_provider('shibboleth',
                                      'SHIB_UUID')
        self.assertTrue(shib.get_remove_policy)

        local = user.get_auth_provider('local')
        self.assertTrue(local.get_remove_policy)

        local.remove_from_user()
        self.assertFalse(shib.get_remove_policy)
        self.assertRaises(Exception, shib.remove_from_user)

985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
        provider = user.get_auth_providers()[0]
        self.assertRaises(Exception, provider.add_to_user)

    @im_settings(IM_MODULES=['local', 'shibboleth'])
    @shibboleth_settings(ADD_GROUPS_POLICY=['group1', 'group2'])
    @shibboleth_settings(CREATION_GROUPS_POLICY=['group-create', 'group1',
                                                 'group2'])
    @localauth_settings(ADD_GROUPS_POLICY=['localgroup'])
    @localauth_settings(CREATION_GROUPS_POLICY=['localgroup-create',
                                                'group-create'])
    def test_add_groups(self):
        user = AstakosUser.objects.create(email="kpap@grnet.gr")
        provider = auth.get_provider('shibboleth', user, 'test123')
        provider.add_to_user()
        user = AstakosUser.objects.get()
        self.assertItemsEqual(user.groups.values_list('name', flat=True),
                              [u'group1', u'group2', u'group-create'])

        local = auth.get_provider('local', user)
        local.add_to_user()
        provider = user.get_auth_provider('shibboleth')
        self.assertEqual(provider.get_add_groups_policy, ['group1', 'group2'])
        provider.remove_from_user()
        user = AstakosUser.objects.get()
        self.assertEqual(len(user.get_auth_providers()), 1)
        self.assertItemsEqual(user.groups.values_list('name', flat=True),
                              [u'group-create', u'localgroup'])

        local = user.get_auth_provider('local')
        self.assertRaises(Exception, local.remove_from_user)
        provider = auth.get_provider('shibboleth', user, 'test123')
        provider.add_to_user()
        user = AstakosUser.objects.get()
        self.assertItemsEqual(user.groups.values_list('name', flat=True),
                              [u'group-create', u'group1', u'group2',
                               u'localgroup'])



    @im_settings(IM_MODULES=['local', 'shibboleth'])
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
    def test_policies(self):
        group_old, created = Group.objects.get_or_create(name='olduser')

        astakos_settings.MODERATION_ENABLED = True
        settings.ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_CREATION_GROUPS_POLICY = \
            ['academic-user']
        settings.ASTAKOS_AUTH_PROVIDER_GOOGLE_ADD_GROUPS_POLICY = \
            ['google-user']

        user = AstakosUser.objects.create(email="kpap@grnet.gr")
        user.groups.add(group_old)
        user.add_auth_provider('local')

        user2 = AstakosUser.objects.create(email="kpap2@grnet.gr")
        user2.add_auth_provider('shibboleth', identifier='shibid')

        user3 = AstakosUser.objects.create(email="kpap3@grnet.gr")
        user3.groups.add(group_old)
        user3.add_auth_provider('local')
        user3.add_auth_provider('shibboleth', identifier='1234')

        self.assertTrue(user2.groups.get(name='academic-user'))
        self.assertFalse(user2.groups.filter(name='olduser').count())

        local = auth_providers.get_provider('local')
        self.assertTrue(local.get_add_policy)

        academic_group = Group.objects.get(name='academic-user')
        AuthProviderPolicyProfile.objects.add_policy('academic', 'shibboleth',
                                                     academic_group,
                                                     exclusive=True,
                                                     add=False,
                                                     login=False)
        AuthProviderPolicyProfile.objects.add_policy('academic', 'shibboleth',
                                                     academic_group,
                                                     exclusive=True,
                                                     login=False,
                                                     add=False)
        # no duplicate entry gets created
        self.assertEqual(academic_group.authpolicy_profiles.count(), 1)

        self.assertEqual(user2.authpolicy_profiles.count(), 0)
        AuthProviderPolicyProfile.objects.add_policy('academic', 'shibboleth',
                                                     user2,
                                                     remove=False)
        self.assertEqual(user2.authpolicy_profiles.count(), 1)

        local = auth_providers.get_provider('local', user2)
        google = auth_providers.get_provider('google', user2)
        shibboleth = auth_providers.get_provider('shibboleth', user2)
        self.assertTrue(shibboleth.get_login_policy)
        self.assertFalse(shibboleth.get_remove_policy)
        self.assertFalse(local.get_add_policy)
        self.assertFalse(local.get_add_policy)
        self.assertFalse(google.get_add_policy)

        user2.groups.remove(Group.objects.get(name='academic-user'))
        self.assertTrue(local.get_add_policy)
        self.assertTrue(google.get_add_policy)
        user2.groups.add(Group.objects.get(name='academic-user'))

        AuthProviderPolicyProfile.objects.add_policy('academic', 'shibboleth',
                                                     user2,
                                                     exclusive=True,
                                                     add=True)
        self.assertTrue(local.get_add_policy)
        self.assertTrue(google.get_add_policy)

        settings.ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_AUTOMODERATE_POLICY = True
        self.assertFalse(local.get_automoderate_policy)
        self.assertFalse(google.get_automoderate_policy)
        self.assertTrue(shibboleth.get_automoderate_policy)

        for s in ['SHIBBOLETH_CREATION_GROUPS_POLICY',
                  'GOOGLE_ADD_GROUPS_POLICY']:
            delattr(settings, 'ASTAKOS_AUTH_PROVIDER_%s' % s)
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198


    @shibboleth_settings(CREATE_POLICY=True)
    @im_settings(IM_MODULES=['local', 'shibboleth'])
    def test_create_http(self):
        # this should be wrapped inside a transaction
        user = AstakosUser(email="test@test.com")
        user.save()
        provider = auth_providers.get_provider('shibboleth', user,
                                               'test@academia.test')
        provider.add_to_user()
        user.get_auth_provider('shibboleth', 'test@academia.test')
        provider = auth_providers.get_provider('local', user)
        provider.add_to_user()
        user.get_auth_provider('local')

        settings.ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_CREATE_POLICY = False
        user = AstakosUser(email="test2@test.com")
        user.save()
        provider = auth_providers.get_provider('shibboleth', user,
                                               'test@shibboleth.com',
                                               **{'info': {'name':
                                                                'User Test'}})
        self.assertFalse(provider.get_create_policy)
        settings.ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_CREATE_POLICY = True
        self.assertTrue(provider.get_create_policy)
        academic = provider.add_to_user()

    @im_settings(IM_MODULES=['local', 'shibboleth'])
    @shibboleth_settings(LIMIT_POLICY=2)
    def test_policies(self):
        user = get_local_user('kpap@grnet.gr')
        user.add_auth_provider('shibboleth', identifier='1234')
        user.add_auth_provider('shibboleth', identifier='12345')

        # default limit is 1
        local = user.get_auth_provider('local')
        self.assertEqual(local.get_add_policy, False)

        settings.ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_LIMIT_POLICY = 3
        academic = user.get_auth_provider('shibboleth',
                                          identifier='1234')
        self.assertEqual(academic.get_add_policy, False)
        newacademic = auth_providers.get_provider('shibboleth', user,
                                                  identifier='123456')
        self.assertEqual(newacademic.get_add_policy, True)
        user.add_auth_provider('shibboleth', identifier='123456')
        self.assertEqual(academic.get_add_policy, False)
        settings.ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_LIMIT_POLICY = 1

    @im_settings(IM_MODULES=['local', 'shibboleth'])
    @shibboleth_settings(LIMIT_POLICY=2)
    def test_messages(self):
        user = get_local_user('kpap@grnet.gr')
        user.add_auth_provider('shibboleth', identifier='1234')
        user.add_auth_provider('shibboleth', identifier='12345')
        provider = auth_providers.get_provider('shibboleth')
        self.assertEqual(provider.get_message('title'), 'Academic')
        settings.ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_TITLE = 'New title'
        # regenerate messages cache
        provider = auth_providers.get_provider('shibboleth')
        self.assertEqual(provider.get_message('title'), 'New title')
        self.assertEqual(provider.get_message('login_title'),
                         'New title LOGIN')
        self.assertEqual(provider.get_login_title_msg, 'New title LOGIN')
        self.assertEqual(provider.get_module_icon,
                         settings.MEDIA_URL + 'im/auth/icons/shibboleth.png')
        self.assertEqual(provider.get_module_medium_icon,
                         settings.MEDIA_URL +
                         'im/auth/icons-medium/shibboleth.png')

        settings.ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_TITLE = None
        provider = auth_providers.get_provider('shibboleth', user, '12345')
        self.assertEqual(provider.get_method_details_msg,
                         'Account: 12345')
        provider = auth_providers.get_provider('shibboleth', user, '1234')
        self.assertEqual(provider.get_method_details_msg,
                         'Account: 1234')

        provider = auth_providers.get_provider('shibboleth', user, '1234')
        self.assertEqual(provider.get_not_active_msg,
                         "'Academic login' is disabled.")

    @im_settings(IM_MODULES=['local', 'shibboleth'])
    @shibboleth_settings(LIMIT_POLICY=2)
    def test_templates(self):
        user = get_local_user('kpap@grnet.gr')
        user.add_auth_provider('shibboleth', identifier='1234')
        user.add_auth_provider('shibboleth', identifier='12345')

        provider = auth_providers.get_provider('shibboleth')
        self.assertEqual(provider.get_template('login'),
                         'im/auth/shibboleth_login.html')
        provider = auth_providers.get_provider('google')
        self.assertEqual(provider.get_template('login'),
                         'im/auth/generic_login.html')


1199
1200
1201
1202
1203
1204
1205
1206
class TestProjects(TestCase):
    """
    Test projects.
    """
    def setUp(self):
        self.service = Service.objects.create(name="service1",
                                              api_url="http://service.api")
        self.resource = Resource.objects.create(name="service1.resource",
1207
1208
                                                uplimit=100,
                                                service=self.service)
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
        self.admin = get_local_user("projects-admin@synnefo.org")
        self.admin.uuid = 'uuid1'
        self.admin.save()

        self.user = get_local_user("user@synnefo.org")
        self.member = get_local_user("member@synnefo.org")
        self.member2 = get_local_user("member2@synnefo.org")

        self.admin_client = get_user_client("projects-admin@synnefo.org")
        self.user_client = get_user_client("user@synnefo.org")
        self.member_client = get_user_client("member@synnefo.org")
        self.member2_client = get_user_client("member2@synnefo.org")

    @im_settings(PENDING_APPLICATION_LIMIT=0, PROJECT_ADMINS=['uuid1'])
    def test_application_limit(self):
        # user cannot create a project
        r = self.user_client.get(reverse('project_add'), follow=True)
        self.assertRedirects(r, reverse('project_list'))
        self.assertContains(r, "You are not allowed to create a new project")

        # but admin can
        r = self.admin_client.get(reverse('project_add'), follow=True)
        self.assertRedirects(r, reverse('project_add'))

    @im_settings(PENDING_APPLICATION_LIMIT=2, PROJECT_ADMINS=['uuid1'])
    def test_applications(self):
        r = self.user_client.get(reverse('project_add'), follow=True)
        self.assertRedirects(r, reverse('project_add'))

        # user fills the project application form
        post_url = reverse('project_add') + '?verify=1'
        dfrom = datetime.now()
        dto = datetime.now() + timedelta(days=30)
        application_data = {
            'name': 'project.synnefo.org',
            'homepage': 'https://www.synnefo.org',
            'start_date': dfrom.strftime("%Y-%m-%d"),
            'end_date': dto.strftime("%Y-%m-%d"),
            'member_join_policy': 2,
            'member_leave_policy': 1,
            'service1.resource_uplimit': 100,
            'is_selected_service1.resource': 1,
            'user': self.user.pk
        }
        r = self.user_client.post(post_url, data=application_data, follow=True)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.context['form'].is_valid(), True)

        # confirm request
        post_url = reverse('project_add') + '?verify=0&edit=0'
        r = self.user_client.post(post_url, data=application_data, follow=True)
        self.assertContains(r, "The project application has been received")
        self.assertRedirects(r, reverse('project_list'))
        self.assertEqual(ProjectApplication.objects.count(), 1)
        app1_id = ProjectApplication.objects.filter().order_by('pk')[0].pk

        # create another one
        application_data['name'] = 'project2.synnefo.org'
        r = self.user_client.post(post_url, data=application_data, follow=True)
        app2_id = ProjectApplication.objects.filter().order_by('pk')[1].pk

        # no more applications (LIMIT is 2)
        r = self.user_client.get(reverse('project_add'), follow=True)
        self.assertRedirects(r, reverse('project_list'))
        self.assertContains(r, "You are not allowed to create a new project")

        # login
        self.admin_client.get(reverse("edit_profile"))
        # admin approves
        r = self.admin_client.post(reverse('project_app_approve',
                                           kwargs={'application_id': app1_id}),
                                   follow=True)
        self.assertEqual(r.status_code, 200)

        # project created
        self.assertEqual(Project.objects.count(), 1)

        # login
        self.member_client.get(reverse("edit_profile"))
        # cannot join app2 (not approved yet)
        join_url = reverse("project_join", kwargs={'chain_id': app2_id})
        r = self.member_client.post(join_url, follow=True)
        self.assertEqual(r.status_code, 403)

        # can join app1
        self.member_client.get(reverse("edit_profile"))
        join_url = reverse("project_join", kwargs={'chain_id': app1_id})
        r = self.member_client.post(join_url, follow=True)
        self.assertEqual(r.status_code, 200)

        self.assertEqual(ProjectMembership.objects.count(), 1)

        reject_member_url = reverse('project_reject_member',
                                    kwargs={'chain_id': app1_id, 'user_id':
                                            self.member.pk})
        accept_member_url = reverse('project_accept_member',
                                    kwargs={'chain_id': app1_id, 'user_id':
                                            self.member.pk})

        # only project owner is allowed to reject
        r = self.member_client.post(reject_member_url, follow=True)
        self.assertContains(r, "You do not have the permissions")
        self.assertEqual(r.status_code, 200)

        # user (owns project) rejects membership
        r = self.user_client.post(reject_member_url, follow=True)
        self.assertEqual(ProjectMembership.objects.count(), 0)

        # user rejoins
        self.member_client.get(reverse("edit_profile"))
        join_url = reverse("project_join", kwargs={'chain_id': app1_id})
        r = self.member_client.post(join_url, follow=True)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(ProjectMembership.objects.count(), 1)

        # user (owns project) accepts membership
        r = self.user_client.post(accept_member_url, follow=True)
        self.assertEqual(ProjectMembership.objects.count(), 1)
        membership = ProjectMembership.objects.get()
        self.assertEqual(membership.state, ProjectMembership.ACCEPTED)

        user_quotas = quotas.get_users_quotas([self.member])
        resource = 'service1.resource'
        newlimit = user_quotas[self.member.uuid]['system'][resource]['limit']
        # 100 from initial uplimit + 100 from project
        self.assertEqual(newlimit, 200)

        remove_member_url = reverse('project_remove_member',
                                    kwargs={'chain_id': app1_id, 'user_id':
                                            self.member.pk})
        r = self.user_client.post(remove_member_url, follow=True)
        self.assertEqual(r.status_code, 200)

        user_quotas = quotas.get_users_quotas([self.member])
        resource = 'service1.resource'
        newlimit = user_quotas[self.member.uuid]['system'][resource]['limit']
        # 200 - 100 from project
        self.assertEqual(newlimit, 100)