Projet

Général

Profil

Télécharger (6,88 ko) Statistiques
| Branche: | Tag: | Révision:

oidc / ckanext / ozwillo_pyoidc / plugin.py @ 992d3237

1 c8204b73 Serghei Mihai
import logging
2 25877dab Serghei MIHAI
from routes import redirect_to, url_for
3 c8204b73 Serghei Mihai
4 b169c797 Serghei MIHAI
import ckan.plugins as plugins
5
import ckan.plugins.toolkit as toolkit
6 f1d53ae8 Serghei MIHAI
from ckan.common import session, c, request, response
7 a5f39ab1 Serghei MIHAI
from ckan import model
8 c8204b73 Serghei Mihai
import ckan.lib.base as base
9
10 f1d53ae8 Serghei MIHAI
from pylons import config
11 c8204b73 Serghei Mihai
12 b71e8531 Serghei MIHAI
import conf
13
from oidc import create_client
14 c8204b73 Serghei Mihai
15
plugin_config_prefix = 'ckanext.ozwillo_pyoidc.'
16
17
log = logging.getLogger(__name__)
18 1c8b9fc4 Serghei MIHAI
plugin_controller = __name__ + ':OpenidController'
19 c8204b73 Serghei Mihai
20 b699aa44 Serghei MIHAI
_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 25877dab Serghei MIHAI
            'redirect_uris': [url_for(host=request.host,
39
                                      controller=plugin_controller,
40
                                      action='callback',
41
                                      id=g.name,
42
                                      qualified=True)]
43 b699aa44 Serghei MIHAI
        })
44
        return create_client(**params)
45
46 b169c797 Serghei MIHAI
47
class OzwilloPyoidcPlugin(plugins.SingletonPlugin):
48
    plugins.implements(plugins.IConfigurer)
49 c8204b73 Serghei Mihai
    plugins.implements(plugins.IRoutes)
50
    plugins.implements(plugins.IAuthenticator, inherit=True)
51 b169c797 Serghei MIHAI
52 c8204b73 Serghei Mihai
    def before_map(self, map):
53 a5f39ab1 Serghei MIHAI
        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 1c8b9fc4 Serghei MIHAI
        map.connect('/logout', controller=plugin_controller,
60
                    action='logout')
61 1ae62674 Serghei MIHAI
        map.connect('/user/slo',
62
                    controller=plugin_controller,
63 1c8b9fc4 Serghei MIHAI
                    action='slo',
64
                    conditions={'method': ['POST']})
65 1ae62674 Serghei MIHAI
        map.redirect('/organization/{id:.*}/logout', '/user/_logout')
66
67 c8204b73 Serghei Mihai
        return map
68
69
    def after_map(self, map):
70
        return map
71
72
    def identify(self):
73 a5f39ab1 Serghei MIHAI
        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 c8204b73 Serghei Mihai
79
    def login(self):
80 f1d53ae8 Serghei MIHAI
        for cookie in request.cookies:
81
            value = request.cookies.get(cookie)
82
            response.set_cookie(cookie, value, secure=True, httponly=True)
83
84 a5f39ab1 Serghei MIHAI
        if 'organization_id' in session:
85
            g = model.Group.get(session['organization_id'])
86 b699aa44 Serghei MIHAI
            client = Clients.get(g)
87 6388360c Serghei MIHAI
            url, ht_args = client.create_authn_request(conf.ACR_VALUES)
88 a5f39ab1 Serghei MIHAI
            if ht_args:
89
                toolkit.request.headers.update(ht_args)
90 c4dcef5d Serghei MIHAI
            redirect_to(url)
91 a5f39ab1 Serghei MIHAI
        else:
92 c4dcef5d Serghei MIHAI
            redirect_to('/')
93 c8204b73 Serghei Mihai
94
    def logout(self):
95 b87c1c93 Serghei MIHAI
        log.info('Logging out user: %s' % session['user'])
96 7400c5df Serghei MIHAI
        session['user'] = None
97 b87c1c93 Serghei MIHAI
        session.save()
98
        g = model.Group.get(session['organization_id'])
99 992d3237 Serghei MIHAI
        for cookie in request.cookies:
100
            response.delete_cookie(cookie)
101 b87c1c93 Serghei MIHAI
        if g:
102 84922cdf Serghei MIHAI
            org_url = toolkit.url_for(host=request.host,
103
                                      controller='organization',
104
                                      action='read',
105
                                      id=g.name,
106
                                      qualified=True)
