Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / auth_providers.py @ cbc7a32c

History | View | Annotate | Download (22.2 kB)

1
# Copyright 2011 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
import copy
35
import json
36

    
37
from synnefo.lib.ordereddict import OrderedDict
38

    
39
from django.core.urlresolvers import reverse
40
from django.utils.translation import ugettext as _
41
from django.contrib.auth.models import Group
42
from django import template
43

    
44
from django.conf import settings
45

    
46
from astakos.im import settings as astakos_settings
47
from astakos.im import messages as astakos_messages
48

    
49
from synnefo_branding import utils as branding_utils
50

    
51
import logging
52

    
53
logger = logging.getLogger(__name__)
54

    
55
# providers registry
56
PROVIDERS = {}
57
REQUIRED_PROVIDERS = {}
58

    
59

    
60
class AuthProviderBase(type):
61

    
62
    def __new__(cls, name, bases, dct):
63
        include = False
64
        if [b for b in bases if isinstance(b, AuthProviderBase)]:
65
            type_id = dct.get('module')
66
            if type_id:
67
                include = True
68
            if type_id in astakos_settings.IM_MODULES:
69
                if astakos_settings.IM_MODULES.index(type_id) == 0:
70
                    dct['is_primary'] = True
71
                dct['module_enabled'] = True
72

    
73
        newcls = super(AuthProviderBase, cls).__new__(cls, name, bases, dct)
74
        if include:
75
            PROVIDERS[type_id] = newcls
76
            if newcls().get_required_policy:
77
                REQUIRED_PROVIDERS[type_id] = newcls
78
        return newcls
79

    
80

    
81
class AuthProvider(object):
82

    
83
    __metaclass__ = AuthProviderBase
84

    
85
    module = None
86
    module_enabled = False
87
    is_primary = False
88

    
89
    message_tpls = OrderedDict((
90
        ('title', '{module_title}'),
91
        ('login_title', '{title} LOGIN'),
92
        ('method_prompt', '{title} login'),
93
        ('account_prompt', '{title} account'),
94
        ('signup_title', '{title}'),
95
        ('profile_title', '{title}'),
96
        ('method_details', '{account_prompt}: {identifier}'),
97
        ('primary_login_prompt', 'Login using '),
98
        ('required', '{title} is required. You can assign it '
99
                     'from your profile page'),
100
        ('login_prompt', ''),
101
        ('add_prompt', 'Allows you to login using {title}'),
102
        ('login_extra', ''),
103
        ('username', '{username}'),
104
        ('disabled_for_create', 'It seems this is the first time you\'re '
105
                                'trying to access {service_name}. '
106
                                'Unfortunately, we are not accepting new '
107
                                'users at this point.'),
108
        ('switch_success', 'Account changed successfully.'),
109
        ('cannot_login', '{title} is not available for login. '
110
                         'Please use one of your other available methods '
111
                         'to login ({available_methods_links}'),
112

    
113
        # icons should end with _icon
114
        ('module_medium_icon', 'im/auth/icons-medium/{module}.png'),
115
        ('module_icon', 'im/auth/icons/{module}.png'))
116
    )
117

    
118
    messages = {}
119
    module_urls = {}
120

    
121
    remote_authenticate = True
122
    remote_logout_url = None
123

    
124
    # templates
125
    primary_login_template = 'im/auth/generic_primary_login.html'
126
    login_template = 'im/auth/generic_login.html'
127
    signup_template = 'im/signup.html'
128
    login_prompt_template = 'im/auth/generic_login_prompt.html'
129
    signup_prompt_template = 'im/auth/signup_prompt.html'
130

    
131
    default_policies = {
132
        'login': True,
133
        'create': True,
134
        'add': True,
135
        'remove': True,
136
        'limit': 1,
137
        'switch': True,
138
        'add_groups': [],
139
        'creation_groups': [],
140
        'required': False,
141
        'automoderate': not astakos_settings.MODERATION_ENABLED
142
    }
143

    
144
    policies = {}
145

    
146
    def __init__(self, user=None, identifier=None, **provider_params):
