Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / auth_providers.py @ 1d59653f

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

    
51
class AuthProviderBase(type):
52

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

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

    
67

    
68
class AuthProvider(object):
69

    
70
    __metaclass__ = AuthProviderBase
71

    
72
    module = None
73
    module_active = False
74
    module_enabled = False
75
    one_per_user = False
76

    
77
    def get_message(self, msg, **kwargs):
78
        params = kwargs
79
        params.update({'provider': self.get_title_display})
80

    
81
        override_msg = getattr(self, 'get_%s_message_display' % msg.lower(), None)
82
        msg = 'AUTH_PROVIDER_%s' % msg
83
        return override_msg or getattr(astakos_messages, msg, msg) % params
84

    
85
    def __init__(self, user=None):
86
        self.user = user
87

    
88
    def __getattr__(self, key):
89
        if not key.startswith('get_'):
90
            return super(AuthProvider, self).__getattribute__(key)
91

    
92
        if key.endswith('_display') or key.endswith('template'):
93
            attr = key.replace('_display', '').replace('get_','')
94
            settings_attr = self.get_setting(attr.upper())
95
            if not settings_attr:
96
                return getattr(self, attr)
97
            return settings_attr
98
        else:
99
            return super(AuthProvider, self).__getattr__(key)
100

    
101
    def get_setting(self, name, default=None):
102
        attr = 'ASTAKOS_AUTH_PROVIDER_%s_%s' % (self.module.upper(), name.upper())
103
        attr_sec = 'ASTAKOS_%s_%s' % (self.module.upper(), name.upper())
104
        if not hasattr(settings, attr):
105
            return getattr(settings, attr_sec, default)
106
        return getattr(settings, attr, default)
107

    
108
    def is_available_for_login(self):
109
        """ A user can login using authentication provider"""
110
        return self.is_active() and self.get_setting('CAN_LOGIN',
111
                                                     self.is_active())
112

    
113
    def is_available_for_create(self):
114
        """ A user can create an account using this provider"""
115
        return self.is_active() and self.get_setting('CAN_CREATE',
116
                                                   self.is_active())
117

    
118
    def is_available_for_add(self):
119
        """ A user can assign provider authentication method"""
120
        return self.is_active() and self.get_setting('CAN_ADD',
121
                                                   self.is_active())
122

    
123
    def is_active(self):
124
        return self.module in astakos_settings.IM_MODULES
125

    
126

    
127
class LocalAuthProvider(AuthProvider):
128
    module = 'local'
129
    title = _('Local password')
130
    description = _('Create a local password for your account')
131
    create_prompt =  _('Create an account')
132
    add_prompt =  _('Create a local password for your account')
133

    
134

    
135
    @property
136
    def add_url(self):
137
        return reverse('password_change')
138

    
139
    one_per_user = True
140

    
141
    login_template = 'im/auth/local_login_form.html'
142
    login_prompt_template = 'im/auth/local_login_prompt.html'
143
    signup_prompt_template = 'im/auth/local_signup_prompt.html'
144
    details_tpl = _('You can login to your account using your'
145
                    ' %(auth_backend)s password.')
146

    
147
    @property
148
    def extra_actions(self):
149
        return [(_('Change password'), reverse('password_change')), ]
150

    
151
class LDAPAuthProvider(AuthProvider):
152
    module = 'ldap'
153
    title = _('LDAP credentials')
154
    description = _('Allows you to login using your LDAP credentials')
155

    
156
    one_per_user = True
157

    
158
    login_template = 'im/auth/local_login_form.html'
159
    login_prompt_template = 'im/auth/local_login_prompt.html'
160
    signup_prompt_template = 'im/auth/local_signup_prompt.html'
161
    details_tpl = _('You can login to your account using your'
162
                    ' %(auth_backend)s password.')
163

    
164
class ShibbolethAuthProvider(AuthProvider):
165
    module = 'shibboleth'
166
    title = _('Academic credentials (Shibboleth)')
167
    description = _('Allows you to login to your account using your academic '
168
                    'credentials')
169
    add_prompt = _('Add academic credentials to your account.')
170
    details_tpl = _('Shibboleth account %(identifier)s ('
171
                    '%(affiliation)s affiliation) is connected with your '
172
                    ' account.')
173
    user_title = _('Academic credentials (%(identifier)s)')
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
    description = _('Allows you to login to your account using your twitter '
187
                    'account')
188
    add_prompt = _('Connect with your Twitter account.')
189
    details_tpl = _('Twitter screen name: %(info_screen_name)s')
190
    user_title = _('Twitter (%(info_screen_name)s)')
191

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

    
196
    login_template = 'im/auth/twitter_login.html'
197
    login_prompt_template = 'im/auth/twitter_login_prompt.html'
198

    
199
def get_provider(id, user_obj=None, default=None):
200
    """
201
    Return a provider instance from the auth providers registry.
202
    """
203
    return PROVIDERS.get(id, default)(user_obj)
204