Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / views / target / shibboleth.py @ 412048af

History | View | Annotate | Download (7.6 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.conf import settings as global_settings
35
from django.utils.translation import ugettext as _
36
from django.contrib import messages
37
from django.views.decorators.http import require_http_methods
38
from django.http import HttpResponseRedirect
39

    
40
from astakos.im.util import login_url
41
from astakos.im.models import AstakosUser, AstakosUserAuthProvider, \
42
    PendingThirdPartyUser
43
from astakos.im import settings
44
from astakos.im.views.target import get_pending_key, \
45
    handle_third_party_signup, handle_third_party_login, \
46
    init_third_party_session
47
from astakos.im.views.decorators import cookie_fix, requires_auth_provider
48

    
49
import astakos.im.messages as astakos_messages
50
import logging
51

    
52
logger = logging.getLogger(__name__)
53

    
54

    
55
def migrate_eppn_to_remote_id(eppn, remote_id):
56
    """
57
    Retrieve active and pending accounts that are associated with shibboleth
58
    using EPPN as the third party unique identifier update them by storing
59
    REMOTE_USER value instead.
60
    """
61
    if eppn == remote_id:
62
        return
63

    
64
    try:
65
        provider = AstakosUserAuthProvider.objects.get(module='shibboleth',
66
                                                       identifier=eppn)
67
        msg = "Migrating user %r eppn (%s -> %s)"
68
        logger.info(msg, provider.user.log_display, eppn, remote_id)
69
        provider.identifier = remote_id
70
        provider.save()
71
    except AstakosUserAuthProvider.DoesNotExist:
72
        pass
73

    
74
    pending_users = \
75
        PendingThirdPartyUser.objects.filter(third_party_identifier=eppn,
76
                                             provider='shibboleth')
77

    
78
    for pending in pending_users:
79
        msg = "Migrating pending user %s eppn (%s -> %s)"
80
        logger.info(msg, pending.email, eppn, remote_id)
81
        pending.third_party_identifier = remote_id
82
        pending.save()
83

    
84
    return remote_id
85

    
86

    
87
class Tokens:
88
    # these are mapped by the Shibboleth SP software
89
    SHIB_EPPN = "HTTP_EPPN"  # eduPersonPrincipalName
90
    SHIB_NAME = "HTTP_SHIB_INETORGPERSON_GIVENNAME"
91
    SHIB_SURNAME = "HTTP_SHIB_PERSON_SURNAME"
92
    SHIB_CN = "HTTP_SHIB_PERSON_COMMONNAME"
93
    SHIB_DISPLAYNAME = "HTTP_SHIB_INETORGPERSON_DISPLAYNAME"
94
    SHIB_EP_AFFILIATION = "HTTP_SHIB_EP_AFFILIATION"
95
    SHIB_SESSION_ID = "HTTP_SHIB_SESSION_ID"
96
    SHIB_MAIL = "HTTP_SHIB_MAIL"
97
    SHIB_REMOTE_USER = "HTTP_REMOTE_USER"
98

    
99

    
100
@requires_auth_provider('shibboleth')
101
@require_http_methods(["GET", "POST"])
102
@cookie_fix
103
def login(request,
104
          template='im/third_party_check_local.html',
105
          extra_context=None):
106

    
107
    init_third_party_session(request)
108
    extra_context = extra_context or {}
109

    
110
    tokens = request.META
111
    third_party_key = get_pending_key(request)
112

    
113
    shibboleth_headers = {}
114
    for token in dir(Tokens):
115
        if token == token.upper():
116
            shibboleth_headers[token] = request.META.get(getattr(Tokens,
117
                                                                 token),
118
                                                         'NOT_SET')
119
            # also include arbitrary shibboleth headers
120
            for key in request.META.keys():
121
                if key.startswith('HTTP_SHIB_'):
122
                    shibboleth_headers[key.replace('HTTP_', '')] = \
123
                        request.META.get(key)
124

    
125
    # log shibboleth headers
126
    # TODO: info -> debug
127
    logger.info("shibboleth request: %r" % shibboleth_headers)
128

    
129
    try:
130
        eppn = tokens.get(Tokens.SHIB_EPPN, None)
131
        user_id = tokens.get(Tokens.SHIB_REMOTE_USER)
132
        fullname, first_name, last_name, email = None, None, None, None
133
        if global_settings.DEBUG and not eppn:
134
            user_id = getattr(global_settings, 'SHIBBOLETH_TEST_REMOTE_USER',
135
                              None)
136
            eppn = getattr(global_settings, 'SHIBBOLETH_TEST_EPPN', None)
137
            fullname = getattr(global_settings, 'SHIBBOLETH_TEST_FULLNAME',
138
                               None)
139

    
140
        if not user_id:
141
            raise KeyError(_(astakos_messages.SHIBBOLETH_MISSING_USER_ID) % {
142
                'domain': settings.BASE_HOST,
143
                'contact_email': settings.CONTACT_EMAIL
144
            })
145
        if Tokens.SHIB_DISPLAYNAME in tokens:
146
            fullname = tokens[Tokens.SHIB_DISPLAYNAME]
147
        elif Tokens.SHIB_CN in tokens:
148
            fullname = tokens[Tokens.SHIB_CN]
149
        if Tokens.SHIB_NAME in tokens:
150
            first_name = tokens[Tokens.SHIB_NAME]
151
        if Tokens.SHIB_SURNAME in tokens:
152
            last_name = tokens[Tokens.SHIB_SURNAME]
153

    
154
        if fullname:
155
            splitted = fullname.split(' ', 1)
156
            if len(splitted) == 2:
157
                first_name, last_name = splitted
158
        fullname = '%s %s' % (first_name, last_name)
159

    
160
        if not any([first_name, last_name]) and \
161
                    settings.SHIBBOLETH_REQUIRE_NAME_INFO:
162
            raise KeyError(_(astakos_messages.SHIBBOLETH_MISSING_NAME))
163

    
164
    except KeyError, e:
165
        # invalid shibboleth headers, redirect to login, display message
166
        logger.exception(e)
167
        messages.error(request, e.message)
168
        return HttpResponseRedirect(login_url(request))
169

    
170
    if settings.SHIBBOLETH_MIGRATE_EPPN:
171
        migrate_eppn_to_remote_id(eppn, user_id)
172

    
173
    affiliation = tokens.get(Tokens.SHIB_EP_AFFILIATION, 'Shibboleth')
174
    email = tokens.get(Tokens.SHIB_MAIL, '')
175
    provider_info = {'eppn': eppn, 'email': email, 'name': fullname,
176
                     'headers': shibboleth_headers, 'user_id': user_id}
177

    
178
    try:
179
        return handle_third_party_login(request, 'shibboleth',
180
                                        user_id, provider_info,
181
                                        affiliation, third_party_key)
182
    except AstakosUser.DoesNotExist, e:
183
        third_party_key = get_pending_key(request)
184
        user_info = {'affiliation': affiliation,
185
                     'first_name': first_name,
186
                     'last_name': last_name,
187
                     'email': email}
188
        return handle_third_party_signup(request, user_id, 'shibboleth',
189
                                         third_party_key,
190
                                         provider_info,
191
                                         user_info,
192
                                         template,
193
                                         extra_context)