Project

General

Profile

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

oidc / ckanext / ozwillo_pyoidc / plugin.py @ c4dcef5d

1 c8204b73 Serghei Mihai
import logging
2 c4dcef5d Serghei MIHAI
from routes import redirect_to
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
            'redirect_uris': [toolkit.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 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
            url, ht_args = client.create_authn_request(session, 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
        if g:
100 84922cdf Serghei MIHAI
            org_url = toolkit.url_for(host=request.host,
101
                                      controller='organization',
102
                                      action='read',
103
                                      id=g.name,
104
                                      qualified=True)
105
106 c4dcef5d Serghei MIHAI
            redirect_to(str(org_url))
107 b87c1c93 Serghei MIHAI
        else:
108 c4dcef5d Serghei MIHAI
            redirect_to('/')
109 b169c797 Serghei MIHAI
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 c8204b73 Serghei Mihai
115
class OpenidController(base.BaseController):
116
117 a5f39ab1 Serghei MIHAI
    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 c4dcef5d Serghei MIHAI
        redirect_to(login_url)
127 a5f39ab1 Serghei MIHAI
128
    def callback(self):
129 b699aa44 Serghei MIHAI
        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 e7b8bf5b Serghei MIHAI
        userobj = model.User.get(userinfo['sub'])
134 b699aa44 Serghei MIHAI
        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 cdd21e6f Serghei MIHAI
                                  id=g.name,
147 b013655e Serghei MIHAI
                                  locale=userinfo.get('locale'),
148 b699aa44 Serghei MIHAI
                                  qualified=True)
149 c4dcef5d Serghei MIHAI
        redirect_to(str(org_url))
150 1ae62674 Serghei MIHAI
151 1c8b9fc4 Serghei MIHAI
    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 1ae62674 Serghei MIHAI
    def slo(self):
159
        """
160
        Revokes the delivered access token. Logs out the user
161
        """
162 b699aa44 Serghei MIHAI
        g = model.Group.get(session['organization_id'])
163 1ae62674 Serghei MIHAI
        org_url = toolkit.url_for(host=request.host,
164
                                  controller='organization',
165
                                  action='read',
166 cdd21e6f Serghei MIHAI
                                  id=g.name,
167 1ae62674 Serghei MIHAI
                                  qualified=True)
168 1c8b9fc4 Serghei MIHAI
        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
            # revoke the access token
177
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
178
            data = 'token=' + client.access_token
179
            data += '&token_type_hint=access_token'
180
            client.http_request(client.revocation_endpoint, 'POST',
181
                                data=data, headers=headers)
182
183
            # redirect to IDP logout
184
            logout_url += '?id_token_hint=%s&' % client.id_token
185
            logout_url += 'post_logout_redirect_uri=%s' % redirect_uri
186 c4dcef5d Serghei MIHAI
            redirect_to(logout_url)
187
        redirect_to(org_url)