Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / auth_providers.py @ 01223f04

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

    
41
from astakos.im import settings as astakos_settings
42
from astakos.im import messages as astakos_messages
43

    
44
import logging
45
import urllib
46

    
47
logger = logging.getLogger(__name__)
48

    
49
# providers registry
50
PROVIDERS = {}
51
REQUIRED_PROVIDERS = {}
52

    
53
class AuthProviderBase(type):
54

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

    
64
        newcls = super(AuthProviderBase, cls).__new__(cls, name, bases, dct)
65
        if include:
66
            PROVIDERS[type_id] = newcls
67
            if newcls().is_required():
68
                REQUIRED_PROVIDERS[type_id] = newcls
69
        return newcls
70

    
71

    
72
class AuthProvider(object):
73

    
74
    __metaclass__ = AuthProviderBase
75

    
76
    module = None
77
    module_active = False
78
    module_enabled = False
79
    one_per_user = False
80
    login_prompt = _('Login using ')
81
    primary_login_prompt = _('Login using ')
82
    login_message = None
83
    logout_message = 'You may still be logged in at "%(provider)s". Consider logging out.'
84
    remote_authenticate = True
85
    remote_logout_url = None
86

    
87
    def get_message(self, msg, **kwargs):
88
        params = kwargs
89
        params.update({'provider': self.get_title_display})
90

    
91
        override_msg = getattr(self, 'get_%s_message_display' % msg.lower(), None)
92
        msg = 'AUTH_PROVIDER_%s' % msg
93
        return override_msg or getattr(astakos_messages, msg, msg) % params
94

    
95
    @property
96
    def add_url(self):
97
        return reverse(self.login_view)
98

    
99
    def __init__(self, user=None):
100
        self.user = user
101
        for tpl in ['login_prompt', 'login', 'signup_prompt']:
102
            tpl_name = '%s_%s' % (tpl, 'template')
103
            override = self.get_setting(tpl_name)
104
            if override:
105
                setattr(self, tpl_name, override)
106

    
107
        for key in ['one_per_user']:
108
            override = self.get_setting(key)
109
            if override != None:
110
                setattr(self, key, override)
111

    
112
        self.login_message = self.login_message or self.get_title_display
113
        if self.logout_message and "%" in self.logout_message:
114
            self.logout_message = self.logout_message % {'provider':
115
                                                         self.get_login_message_display}
116
        else:
117
            self.logout_message = self.logout_message or ''
118

    
119
    def __getattr__(self, key):
120
        if not key.startswith('get_'):
121
            return super(AuthProvider, self).__getattribute__(key)
122

    
123
        if key.endswith('_display') or key.endswith('template'):
124
            attr = key.replace('_display', '').replace('get_','')
125
            settings_attr = self.get_setting(attr.upper())
126
            if not settings_attr:
127
                return getattr(self, attr)
128
            return _(settings_attr)
129
        else:
130
            return super(AuthProvider, self).__getattr__(key)
131

    
132
    def get_logout_message(self):
133
        content = ''
134
        if self.remote_logout_url:
135
            content = '<a href="%s" title="Logout from %%s"></a>' % self.remote_logou_url
136
        return content % (self.get_logout_message_display % self.get_title_display)
137

    
138
    def get_setting(self, name, default=None):
139
        attr = 'ASTAKOS_AUTH_PROVIDER_%s_%s' % (self.module.upper(), name.upper())
140
        attr_sec = 'ASTAKOS_%s_%s' % (self.module.upper(), name.upper())
141
        if not hasattr(settings, attr):
142
            return getattr(settings, attr_sec, default)
143

    
144
        return getattr(settings, attr, default)
145

    
146
    def is_available_for_login(self):
147
        """ A user can login using authentication provider"""
148
        return self.is_active() and self.get_setting('CAN_LOGIN',
149
                                                     self.is_active())
150

    
151
    def is_available_for_create(self):
152
        """ A user can create an account using this provider"""