147
        """
148
        3 ways to initialize (no args, user, user and identifier).
149

150
        no args: Used for anonymous unauthenticated users.
151
        >>> p = auth_providers.get_provider('local')
152
        >>> # check that global settings allows us to create a new account
153
        >>> # using `local` provider.
154
        >>> print p.is_available_for_create()
155

156
        user and identifier: Used to provide details about a user's specific
157
        login method.
158
        >>> p = auth_providers.get_provider('google', user,
159
        >>>                                 identifier='1421421')
160
        >>> # provider (google) details prompt
161
        >>> print p.get_method_details()
162
        "Google account: 1421421"
163
        """
164

    
165
        # handle AnonymousUser instance
166
        self.user = None
167
        if user and hasattr(user, 'pk') and user.pk:
168
            self.user = user
169

    
170
        self.identifier = identifier
171
        self._instance = None
172
        if 'instance' in provider_params:
173
            self._instance = provider_params['instance']
174
            del provider_params['instance']
175

    
176
        # initialize policies
177
        self.module_policies = copy.copy(self.default_policies)
178
        self.module_policies['automoderate'] = not \
179
            astakos_settings.MODERATION_ENABLED
180
        for policy, value in self.policies.iteritems():
181
            setting_key = "%s_POLICY" % policy.upper()
182
            if self.has_setting(setting_key):
183
                self.module_policies[policy] = self.get_setting(setting_key)
184
            else:
185
                self.module_policies[policy] = value
186

    
187
        # messages cache
188
        self.message_tpls_compiled = OrderedDict()
189

    
190
        # module specific messages
191
        self.message_tpls = OrderedDict(self.message_tpls)
192
        for key, value in self.messages.iteritems():
193
            self.message_tpls[key] = value
194

    
195
        self._provider_details = provider_params
196

    
197
        self.resolve_available_methods = True
198

    
199
    def get_provider_model(self):
200
        from astakos.im.models import AstakosUserAuthProvider as AuthProvider
201
        return AuthProvider
202

    
203
    def remove_from_user(self):
204
        if not self.get_remove_policy:
205
            raise Exception("Provider cannot be removed")
206

    
207
        for group_name in self.get_add_groups_policy:
208
            group = Group.objects.get(name=group_name)
209
            self.user.groups.remove(group)
210
            self.log('removed from group due to add_groups_policy %s',
211
                     group.name)
212

    
213
        self._instance.delete()
214
        self.log('removed')
215

    
216
    def add_to_user(self, **params):
217
        if self._instance:
218
            raise Exception("Cannot add an existing provider")
219

    
220
        create = False
221
        if self.get_user_providers().count() == 0:
222
            create = True
223

    
224
        if create and not self.get_create_policy:
225
            raise Exception("Provider not available for create")
226

    
227
        if not self.get_add_policy:
228
            raise Exception("Provider cannot be added")
229

    
230
        if create:
231
            for group_name in self.get_creation_groups_policy:
232
                group, created = Group.objects.get_or_create(name=group_name)
233
                self.user.groups.add(group)
234
                self.log("added to %s group due to creation_groups_policy",
235
                         group_name)
236

    
237
        for group_name in self.get_add_groups_policy:
238
            group, created = Group.objects.get_or_create(name=group_name)
239
            self.user.groups.add(group)
240
            self.log("added to %s group due to add_groups_policy",
241
                     group_name)
242

    
243
        if self.identifier:
244
            pending = self.get_provider_model().objects.unverified(
245
                self.module, identifier=self.identifier)
246

    
247
            if pending:
248
                pending._instance.delete()
249

    
250
        create_params = {
251
            'module': self.module,
252
            'info_data': json.dumps(self.provider_details.get('info', {})),
253
            'active': True,
254
            'identifier': self.identifier
255
        }
256
        if 'info' in self.provider_details:
257
            del self.provider_details['info']
258

    
259
        create_params.update(self.provider_details)
260
        create_params.update(params)
261
        create = self.user.auth_providers.create(**create_params)
262
        self.log("created %r" % create_params)
263
        return create
264

    
265
    def __repr__(self):
266
        r = "'%s' module" % self.__class__.__name__
267
        if self.user:
268
            r += ' (user: %s)' % self.user
269
        if self.identifier:
270
            r += '(identifier: %s)' % self.identifier
271
        return r
272

    
273
    def _message_params(self, **extra_params):
274
        """
275
        Retrieve message formating parameters.
276
        """
277
        params = {'module': self.module, 'module_title': self.module.title()}
278
        if self.identifier:
279
            params['identifier'] = self.identifier
