Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / target / shibboleth.py @ d2633501

History | View | Annotate | Download (7.2 kB)

1
# Copyright 2011-2012 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
from django.http import HttpResponseBadRequest
35
from django.utils.translation import ugettext as _
36
from django.contrib import messages
37
from django.template import RequestContext
38
from django.views.decorators.http import require_http_methods
39
from django.db.models import Q
40
from django.core.exceptions import ValidationError
41
from django.http import HttpResponseRedirect
42
from django.core.urlresolvers import reverse
43
from django.utils.http import urlencode
44
from django.shortcuts import get_object_or_404
45

    
46
from urlparse import urlunsplit, urlsplit
47

    
48
from astakos.im.util import prepare_response, get_context, get_invitation
49
from astakos.im.views import requires_anonymous, render_response, \
50
        requires_auth_provider
51
from astakos.im.settings import ENABLE_LOCAL_ACCOUNT_MIGRATION, BASEURL
52

    
53
from astakos.im.models import AstakosUser, PendingThirdPartyUser
54
from astakos.im.forms import LoginForm
55
from astakos.im.activation_backends import get_backend, SimpleBackend
56
from astakos.im import settings
57

    
58
import logging
59

    
60
logger = logging.getLogger(__name__)
61

    
62
class Tokens:
63
    # these are mapped by the Shibboleth SP software
64
    SHIB_EPPN = "HTTP_EPPN" # eduPersonPrincipalName
65
    SHIB_NAME = "HTTP_SHIB_INETORGPERSON_GIVENNAME"
66
    SHIB_SURNAME = "HTTP_SHIB_PERSON_SURNAME"
67
    SHIB_CN = "HTTP_SHIB_PERSON_COMMONNAME"
68
    SHIB_DISPLAYNAME = "HTTP_SHIB_INETORGPERSON_DISPLAYNAME"
69
    SHIB_EP_AFFILIATION = "HTTP_SHIB_EP_AFFILIATION"
70
    SHIB_SESSION_ID = "HTTP_SHIB_SESSION_ID"
71
    SHIB_MAIL = "HTTP_SHIB_MAIL"
72

    
73
@requires_auth_provider('local', login=True)
74
@require_http_methods(["GET", "POST"])
75
def login(
76
    request,
77
    template='im/third_party_check_local.html',
78
    extra_context=None
79
):
80
    extra_context = extra_context or {}
81

    
82
    tokens = request.META
83

    
84
    try:
85
        eppn = tokens.get(Tokens.SHIB_EPPN)
86
        if not eppn:
87
            raise KeyError(_('Missing provider token'))
88
        if Tokens.SHIB_DISPLAYNAME in tokens:
89
            realname = tokens[Tokens.SHIB_DISPLAYNAME]
90
        elif Tokens.SHIB_CN in tokens:
91
            realname = tokens[Tokens.SHIB_CN]
92
        elif Tokens.SHIB_NAME in tokens and Tokens.SHIB_SURNAME in tokens:
93
            realname = tokens[Tokens.SHIB_NAME] + ' ' + tokens[Tokens.SHIB_SURNAME]
94
        else:
95
            raise KeyError(_('Missing provider user information'))
96
    except KeyError, e:
97
        # invalid shibboleth headers, redirect to login, display message
98
        messages.error(request, e)
99
        return HttpResponseRedirect(reverse('login'))
100

    
101
    affiliation = tokens.get(Tokens.SHIB_EP_AFFILIATION, '')
102
    email = tokens.get(Tokens.SHIB_MAIL, '')
103

    
104
    # an existing user accessed the view
105
    if request.user.is_authenticated():
106
        if request.user.has_auth_provider('shibboleth', identifier=eppn):
107
            return HttpResponseRedirect(reverse('edit_profile'))
108

    
109
        # automatically add eppn provider to user
110
        user = request.user
111
        user.add_provider('shibboleth', identifier=eppn)
112
        return HttpResponseRedirect('edit_profile')
113

    
114
    try:
115
        # astakos user exists ?
116
        user = AstakosUser.objects.get_auth_provider_user(
117
            'shibboleth',
118
            identifier=eppn
119
        )
120
        if user.is_active:
121
            # authenticate user
122
            return prepare_response(request,
123
                                    user,
124
                                    request.GET.get('next'),
125
                                    'renew' in request.GET)
126
        elif not user.activation_sent:
127
            message = _('Your request is pending activation')
128
            if not settings.MODERATION_ENABLED:
129
                url = user.get_resend_activation_url()
130
                msg_extra = _('<a href="%s">Resend activation email?</a>') % url
131
                message = message + u' ' + msg_extra
132

    
133
            messages.error(request, message)
134
            return HttpResponseRedirect(reverse('login'))
135

    
136
        else:
137
            message = _(u'Account disabled. Please contact support')
138
            messages.error(request, message)
139
            return HttpResponseRedirect(reverse('login'))
140

    
141
    except AstakosUser.DoesNotExist, e:
142
        # eppn not stored in astakos models, create pending profile
143
        user, created = PendingThirdPartyUser.objects.get_or_create(
144
            third_party_identifier=eppn,
145
            provider='shibboleth',
146
        )
147
        # update pending user
148
        user.realname = realname
149
        user.affiliation = affiliation
150
        user.email = email
151
        user.generate_token()
152
        user.save()
153

    
154
        extra_context['provider'] = 'shibboleth'
155
        extra_context['token'] = user.token
156

    
157
        return render_response(
158
            template,
159
            context_instance=get_context(request, extra_context)
160
        )
161

    
162

    
163
@requires_auth_provider('local', login=True, create=True)
164
@require_http_methods(["GET"])
165
@requires_anonymous
166
def signup(
167
    request,
168
    token,
169
    backend=None,
170
    on_creation_template='im/third_party_registration.html',
171
    extra_context=None):
172

    
173
    extra_context = extra_context or {}
174
    if not token:
175
        return HttpResponseBadRequest(_('Missing key parameter.'))
176

    
177
    pending = get_object_or_404(PendingThirdPartyUser, token=token)
178
    d = pending.__dict__
179
    d.pop('_state', None)
180
    d.pop('id', None)
181
    d.pop('token', None)
182
    d.pop('created', None)
183
    user = AstakosUser(**d)
184

    
185
    try:
186
        backend = backend or get_backend(request)
187
    except ImproperlyConfigured, e:
188
        messages.error(request, e)
189
    else:
190
        extra_context['form'] = backend.get_signup_form(
191
            provider='shibboleth',
192
            instance=user
193
        )
194

    
195
    extra_context['provider'] = 'shibboleth'
196
    extra_context['third_party_token'] = token
197
    return render_response(
198
            on_creation_template,
199
            context_instance=get_context(request, extra_context)
200
    )
201