153
        return self.is_active() and self.get_setting('CAN_CREATE',
154
                                                   self.is_active())
155

    
156
    def is_available_for_add(self):
157
        """ A user can assign provider authentication method"""
158
        return self.is_active() and self.get_setting('CAN_ADD',
159
                                                   self.is_active())
160

    
161
    def is_required(self):
162
        """Provider required (user cannot remove the last one)"""
163
        return self.is_active() and self.get_setting('REQUIRED', False)
164

    
165
    def is_active(self):
166
        return self.module in astakos_settings.IM_MODULES
167

    
168

    
169
class LocalAuthProvider(AuthProvider):
170
    module = 'local'
171
    title = _('Local password')
172
    description = _('Create a local password for your account')
173
    add_prompt =  _('Create a local password for your account')
174
    login_prompt = _('if you already have a username and password')
175
    signup_prompt = _('New to ~okeanos ?')
176
    signup_link_prompt = _('create an account now')
177
    login_view = 'password_change'
178
    remote_authenticate = False
179
    logout_message = ''
180

    
181
    one_per_user = True
182

    
183
    login_template = 'im/auth/local_login_form.html'
184
    login_prompt_template = 'im/auth/local_login_prompt.html'
185
    signup_prompt_template = 'im/auth/local_signup_prompt.html'
186
    details_tpl = _('You can login to your account using your'
187
                    ' %(auth_backend)s password.')
188

    
189
    @property
190
    def extra_actions(self):
191
        return [(_('Change password'), reverse('password_change')), ]
192

    
193

    
194
class ShibbolethAuthProvider(AuthProvider):
195
    module = 'shibboleth'
196
    title = _('Academic credentials (Shibboleth)')
197
    add_prompt = _('Allows you to login to your account using your academic '
198
                    'account')
199
    details_tpl = _('Shibboleth account \'%(identifier)s\' is connected to your '
200
                    ' account.')
201
    user_title = _('Academic credentials (%(identifier)s)')
202
    primary_login_prompt = _('If you are a student/researcher/faculty you can'
203
                             ' login using your university-credentials in'
204
                             ' the following page')
205
    login_view = 'astakos.im.target.shibboleth.login'
206

    
207
    login_template = 'im/auth/shibboleth_login.html'
208
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
209

    
210

    
211
class TwitterAuthProvider(AuthProvider):
212
    module = 'twitter'
213
    title = _('Twitter')
214
    add_prompt = _('Allows you to login to your account using Twitter')
215
    details_tpl = _('Twitter screen name: %(info_screen_name)s')
216
    user_title = _('Twitter (%(info_screen_name)s)')
217
    login_view = 'astakos.im.target.twitter.login'
218

    
219
    login_template = 'im/auth/third_party_provider_generic_login.html'
220
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
221

    
222

    
223
class GoogleAuthProvider(AuthProvider):
224
    module = 'google'
225
    title = _('Google')
226
    add_prompt = _('Allows you to login to your account using Google')
227
    details_tpl = _('Google account: %(info_email)s')
228
    user_title = _('Google (%(info_email)s)')
229
    login_view = 'astakos.im.target.google.login'
230

    
231
    login_template = 'im/auth/third_party_provider_generic_login.html'
232
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
233

    
234

    
235
class LinkedInAuthProvider(AuthProvider):
236
    module = 'linkedin'
237
    title = _('LinkedIn')
238
    add_prompt = _('Allows you to login to your account using LinkedIn')
239
    user_title = _('LinkedIn (%(info_emailAddress)s)')
240
    details_tpl = _('LinkedIn account: %(info_emailAddress)s')
241
    login_view = 'astakos.im.target.linkedin.login'
242

    
243
    login_template = 'im/auth/third_party_provider_generic_login.html'
244
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
245

    
246

    
247
def get_provider(id, user_obj=None, default=None):
248
    """
249
    Return a provider instance from the auth providers registry.
250
    """
251
    return PROVIDERS.get(id, default)(user_obj)
252