280

    
281
        if self.user:
282
            for key, val in self.user.__dict__.iteritems():
283
                params["user_%s" % key.lower()] = val
284

    
285
        if self.provider_details:
286
            for key, val in self.provider_details.iteritems():
287
                params["provider_%s" % key.lower()] = val
288

    
289
            if 'info' in self.provider_details:
290
                if isinstance(self.provider_details['info'], basestring):
291
                    self.provider_details['info'] = \
292
                        json.loads(self.provider_details['info'])
293
                for key, val in self.provider_details['info'].iteritems():
294
                    params['provider_info_%s' % key.lower()] = val
295

    
296
        # resolve username, handle unexisting defined username key
297
        if self.user and self.username_key in params:
298
            params['username'] = params[self.username_key]
299
        else:
300
            params['username'] = self.identifier
301

    
302
        branding_params = dict(map(lambda k: (k[0].lower(), k[1]),
303
            branding_utils.get_branding_dict().iteritems()))
304
        params.update(branding_params)
305

    
306
        if not self.message_tpls_compiled:
307
            for key, message_tpl in self.message_tpls.iteritems():
308
                msg = self.messages.get(key, self.message_tpls.get(key))
309
                override_in_settings = self.get_setting(key)
310
                if override_in_settings is not None:
311
                    msg = override_in_settings
312
                try:
313
                    self.message_tpls_compiled[key] = msg.format(**params)
314
                    params.update(self.message_tpls_compiled)
315
                except KeyError, e:
316
                    continue
317
        else:
318
            params.update(self.message_tpls_compiled)
319

    
320
        for key, value in self.urls.iteritems():
321
            params['%s_url' % key] = value
322

    
323
        if self.user and self.resolve_available_methods:
324
            available_providers = self.user.get_enabled_auth_providers()
325
            for p in available_providers:
326
                p.resolve_available_methods = False
327
                if p.module == self.module and p.identifier == self.identifier:
328
                    available_providers.remove(p)
329

    
330
            get_msg = lambda p: p.get_method_prompt_msg
331
            params['available_methods'] = \
332
                ','.join(map(get_msg, available_providers))
333

    
334
            get_msg = lambda p: "<a href='%s'>%s</a>" % \
335
                (p.get_login_url, p.get_method_prompt_msg)
336

    
337
            params['available_methods_links'] = \
338
                ','.join(map(get_msg, available_providers))
339

    
340
        params.update(extra_params)
341
        return params
342

    
343
    def get_template(self, tpl):
344
        tpls = ['im/auth/%s_%s.html' % (self.module, tpl),
345
                getattr(self, '%s_template' % tpl)]
346
        found = None
347
        for tpl in tpls:
348
            try:
349
                found = template.loader.get_template(tpl)
350
                return tpl
351
            except template.TemplateDoesNotExist:
352
                continue
353
        if not found:
354
            raise template.TemplateDoesNotExist
355
        return tpl
356

    
357
    def get_username(self):
358
        return self.get_username_msg
359

    
360
    def get_user_providers(self):
361
        return self.user.auth_providers.active().filter(
362
            module__in=astakos_settings.IM_MODULES)
363

    
364
    def get_user_module_providers(self):
365
        return self.user.auth_providers.active().filter(module=self.module)
366

    
367
    def get_existing_providers(self):
368
        return ""
369

    
370
    def verified_exists(self):
371
        return self.get_provider_model().objects.verified(
372
            self.module, identifier=self.identifier)
373

    
374
    def resolve_policy(self, policy, default=None):
375

    
376
        if policy == 'switch' and default and not self.get_add_policy:
377
            return not self.get_policy('remove')
378

    
379
        if not self.user:
380
            return default
381

    
382
        if policy == 'remove' and default is True:
383
            return self.get_user_providers().count() > 1
384

    
385
        if policy == 'add' and default is True:
386
            limit = self.get_policy('limit')
387
            if limit <= self.get_user_module_providers().count():
388
                return False
389

    
390
            if self.identifier:
391
                if self.verified_exists():
392
                    return False
393

    
394
        return default
395

    
396
    def get_user_policies(self):
397
        from astakos.im.models import AuthProviderPolicyProfile
398
        return AuthProviderPolicyProfile.objects.for_user(self.user,
399
                                                          self.module)
400

    
401
    def get_policy(self, policy):
