Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / auth_providers.py @ 469d0997

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

    
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 = True
80
    login_prompt = _('Login using ')
81
    primary_login_prompt = _('Login using ')
82
    login_message = None
83
    logout_message = 'You may still be logged in %(provider)s though. Consider logging out from there too.'
84
    remote_authenticate = True
85
    remote_logout_url = None
86
    logout_from_provider_text = None
87
    icon_url = None
88
    icon_medium_url = None
89
    method_prompt = None
90

    
91
    def get_message(self, msg, **kwargs):
92
        params = kwargs
93
        params.update({'provider': self.get_title_display})
94

    
95
        override_msg = getattr(self, 'get_%s_message_display' % msg.lower(), None)
96
        msg = 'AUTH_PROVIDER_%s' % msg
97
        return override_msg or getattr(astakos_messages, msg, msg) % params
98

    
99
    @property
100
    def add_url(self):
101
        return reverse(self.login_view)
102

    
103
    @property
104
    def provider_details(self):
105
        if self.user:
106
            if self.identifier:
107
                self._provider_details = \
108
                    self.user.get_auth_providers().get(module=self.module,
109
                                                       identifier=self.identifier).__dict__
110
            else:
111
                self._provider_details = self.user.get(module=self.module).__dict__
112
        return self._provider_details
113

    
114
    def __init__(self, user=None, identifier=None, provider_details=None):
115
        self.user = user
116
        self.identifier = identifier
117

    
118
        self._provider_details = None
119
        if provider_details:
120
            self._provider_details = provider_details
121

    
122
        for tpl in ['login_prompt', 'login', 'signup_prompt']:
123
            tpl_name = '%s_%s' % (tpl, 'template')
124
            override = self.get_setting(tpl_name)
125
            if override:
126
                setattr(self, tpl_name, override)
127

    
128
        for key in ['one_per_user']:
129
            override = self.get_setting(key)
130
            if override != None:
131
                setattr(self, key, override)
132

    
133
        self.login_message = self.login_message or self.get_title_display
134
        if self.logout_message and "%" in self.logout_message:
135
            logout_text_display = self.logout_from_provider_text or 'at %s' % self.get_title_display
136
            self.logout_message = self.logout_message % {'provider':
137
                                                         logout_text_display}
138
        else:
139
            self.logout_message = self.logout_message or ''
140

    
141
        if not self.icon_url:
142
            self.icon_url = '%s%s' % (settings.MEDIA_URL, 'im/auth/icons/%s.png' %
143
                                       self.module.lower())
144

    
145
        if not self.icon_medium_url:
146
            self.icon_medium_url = '%s%s' % (settings.MEDIA_URL, 'im/auth/icons-medium/%s.png' %
147
                                       self.module.lower())
148

    
149
        if not self.method_prompt:
150
            self.method_prompt = _('%s login method') % self.get_title_display
151

    
152
    def __getattr__(self, key):
153
        if not key.startswith('get_'):
154
            return super(AuthProvider, self).__getattribute__(key)
155

    
156
        if key.endswith('_display') or key.endswith('template'):
157
            attr = key.replace('_display', '').replace('get_','')
158
            settings_attr = self.get_setting(attr.upper())
159
            if not settings_attr:
160
                return getattr(self, attr)
161
            return _(settings_attr)
162
        else:
163
            return super(AuthProvider, self).__getattr__(key)
164

    
165
    def get_logout_message(self):
166
        content = ''
167
        if self.remote_logout_url:
168
            content = '<a href="%s" title="Logout from %%s"></a>' % self.remote_logou_url
169
        return content % (self.get_logout_message_display % self.get_title_display)
170

    
171
    def get_setting(self, name, default=None):
172
        attr = 'ASTAKOS_AUTH_PROVIDER_%s_%s' % (self.module.upper(), name.upper())
173
        attr_sec = 'ASTAKOS_%s_%s' % (self.module.upper(), name.upper())
174
        if not hasattr(settings, attr):
175
            return getattr(settings, attr_sec, default)
176

    
177
        return getattr(settings, attr, default)
178

    
179
    def is_available_for_remove(self):
180
        return self.is_active() and self.get_setting('CAN_REMOVE', True)
181

    
182
    def is_available_for_login(self):
183
        """ A user can login using authentication provider"""
