Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / auth_providers.py @ b9231ded

History | View | Annotate | Download (7.5 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
    login_prompt = _('Login using')
77

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

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

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

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

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

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

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

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

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

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

    
127

    
128
class LocalAuthProvider(AuthProvider):
129
    module = 'local'
130
    title = _('Local password')
131
    description = _('Create a local password for your account')
132
    create_prompt =  _('Create an account')
133
    add_prompt =  _('Create a local password for your account')
134
    login_prompt = _('if you already have a username and password')
135
    signup_prompt = _('New to ~Okeanos ?')
136

    
137

    
138
    @property
139
    def add_url(self):
140
        return reverse('password_change')
141

    
142
    one_per_user = True
143

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

    
150
    @property
151
    def extra_actions(self):
152
        return [(_('Change password'), reverse('password_change')), ]
153

    
154
class LDAPAuthProvider(AuthProvider):
155
    module = 'ldap'
156
    title = _('LDAP credentials')
157
    description = _('Allows you to login using your LDAP credentials')
158

    
159
    one_per_user = True
160

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

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

    
180
    @property
181
    def add_url(self):
182
        return reverse('astakos.im.target.shibboleth.login')
183

    
184
    login_template = 'im/auth/shibboleth_login.html'
185
    login_prompt_template = 'im/auth/shibboleth_login_prompt.html'
186

    
187

    
188
class TwitterAuthProvider(AuthProvider):
189
    module = 'twitter'
190
    title = _('Twitter')
191
    description = _('Allows you to login to your account using your twitter '
192
                    'account')
193
    add_prompt = _('Connect with your Twitter account.')
194
    details_tpl = _('Twitter screen name: %(info_screen_name)s')
195
    user_title = _('Twitter (%(info_screen_name)s)')
196

    
197
    @property
198
    def add_url(self):
199
        return reverse('astakos.im.target.twitter.login')
200

    
201
    login_template = 'im/auth/twitter_login.html'
202
    login_prompt_template = 'im/auth/twitter_login_prompt.html'
203

    
204
def get_provider(id, user_obj=None, default=None):
205
    """
206
    Return a provider instance from the auth providers registry.
207
    """
208
    return PROVIDERS.get(id, default)(user_obj)
209