Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (5.9 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

    
35
from django.core.urlresolvers import reverse
36
from django.utils.translation import ugettext as _
37
from django.utils.datastructures import SortedDict
38

    
39
from django.conf import settings
40
from astakos.im import settings as astakos_settings
41

    
42
import logging
43

    
44
logger = logging.getLogger(__name__)
45

    
46
# providers registry
47
PROVIDERS = {}
48

    
49
class AuthProviderBase(type):
50

    
51
    def __new__(cls, name, bases, dct):
52
        include = False
53
        if [b for b in bases if isinstance(b, AuthProviderBase)]:
54
            type_id = dct.get('module')
55
            if type_id:
56
                include = True
57
            if type_id in astakos_settings.IM_MODULES:
58
                dct['module_enabled'] = True
59

    
60
        newcls = super(AuthProviderBase, cls).__new__(cls, name, bases, dct)
61
        if include:
62
            PROVIDERS[type_id] = newcls
63
        return newcls
64

    
65

    
66
class AuthProvider(object):
67

    
68
    __metaclass__ = AuthProviderBase
69

    
70
    module = None
71
    module_active = False
72
    module_enabled = False
73
    one_per_user = False
74

    
75
    def __init__(self, user=None):
76
        self.user = user
77

    
78
    def __getattr__(self, key):
79
        if not key.startswith('get_'):
80
            return super(AuthProvider, self).__getattr__(key)
81

    
82
        if key.endswith('_display') or key.endswith('template'):
83
            attr = key.replace('_display', '').replace('get_','')
84
            settings_attr = self.get_setting(attr.upper())
85
            if not settings_attr:
86
                return getattr(self, attr)
87
            return settings_attr
88
        else:
89
            return super(AuthProvider, self).__getattr__(key)
90

    
91
    def get_setting(self, name, default=None):
92
        attr = 'ASTAKOS_AUTH_PROVIDER_%s_%s' % (self.module.upper(), name.upper())
93
        return getattr(settings, attr, default)
94

    
95
    def is_available_for_login(self):
96
        """ A user can login using authentication provider"""
97
        return self.is_active() and self.get_setting('CAN_LOGIN',
98
                                                     self.is_active())
99

    
100
    def is_available_for_create(self):
101
        """ A user can create an account using this provider"""
102
        return self.is_active() and self.get_setting('CAN_CREATE',
103
                                                   self.is_active())
104

    
105
    def is_available_for_add(self):
106
        """ A user can assign provider authentication method"""
107
        return self.is_active() and self.get_setting('CAN_ADD',
108
                                                   self.is_active())
109

    
110
    def is_active(self):
111
        return self.module in astakos_settings.IM_MODULES
112

    
113

    
114
class LocalAuthProvider(AuthProvider):
115
    module = 'local'
116
    title = _('Local password')
117
    description = _('Create a local password for your account')
118
    create_prompt =  _('Create an account')
119
    add_prompt =  _('Create a local password for your account')
120

    
121

    
122
    @property
123
    def add_url(self):
124
        return reverse('password_change')
125

    
126
    one_per_user = True
127

    
128
    login_template = 'im/auth/local_login_form.html'
129
    login_prompt_template = 'im/auth/local_login_prompt.html'
130
    signup_prompt_template = 'im/auth/local_signup_prompt.html'
131
    details_tpl = _('You can login to your account using your'
132
                    ' %(auth_backend)s password.')
133

    
134
    @property
135
    def extra_actions(self):
136
        return [(_('Change password'), reverse('password_change')), ]
137

    
138

    
139
class ShibbolethAuthProvider(AuthProvider):
140
    module = 'shibboleth'
141
    title = _('Academic credentials (Shibboleth)')
142
    description = _('Allows you to login to your account using your academic '
143
                    'credentials')
144
    add_prompt = _('Add academic credentials to your account.')
145

    
146
    @property
147
    def add_url(self):
148
        return reverse('astakos.im.target.shibboleth.login')
149

    
150
    login_template = 'im/auth/shibboleth_login.html'
151
    login_prompt_template = 'im/auth/shibboleth_login_prompt.html'
152

    
153

    
154
class TwitterAuthProvider(AuthProvider):
155
    module = 'twitter'
156
    title = _('Twitter')
157
    description = _('Allows you to login to your account using your twitter '
158
                    'account')
159
    add_prompt = _('Connect with your Twitter account.')
160

    
161
    @property
162
    def add_url(self):
163
        return reverse('astakos.im.target.twitter.login')
164

    
165
    login_template = 'im/auth/twitter_login.html'
166
    login_prompt_template = 'im/auth/twitter_login_prompt.html'
167

    
168
def get_provider(id, user_obj=None, default=None):
169
    """
170
    Return a provider instance from the auth providers registry.
171
    """
172
    return PROVIDERS.get(id, default)(user_obj)
173