Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / auth_providers.py @ 3f0d6293

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

    
83
    def get_message(self, msg, **kwargs):
84
        params = kwargs
85
        params.update({'provider': self.get_title_display})
86

    
87
        override_msg = getattr(self, 'get_%s_message_display' % msg.lower(), None)
88
        msg = 'AUTH_PROVIDER_%s' % msg
89
        return override_msg or getattr(astakos_messages, msg, msg) % params
90

    
91
    @property
92
    def add_url(self):
93
        return reverse(self.login_view)
94

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

    
103
        for key in ['one_per_user']:
104
            override = self.get_setting(key)
105
            if override != None:
106
                setattr(self, key, override)
107

    
108
    def __getattr__(self, key):
109
        if not key.startswith('get_'):
110
            return super(AuthProvider, self).__getattribute__(key)
111

    
112
        if key.endswith('_display') or key.endswith('template'):
113
            attr = key.replace('_display', '').replace('get_','')
114
            settings_attr = self.get_setting(attr.upper())
115
            if not settings_attr:
116
                return getattr(self, attr)
117
            return _(settings_attr)
118
        else:
119
            return super(AuthProvider, self).__getattr__(key)
120

    
121
    def get_setting(self, name, default=None):
122
        attr = 'ASTAKOS_AUTH_PROVIDER_%s_%s' % (self.module.upper(), name.upper())
123
        attr_sec = 'ASTAKOS_%s_%s' % (self.module.upper(), name.upper())
124
        if not hasattr(settings, attr):
125
            return getattr(settings, attr_sec, default)
126

    
127
        return getattr(settings, attr, default)
128

    
129
    def is_available_for_login(self):
130
        """ A user can login using authentication provider"""
131
        return self.is_active() and self.get_setting('CAN_LOGIN',
132
                                                     self.is_active())
133

    
134
    def is_available_for_create(self):
135
        """ A user can create an account using this provider"""
136
        return self.is_active() and self.get_setting('CAN_CREATE',
137
                                                   self.is_active())
138

    
139
    def is_available_for_add(self):
140
        """ A user can assign provider authentication method"""
141
        return self.is_active() and self.get_setting('CAN_ADD',
142
                                                   self.is_active())
143

    
144
    def is_required(self):
145
        """Provider required (user cannot remove the last one)"""
146
        return self.is_active() and self.get_setting('REQUIRED', False)
147

    
148
    def is_active(self):
149
        return self.module in astakos_settings.IM_MODULES
150

    
151

    
152
class LocalAuthProvider(AuthProvider):
153
    module = 'local'
154
    title = _('Local password')
155
    description = _('Create a local password for your account')
156
    add_prompt =  _('Create a local password for your account')
157
    login_prompt = _('if you already have a username and password')
158
    signup_prompt = _('New to ~okeanos ?')
159
    signup_link_prompt = _('create an account now')
160
    login_view = 'password_change'
161

    
162
    one_per_user = True
163

    
164
    login_template = 'im/auth/local_login_form.html'
165
    login_prompt_template = 'im/auth/local_login_prompt.html'
166
    signup_prompt_template = 'im/auth/local_signup_prompt.html'
167
    details_tpl = _('You can login to your account using your'
168
                    ' %(auth_backend)s password.')
169

    
170
    @property
171
    def extra_actions(self):
172
        return [(_('Change password'), reverse('password_change')), ]
173

    
174

    
175
class ShibbolethAuthProvider(AuthProvider):
176
    module = 'shibboleth'
177
    title = _('Academic credentials (Shibboleth)')
178
    add_prompt = _('Allows you to login to your account using your academic '
179
                    'account')
180
    details_tpl = _('Shibboleth account \'%(identifier)s\' is connected to your '
181
                    ' account.')
182
    user_title = _('Academic credentials (%(identifier)s)')
183
    primary_login_prompt = _('If you are a student/researcher/faculty you can'
184
                             ' login using your university-credentials in'
185
                             ' the following page')
186
    login_view = 'astakos.im.target.shibboleth.login'
187

    
188
    login_template = 'im/auth/shibboleth_login.html'
189
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
190

    
191

    
192
class TwitterAuthProvider(AuthProvider):
193
    module = 'twitter'
194
    title = _('Twitter')
195
    add_prompt = _('Allows you to login to your account using Twitter')
196
    details_tpl = _('Twitter screen name: %(info_screen_name)s')
197
    user_title = _('Twitter (%(info_screen_name)s)')
198
    login_view = 'astakos.im.target.twitter.login'
199

    
200
    login_template = 'im/auth/third_party_provider_generic_login.html'
201
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
202

    
203

    
204
class GoogleAuthProvider(AuthProvider):
205
    module = 'google'
206
    title = _('Google')
207
    add_prompt = _('Allows you to login to your account using Google')
208
    details_tpl = _('Google account: %(info_email)s')
209
    user_title = _('Google (%(info_email)s)')
210
    login_view = 'astakos.im.target.google.login'
211

    
212
    login_template = 'im/auth/third_party_provider_generic_login.html'
213
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
214

    
215

    
216
class LinkedInAuthProvider(AuthProvider):
217
    module = 'linkedin'
218
    title = _('LinkedIn')
219
    add_prompt = _('Allows you to login to your account using LinkedIn')
220
    user_title = _('LinkedIn (%(info_emailAddress)s)')
221
    details_tpl = _('LinkedIn account: %(info_emailAddress)s')
222
    login_view = 'astakos.im.target.linkedin.login'
223

    
224
    login_template = 'im/auth/third_party_provider_generic_login.html'
225
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
226

    
227

    
228
def get_provider(id, user_obj=None, default=None):
229
    """
230
    Return a provider instance from the auth providers registry.
231
    """
232
    return PROVIDERS.get(id, default)(user_obj)
233