Project

General

Profile

Download (6.73 KB) Statistics
| Branch: | Tag: | Revision:

oidc / ckanext / ozwillo_pyoidc / plugin.py @ 6388360c

1
import logging
2
from routes import redirect_to, url_for
3

    
4
import ckan.plugins as plugins
5
import ckan.plugins.toolkit as toolkit
6
from ckan.common import session, c, request, response
7
from ckan import model
8
import ckan.lib.base as base
9

    
10
from pylons import config
11

    
12
import conf
13
from oidc import create_client
14

    
15
plugin_config_prefix = 'ckanext.ozwillo_pyoidc.'
16

    
17
log = logging.getLogger(__name__)
18
plugin_controller = __name__ + ':OpenidController'
19

    
20
_CLIENTS = {}
21

    
22
class Clients(object):
23

    
24
    @classmethod
25
    def get(cls, g):
26
        global _CLIENTS
27
        if g.id in _CLIENTS:
28
            return _CLIENTS.get(g.id)
29
        client = cls().get_client(g)
30
        _CLIENTS.update({g.id: client})
31
        return client
32

    
33
    def get_client(self, g):
34
        params = conf.CLIENT.copy()
35
        params['client_registration'].update({
36
            'client_id': g._extras['client_id'].value,
37
            'client_secret': g._extras['client_secret'].value,
38
            'redirect_uris': [url_for(host=request.host,
39
                                      controller=plugin_controller,
40
                                      action='callback',
41
                                      id=g.name,
42
                                      qualified=True)]
43
        })
44
        return create_client(**params)
45

    
46

    
47
class OzwilloPyoidcPlugin(plugins.SingletonPlugin):
48
    plugins.implements(plugins.IConfigurer)
49
    plugins.implements(plugins.IRoutes)
50
    plugins.implements(plugins.IAuthenticator, inherit=True)
51

    
52
    def before_map(self, map):
53
        map.connect('/organization/{id:.*}/sso',
54
                    controller=plugin_controller,
55
                    action='sso')
56
        map.connect('/organization/{id:.*}/callback',
57
                    controller=plugin_controller,
58
                    action='callback')
59
        map.connect('/logout', controller=plugin_controller,
60
                    action='logout')
61
        map.connect('/user/slo',
62
                    controller=plugin_controller,
63
                    action='slo',
64
                    conditions={'method': ['POST']})
65
        map.redirect('/organization/{id:.*}/logout', '/user/_logout')
66

    
67
        return map
68

    
69
    def after_map(self, map):
70
        return map
71

    
72
    def identify(self):
73
        user = session.get('user')
74
        if user and not toolkit.c.userobj:
75
            userobj = model.User.get(user)
76
            toolkit.c.user = userobj.name
77
            toolkit.c.userobj = userobj
78

    
79
    def login(self):
80
        for cookie in request.cookies:
81
            value = request.cookies.get(cookie)
82
            response.set_cookie(cookie, value, secure=True, httponly=True)
83

    
84
        if 'organization_id' in session:
85
            g = model.Group.get(session['organization_id'])
86
            client = Clients.get(g)
87
            url, ht_args = client.create_authn_request(conf.ACR_VALUES)
88
            if ht_args:
89
                toolkit.request.headers.update(ht_args)
90
            redirect_to(url)
91
        else:
92
            redirect_to('/')
93

    
94
    def logout(self):
95
        log.info('Logging out user: %s' % session['user'])
96
        session['user'] = None
97
        session.save()
98
        g = model.Group.get(session['organization_id'])
99
        if g:
100
            org_url = toolkit.url_for(host=request.host,
101
                                      controller='organization',
102
                                      action='read',
103
                                      id=g.name,
104
                                      qualified=True)
105

    
106
            redirect_to(str(org_url))
107
        else:
108
            redirect_to('/')
109

    
110
    def update_config(self, config_):
111
        toolkit.add_template_directory(config_, 'templates')
112
        toolkit.add_public_directory(config_, 'public')
113
        toolkit.add_resource('fanstatic', 'ozwillo_pyoidc')
114

    
115
class OpenidController(base.BaseController):
116

    
117
    def sso(self, id):
118
        log.info('SSO for organization "%s"' % id)
119
        session['organization_id'] = id
120
        session.save()
121
        log.info('redirecting to login page')
122
        login_url = toolkit.url_for(host=request.host,
123
                                    controller='user',
124
                                    action='login',
125
                                    qualified=True)
126
        redirect_to(login_url)
127

    
128
    def callback(self):
129
        g = model.Group.get(session['organization_id'])
130
        client = Clients.get(g)
131
        userinfo = client.callback(request.GET)
132
        log.info('Received userinfo: %s' % userinfo)
133
        userobj = model.User.get(userinfo['sub'])
134
        if userobj:
135
            if 'given_name' in userinfo:
136
                userobj.fullname = userinfo['given_name']
137
            if 'family_name' in userinfo:
138
                userobj.fullname += userinfo['family_name']
139
            userobj.save()
140
            session['user'] = userobj.id
141
            session.save()
142

    
143
        org_url = toolkit.url_for(host=request.host,
144
                                  controller="organization",
145
                                  action='read',
146
                                  id=g.name,
147
                                  locale=userinfo.get('locale'),
148
                                  qualified=True)
149
        redirect_to(str(org_url))
150

    
151
    def logout(self):
152
        toolkit.c.slo_url = toolkit.url_for(host=request.host,
153
                                            controller=plugin_controller,
154
                                            action="slo",
155
                                            qualified=True)
156
        return base.render('logout_confirm.html')
157

    
158
    def slo(self):
159
        """
160
        Revokes the delivered access token. Logs out the user
161
        """
162
        g = model.Group.get(session['organization_id'])
163
        org_url = toolkit.url_for(host=request.host,
164
                                  controller='organization',
165
                                  action='read',
166
                                  id=g.name,
167
                                  qualified=True)
168
        org_url = str(org_url)
169

    
170
        if toolkit.c.user and request.method == 'POST':
171
            client = Clients.get(g)
172
            logout_url = client.end_session_endpoint
173

    
174
            redirect_uri = org_url + '/logout'
175

    
176
            if not hasattr(client, 'access_token'):
177
                self.sso(g.name)
178

    
179
            # revoke the access token
180
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
181
            data = 'token=' + client.access_token
182
            data += '&token_type_hint=access_token'
183
            client.http_request(client.revocation_endpoint, 'POST',
184
                                data=data, headers=headers)
185

    
186
            # redirect to IDP logout
187
            logout_url += '?id_token_hint=%s&' % client.id_token
188
            logout_url += 'post_logout_redirect_uri=%s' % redirect_uri
189
            for cookie in request.cookies:
190
                response.delete_cookie(cookie)
191
            redirect_to(logout_url)
192
        redirect_to(org_url)
(4-4/4)