184
        return self.is_active() and self.get_setting('CAN_LOGIN',
185
                                                     self.is_active())
186

    
187
    def is_available_for_create(self):
188
        """ A user can create an account using this provider"""
189
        return self.is_active() and self.get_setting('CAN_CREATE',
190
                                                   self.is_active())
191

    
192
    def is_available_for_add(self):
193
        """ A user can assign provider authentication method"""
194
        return self.is_active() and self.get_setting('CAN_ADD',
195
                                                   self.is_active())
196

    
197
    def is_required(self):
198
        """Provider required (user cannot remove the last one)"""
199
        return self.is_active() and self.get_setting('REQUIRED', False)
200

    
201
    def is_active(self):
202
        return self.module in astakos_settings.IM_MODULES
203

    
204

    
205
class LocalAuthProvider(AuthProvider):
206
    module = 'local'
207
    title = _('Local password')
208
    description = _('Create a local password for your account')
209
    add_prompt =  _('Enable Classic login for your account')
210
    details_tpl = _('Username: %(username)s')
211
    login_prompt = _('Classic login (username/password)')
212
    signup_prompt = _('New to ~okeanos ?')
213
    signup_link_prompt = _('create an account now')
214
    login_view = 'password_change'
215
    remote_authenticate = False
216
    logout_message = ''
217

    
218
    one_per_user = True
219

    
220
    login_template = 'im/auth/local_login_form.html'
221
    login_prompt_template = 'im/auth/local_login_prompt.html'
222
    signup_prompt_template = 'im/auth/local_signup_prompt.html'
223

    
224
    @property
225
    def extra_actions(self):
226
        return [(_('Change password'), reverse('password_change')), ]
227

    
228

    
229
class ShibbolethAuthProvider(AuthProvider):
230
    module = 'shibboleth'
231
    title = _('Academic account')
232
    add_prompt = _('Enable Academic login for your account')
233
    details_tpl = _('Identifier: %(identifier)s')
234
    user_title = _('Academic account (%(identifier)s)')
235
    primary_login_prompt = _('If you are a student, professor or researcher you '
236
                             'can login using your academic account.')
237
    login_view = 'astakos.im.target.shibboleth.login'
238

    
239
    login_template = 'im/auth/shibboleth_login.html'
240
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
241
    logout_from_provider_text = 'Please close all browser windows to complete logout from your Academic account, too.'
242

    
243
    method_prompt = _('Academic account')
244

    
245

    
246
class TwitterAuthProvider(AuthProvider):
247
    module = 'twitter'
248
    title = _('Twitter')
249
    add_prompt = _('Enable Twitter login for your account')
250
    details_tpl = _('Username: %(info_screen_name)s')
251
    user_title = _('Twitter (%(info_screen_name)s)')
252
    login_view = 'astakos.im.target.twitter.login'
253

    
254
    login_template = 'im/auth/third_party_provider_generic_login.html'
255
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
256

    
257

    
258
class GoogleAuthProvider(AuthProvider):
259
    module = 'google'
260
    title = _('Google')
261
    add_prompt = _('Enable Google login for your account')
262
    details_tpl = _('Email: %(info_email)s')
263
    user_title = _('Google (%(info_email)s)')
264
    login_view = 'astakos.im.target.google.login'
265

    
266
    login_template = 'im/auth/third_party_provider_generic_login.html'
267
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
268

    
269

    
270
class LinkedInAuthProvider(AuthProvider):
271
    module = 'linkedin'
272
    title = _('LinkedIn')
273
    add_prompt = _('Enable LinkedIn login for your account')
274
    details_tpl = _('Email: %(info_emailAddress)s')
275
    user_title = _('LinkedIn (%(info_emailAddress)s)')
276
    login_view = 'astakos.im.target.linkedin.login'
277

    
278
    login_template = 'im/auth/third_party_provider_generic_login.html'
279
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
280

    
281

    
282
def get_provider(id, user_obj=None, default=None, identifier=None, provider_details={}):
283
    """
284
    Return a provider instance from the auth providers registry.
285
    """
286
    if not id in PROVIDERS:
287
        raise Exception('Invalid auth provider requested "%s"' % id)
288

    
289
    return PROVIDERS.get(id, default)(user_obj, identifier, provider_details)
290