107
108 c4dcef5d Serghei MIHAI
            redirect_to(str(org_url))
109 b87c1c93 Serghei MIHAI
        else:
110 c4dcef5d Serghei MIHAI
            redirect_to('/')
111 b169c797 Serghei MIHAI
112
    def update_config(self, config_):
113
        toolkit.add_template_directory(config_, 'templates')
114
        toolkit.add_public_directory(config_, 'public')
115
        toolkit.add_resource('fanstatic', 'ozwillo_pyoidc')
116 c8204b73 Serghei Mihai
117
class OpenidController(base.BaseController):
118
119 a5f39ab1 Serghei MIHAI
    def sso(self, id):
120
        log.info('SSO for organization "%s"' % id)
121
        session['organization_id'] = id
122
        session.save()
123
        log.info('redirecting to login page')
124
        login_url = toolkit.url_for(host=request.host,
125
                                    controller='user',
126
                                    action='login',
127
                                    qualified=True)
128 c4dcef5d Serghei MIHAI
        redirect_to(login_url)
129 a5f39ab1 Serghei MIHAI
130
    def callback(self):
131 b699aa44 Serghei MIHAI
        g = model.Group.get(session['organization_id'])
132
        client = Clients.get(g)
133
        userinfo = client.callback(request.GET)
134 cb408fc1 Serghei MIHAI
        locale = None
135 b699aa44 Serghei MIHAI
        log.info('Received userinfo: %s' % userinfo)
136 856c858c Serghei MIHAI
137 cb408fc1 Serghei MIHAI
        if 'sub' in userinfo:
138
            locale = userinfo.get('locale', '')
139
            if '-' in locale:
140
                locale, country = locale.split('-')
141
142
            userobj = model.User.get(userinfo['sub'])
143 b699aa44 Serghei MIHAI
            if 'given_name' in userinfo:
144
                userobj.fullname = userinfo['given_name']
145
            if 'family_name' in userinfo:
146
                userobj.fullname += userinfo['family_name']
147
            userobj.save()
148
            session['user'] = userobj.id
149
            session.save()
150
151
        org_url = toolkit.url_for(host=request.host,
152
                                  controller="organization",
153
                                  action='read',
154 cdd21e6f Serghei MIHAI
                                  id=g.name,
155 856c858c Serghei MIHAI
                                  locale=locale,
156 b699aa44 Serghei MIHAI
                                  qualified=True)
157 c4dcef5d Serghei MIHAI
        redirect_to(str(org_url))
158 1ae62674 Serghei MIHAI
159 1c8b9fc4 Serghei MIHAI
    def logout(self):
160
        toolkit.c.slo_url = toolkit.url_for(host=request.host,
161
                                            controller=plugin_controller,
162
                                            action="slo",
163
                                            qualified=True)
164
        return base.render('logout_confirm.html')
165
166 1ae62674 Serghei MIHAI
    def slo(self):
167
        """
168
        Revokes the delivered access token. Logs out the user
169
        """
170 b699aa44 Serghei MIHAI
        g = model.Group.get(session['organization_id'])
171 1ae62674 Serghei MIHAI
        org_url = toolkit.url_for(host=request.host,
172
                                  controller='organization',
173
                                  action='read',
174 cdd21e6f Serghei MIHAI
                                  id=g.name,
175 1ae62674 Serghei MIHAI
                                  qualified=True)
176 1c8b9fc4 Serghei MIHAI
        org_url = str(org_url)
177
178
        if toolkit.c.user and request.method == 'POST':
179
            client = Clients.get(g)
180
            logout_url = client.end_session_endpoint
181
182
            redirect_uri = org_url + '/logout'
183
184 838dc9f3 Serghei MIHAI
            if not hasattr(client, 'access_token'):
185
                self.sso(g.name)
186
187 1c8b9fc4 Serghei MIHAI
            # revoke the access token
188
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
189
            data = 'token=' + client.access_token
190
            data += '&token_type_hint=access_token'
191
            client.http_request(client.revocation_endpoint, 'POST',
192
                                data=data, headers=headers)
193
194
            # redirect to IDP logout
195
            logout_url += '?id_token_hint=%s&' % client.id_token
196
            logout_url += 'post_logout_redirect_uri=%s' % redirect_uri
197 82a66e96 Serghei MIHAI
            redirect_to(str(logout_url))
198 c4dcef5d Serghei MIHAI
        redirect_to(org_url)