Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (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
from astakos.im import settings as astakos_settings
41

    
42
import logging
43

    
44
logger = logging.getLogger(__name__)
45

    
46
# providers registry
47
PROVIDERS = SortedDict()
48
_PROVIDERS = {}
49

    
50
class AuthProviderBase(type):
51

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

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

    
66

    
67
class AuthProvider(object):
68

    
69
    __metaclass__ = AuthProviderBase
70

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

    
76
    def __init__(self, user=None):
77
        self.user = user
78

    
79
    def __getattr__(self, key):
80
        if not key.startswith('get_'):
81
            return super(AuthProvider, self).__getattr__(key)
82

    
83
        if key.endswith('_display') or key.endswith('template'):
84
            attr = key.replace('_display', '').replace('get_','')
85
            settings_attr = self.get_setting(attr.upper())
86
            if not settings_attr:
87
                return getattr(self, attr)
88
            return settings_attr
89
        else:
90
            return super(AuthProvider, self).__getattr__(key)
91

    
92
    def get_setting(self, name, default=None):
93
        attr = 'ASTAKOS_AUTH_PROVIDER_%s_%s' % (self.module.upper(), name.upper())
94
        return getattr(settings, attr, default)
95

    
96
    def is_available_for_login(self):
97
        """ A user can login using authentication provider"""
98
        return self.is_active() and self.get_setting('CAN_LOGIN',
99
                                                     self.is_active())
100

    
101
    def is_available_for_create(self):
102
        """ A user can create an account using this provider"""
103
        return self.is_active() and self.get_setting('CAN_CREATE',
104
                                                   self.is_active())
105

    
106
    def is_available_for_add(self):
107
        """ A user can assign provider authentication method"""
108
        return self.is_active() and self.get_setting('CAN_ADD',
109
                                                   self.is_active())
110

    
111
    def is_active(self):
112
        return self.module in astakos_settings.IM_MODULES
113

    
114

    
115
class LocalAuthProvider(AuthProvider):
116
    module = 'local'
117
    title = _('Local password')
118
    description = _('Create a local password for your account')
119
    create_prompt =  _('Create an account')
120
    add_prompt =  _('Create a local password for your account')
121

    
122

    
123
    @property
124
    def add_url(self):
125
        return reverse('password_change')
126

    
127
    one_per_user = True
128

    
129
    login_template = 'im/auth/local_login_form.html'
130
    login_prompt_template = 'im/auth/local_login_prompt.html'
131
    signup_prompt_template = 'im/auth/local_signup_prompt.html'
132
    details_tpl = _('You can login to your account using your'
133
                    ' %(auth_backend)s password.')
134

    
135
    @property
136
    def extra_actions(self):
137
        return [(_('Change password'), reverse('password_change')), ]
138

    
139

    
140
class ShibbolethAuthProvider(AuthProvider):
141
    module = 'shibboleth'
142
    title = _('Academic credentials (Shibboleth)')
143
    description = _('Allows you to login to your account using your academic '
144
                    'credentials')
145
    add_prompt = _('Add academic credentials to your account.')
146

    
147
    @property
148
    def add_url(self):
149
        return reverse('astakos.im.target.shibboleth.login')
150

    
151
    login_template = 'im/auth/shibboleth_login.html'
152
    login_prompt_template = 'im/auth/shibboleth_login_prompt.html'
153

    
154

    
155
class TwitterAuthProvider(AuthProvider):
156
    module = 'twitter'
157
    title = _('Twitter')
158
    description = _('Allows you to login to your account using your twitter '
159
                    'account')
160
    add_prompt = _('Connect with your Twitter account.')
161

    
162
    @property
163
    def add_url(self):
164
        return reverse('astakos.im.target.twitter.login')
165

    
166
    login_template = 'im/auth/twitter_login.html'
167
    login_prompt_template = 'im/auth/twitter_login_prompt.html'
168

    
169
def get_provider(id, user_obj=None, default=None):
170
    """
171
    Return a provider instance from the auth providers registry.
172
    """
173
    return PROVIDERS.get(id, default)(user_obj)
174

    
175

    
176
for module in astakos_settings.IM_MODULES:
177
    if module in _PROVIDERS:
178
        PROVIDERS[module] = _PROVIDERS[module]
179