402
        module_default = self.module_policies.get(policy)
403
        settings_key = '%s_POLICY' % policy.upper()
404
        settings_default = self.get_setting(settings_key, module_default)
405

    
406
        if self.user:
407
            user_policies = self.get_user_policies()
408
            settings_default = user_policies.get(policy, settings_default)
409

    
410
        return self.resolve_policy(policy, settings_default)
411

    
412
    def get_message(self, msg, **extra_params):
413
        """
414
        Retrieve an auth provider message
415
        """
416
        if msg.endswith('_msg'):
417
            msg = msg.replace('_msg', '')
418
        params = self._message_params(**extra_params)
419

    
420
        # is message ???
421
        tpl = self.message_tpls_compiled.get(msg.lower(), None)
422
        if not tpl:
423
            msg_key = 'AUTH_PROVIDER_%s' % msg.upper()
424
            try:
425
                tpl = getattr(astakos_messages, msg_key)
426
            except AttributeError, e:
427
                try:
428
                    msg_key = msg.upper()
429
                    tpl = getattr(astakos_messages, msg_key)
430
                except AttributeError, e:
431
                    tpl = ''
432

    
433
        in_settings = self.get_setting(msg)
434
        if in_settings:
435
            tpl = in_settings
436

    
437
        return tpl.format(**params)
438

    
439
    @property
440
    def urls(self):
441
        urls = {
442
            'login': reverse(self.login_view),
443
            'add': reverse(self.login_view),
444
            'profile': reverse('edit_profile'),
445
        }
446
        if self.user:
447
            urls.update({
448
                'resend_activation': self.user.get_resend_activation_url(),
449
            })
450
        if self.identifier and self._instance:
451
            urls.update({
452
                'switch': reverse(self.login_view) + '?switch_from=%d' %
453
                self._instance.pk,
454
                'remove': reverse('remove_auth_provider',
455
                                  kwargs={'pk': self._instance.pk})
456
            })
457
        urls.update(self.module_urls)
458
        return urls
459

    
460
    def get_setting_key(self, name):
461
        return 'ASTAKOS_AUTH_PROVIDER_%s_%s' % (self.module.upper(),
462
                                                name.upper())
463

    
464
    def get_global_setting_key(self, name):
465
        return 'ASTAKOS_AUTH_PROVIDERS_%s' % name.upper()
466

    
467
    def has_global_setting(self, name):
468
        return hasattr(settings, self.get_global_setting_key(name))
469

    
470
    def has_setting(self, name):
471
        return hasattr(settings, self.get_setting_key(name))
472

    
473
    def get_setting(self, name, default=None):
474
        attr = self.get_setting_key(name)
475
        if not self.has_setting(name):
476
            return self.get_global_setting(name, default)
477
        return getattr(settings, attr, default)
478

    
479
    def get_global_setting(self, name, default=None):
480
        attr = self.get_global_setting_key(name)
481
        if not self.has_global_setting(name):
482
            return default
483
        return getattr(settings, attr, default)
484

    
485
    @property
486
    def provider_details(self):
487
        if self._provider_details:
488
            return self._provider_details
489

    
490
        self._provider_details = {}
491

    
492
        if self._instance:
493
            self._provider_details = self._instance.__dict__
494

    
495
        if self.user and self.identifier:
496
            if self.identifier:
497
                try:
498
                    self._provider_details = \
499
                        self.user.get_auth_providers().get(
500
                            module=self.module,
501
                            identifier=self.identifier).__dict__
502
                except Exception:
503
                    return {}
504
        return self._provider_details
505

    
506
    def __getattr__(self, key):
507
        if not key.startswith('get_'):
508
            return super(AuthProvider, self).__getattribute__(key)
509

    
510
        key = key.replace('get_', '')
511
        if key.endswith('_msg'):
512
            return self.get_message(key)
513

    
514
        if key.endswith('_policy'):
515
            return self.get_policy(key.replace('_policy', ''))
516

    
517
        if key.endswith('_url'):
518
            key = key.replace('_url', '')
519
            return self.urls.get(key)
520

    
521
        if key.endswith('_icon'):
522
            key = key.replace('_msg', '_icon')
523
            return settings.MEDIA_URL + self.get_message(key)
524

    
525
        if key.endswith('_setting'):
526
            key = key.replace('_setting', '')
527
            return self.get_message(key)
