Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / auth_providers.py @ 63836eda

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

    
46
logger = logging.getLogger(__name__)
47

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

    
52
class AuthProviderBase(type):
53

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

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

    
70

    
71
class AuthProvider(object):
72

    
73
    __metaclass__ = AuthProviderBase
74

    
75
    module = None
76
    module_active = False
77
    module_enabled = False
78
    one_per_user = False
79
    login_prompt = _('Login using ')
80
    primary_login_prompt = _('Login using ')
81

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

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

    
90
    def __init__(self, user=None):
91
        self.user = user
92

    
93
    def __getattr__(self, key):
94
        if not key.startswith('get_'):
95
            return super(AuthProvider, self).__getattribute__(key)
96

    
97
        if key.endswith('_display') or key.endswith('template'):
98
            attr = key.replace('_display', '').replace('get_','')
99
            settings_attr = self.get_setting(attr.upper())
100
            if not settings_attr:
101
                return getattr(self, attr)
102
            return _(settings_attr)
103
        else:
104
            return super(AuthProvider, self).__getattr__(key)
105

    
106
    def get_setting(self, name, default=None):
107
        attr = 'ASTAKOS_AUTH_PROVIDER_%s_%s' % (self.module.upper(), name.upper())
108
        attr_sec = 'ASTAKOS_%s_%s' % (self.module.upper(), name.upper())
109
        if not hasattr(settings, attr):
110
            return getattr(settings, attr_sec, default)
111
        return getattr(settings, attr, default)
112

    
113
    def is_available_for_login(self):
114
        """ A user can login using authentication provider"""
115
        return self.is_active() and self.get_setting('CAN_LOGIN',
116
                                                     self.is_active())
117

    
118
    def is_available_for_create(self):
119
        """ A user can create an account using this provider"""
120
        return self.is_active() and self.get_setting('CAN_CREATE',
121
                                                   self.is_active())
122

    
123
    def is_available_for_add(self):
124
        """ A user can assign provider authentication method"""
125
        return self.is_active() and self.get_setting('CAN_ADD',
126
                                                   self.is_active())
127

    
128
    def is_required(self):
129
        """Provider required (user cannot remove the last one)"""
130
        return self.is_active() and self.get_setting('REQUIRED', False)
131

    
132
    def is_active(self):
133
        return self.module in astakos_settings.IM_MODULES
134

    
135

    
136
class LocalAuthProvider(AuthProvider):
137
    module = 'local'
138
    title = _('Local password')
139
    description = _('Create a local password for your account')
140
    add_prompt =  _('Create a local password for your account')
141
    login_prompt = _('if you already have a username and password')
142
    signup_prompt = _('New to ~okeanos ?')
143
    signup_link_prompt = _('create an account now')
144

    
145

    
146
    @property
147
    def add_url(self):
148
        return reverse('password_change')
149

    
150
    one_per_user = True
151

    
152
    login_template = 'im/auth/local_login_form.html'
153
    login_prompt_template = 'im/auth/local_login_prompt.html'
154
    signup_prompt_template = 'im/auth/local_signup_prompt.html'
155
    details_tpl = _('You can login to your account using your'
156
                    ' %(auth_backend)s password.')
157

    
158
    @property
159
    def extra_actions(self):
160
        return [(_('Change password'), reverse('password_change')), ]
161

    
162

    
163
class ShibbolethAuthProvider(AuthProvider):
164
    module = 'shibboleth'
165
    title = _('Academic credentials (Shibboleth)')
166
    add_prompt = _('Allows you to login to your account using your academic '
167
                    'account')
168
    details_tpl = _('Shibboleth account \'%(identifier)s\' is connected to your '
169
                    ' account.')
170
    user_title = _('Academic credentials (%(identifier)s)')
171
    primary_login_prompt = _('If you are a student/researcher/faculty you can'
172
                             ' login using your university-credentials in'
173
                             ' the following page')
174

    
175
    @property
176
    def add_url(self):
177
        return reverse('astakos.im.target.shibboleth.login')
178

    
179
    login_template = 'im/auth/shibboleth_login.html'
180
    login_prompt_template = 'im/auth/shibboleth_login_prompt.html'
181

    
182

    
183
class TwitterAuthProvider(AuthProvider):
184
    module = 'twitter'
185
    title = _('Twitter')
186
    add_prompt = _('Allows you to login to your account using Twitter')
187
    details_tpl = _('Twitter screen name: %(info_screen_name)s')
188
    user_title = _('Twitter (%(info_screen_name)s)')
189

    
190
    @property
191
    def add_url(self):
192
        return reverse('astakos.im.target.twitter.login')
193

    
194
    login_template = 'im/auth/third_party_provider_generic_login.html'
195
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
196

    
197

    
198
class GoogleAuthProvider(AuthProvider):
199
    module = 'google'
200
    title = _('Google')
201
    add_prompt = _('Allows you to login to your account using Google')
202
    details_tpl = _('Google account: %(info_email)s')
203
    user_title = _('Google (%(info_email)s)')
204

    
205
    @property
206
    def add_url(self):
207
        return reverse('astakos.im.target.google.login')
208

    
209
    login_template = 'im/auth/third_party_provider_generic_login.html'
210
    login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
211

    
212

    
213
class LinkedInAuthProvider(AuthProvider):
214
    module = 'linkedin'
215
    title = _('LinkedIn')
216
    add_prompt = _('Allows you to login to your account using LinkedIn')
217
    user_title = _('LinkedIn (%(info_emailAddress)s)')
218
    details_tpl = _('LinkedIn account: %(info_emailAddress)s')
219

    
220
    @property
221
    def add_url(self):
222
        return reverse('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