528

    
529
        if key.endswith('_template'):
530
            key = key.replace('_template', '')
531
            return self.get_template(key)
532

    
533
        return super(AuthProvider, self).__getattribute__(key)
534

    
535
    def is_active(self):
536
        return self.module_enabled
537

    
538
    @property
539
    def log_display(self):
540
        dsp = "%sAuth" % self.module.title()
541
        if self.user:
542
            dsp += "[%s]" % self.user.log_display
543
            if self.identifier:
544
                dsp += '[%s]' % self.identifier
545
                if self._instance and self._instance.pk:
546
                    dsp += '[%d]' % self._instance.pk
547
        return dsp
548

    
549
    def log(self, msg, *args, **kwargs):
550
        level = kwargs.pop('level', logging.INFO)
551
        message = '%s: %s' % (self.log_display, msg)
552
        logger.log(level, message, *args, **kwargs)
553

    
554

    
555
class LocalAuthProvider(AuthProvider):
556
    module = 'local'
557

    
558
    login_view = 'password_change'
559
    remote_authenticate = False
560
    username_key = 'user_email'
561

    
562
    messages = {
563
        'title': _('Classic'),
564
        'login_prompt': _('Classic login (username/password)'),
565
        'login_success': _('Logged in successfully.'),
566
        'method_details': 'Username: {username}',
567
        'logout_success_extra': ' '
568
    }
569

    
570
    policies = {
571
        'limit': 1,
572
        'switch': False
573
    }
574

    
575
    @property
576
    def urls(self):
577
        urls = super(LocalAuthProvider, self).urls
578
        urls['change_password'] = reverse('password_change')
579
        if self.user:
580
            urls['add'] = reverse('password_change')
581
        if self._instance:
582
            urls.update({
583
                'remove': reverse('remove_auth_provider',
584
                                  kwargs={'pk': self._instance.pk})
585
            })
586
            if 'switch' in urls:
587
                del urls['switch']
588
        return urls
589

    
590
    def remove_from_user(self):
591
        super(LocalAuthProvider, self).remove_from_user()
592
        self.user.set_unusable_password()
593
        self.user.save()
594

    
595

    
596
class ShibbolethAuthProvider(AuthProvider):
597
    module = 'shibboleth'
598
    login_view = 'astakos.im.views.target.shibboleth.login'
599
    username_key = 'provider_info_eppn'
600

    
601
    policies = {
602
        'switch': False
603
    }
604

    
605
    messages = {
606
        'title': _('Academic'),
607
        'login_description': _('If you are a student, professor or researcher'
608
                               ' you can login using your academic account.'),
609
        'add_prompt': _('Allows you to login using your Academic '
610
                        'account'),
611
        'method_details': 'Account: {username}',
612
        'logout_success_extra': _('You may still be logged in at your Academic'
613
                                  ' account though. Consider logging out '
614
                                  'from there too by closing all browser '
615
                                  'windows')
616
    }
617

    
618

    
619
class TwitterAuthProvider(AuthProvider):
620
    module = 'twitter'
621
    login_view = 'astakos.im.views.target.twitter.login'
622
    username_key = 'provider_info_screen_name'
623

    
624
    messages = {
625
        'title': _('Twitter'),
626
        'method_details': 'Screen name: {username}',
627
    }
628

    
629

    
630
class GoogleAuthProvider(AuthProvider):
631
    module = 'google'
632
    login_view = 'astakos.im.views.target.google.login'
633
    username_key = 'provider_info_email'
634

    
635
    messages = {
636
        'title': _('Google'),
637
        'method_details': 'Email: {username}',
638
    }
639

    
640

    
641
class LinkedInAuthProvider(AuthProvider):
642
    module = 'linkedin'
643
    login_view = 'astakos.im.views.target.linkedin.login'
644
    username_key = 'provider_info_email'
645

    
646
    messages = {
647
        'title': _('LinkedIn'),
648
        'method_details': 'Email: {username}',
649
    }
650

    
651

    
652
# Utility method
653
def get_provider(module, user_obj=None, identifier=None, **params):
654
    """
655
    Return a provider instance from the auth providers registry.
656
    """
657
    if not module in PROVIDERS:
658
        raise Exception('Invalid auth provider "%s"' % id)
659

    
660
    return PROVIDERS.get(module)(user_obj, identifier, **params)