summaryrefslogtreecommitdiffstats
path: root/idp/extra/modules/services_ui.ptl
blob: 552dcb6d35c96ee789f9a96c8a91d0a14cbc6cc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import lasso
import tempfile
import re
import urllib2
import ldap.dn
import ldap

from quixote import get_request, get_response, get_session, redirect, get_publisher
from quixote.directory import Directory
from quixote.html import htmltext, htmlescape, url_quote

from qommon.backoffice.menu import html_top
from qommon.admin.menu import command_icon

from qommon import errors
from qommon import misc
from qommon.form import *
from qommon import template

import directory

class ServiceInstanceDirectory(Directory):
    _q_exports = ['', 'edit', 'delete', 'update']

    attrs = [
        ('cdg59URL', _('URL to service root'),
             {'widget_class': ValidUrlWidget, 'size': 80}),
        ('cdg59metadataURL', _('URL to service metadata'),
             {'widget_class': ValidUrlWidget, 'size': 80}),
    ]


    def __init__(self, service):
        self.service = service
        try:
            self.service_type = directory.get_service(self.service.cdg59serviceType)
        except KeyError:
            raise
        get_response().breadcrumb.append((self.service.cdg59siid + '/', self.service.name))

    def _q_index [html] (self):
        html_top('services', title = _('Service: %s') % self.service.name)
        '<h2>%s</h2>' % _('Service: %s') % self.service.name

        get_session().display_message()

        '<p>'
        if not self.service_type.cdg59isGlobal:
            '<a href="edit">%s</a> - ' % _('Edit')
        '<a href="delete" rel="popup">%s</a>' % _('Unsubscribe')
        if self.service.cdg59metadataURL:
            ' - <a href="update">%s</a>' % _('Update SAML Metadata')
        '</p>'

    def edit [html] (self):
        if self.service_type.cdg59isGlobal:
            get_response().breadcrumb.append(('edit', _('Edit')))
            html_top('services', title = _('Service: %s') % self.service.name)
            '<p>'
            _('Global Service, nothing to do here')
            '</p>'
            '<p><a href=".">%s</a></p>' % _('Back')
        else:
            form = Form(enctype='multipart/form-data')

            for k, l, attrs in self.attrs:
                if not attrs:
                    attrs = {}
                if attrs.has_key('widget_class'):
                    widget_class = attrs.get('widget_class')
                    attrs = attrs.copy()
                    del attrs['widget_class']
                else:
                    widget_class = StringWidget
                form.add(widget_class, k, title = _(l),
                        value = getattr(self.service, k),
                        **attrs)

            form.add_submit('submit', _('Submit'))
            form.add_submit('cancel', _('Cancel'))
            if form.get_submit() == 'cancel':
                return redirect('..')

            if form.is_submitted() and not form.has_errors():
                self.submit(form)
                if not form.has_errors():
                    return redirect('..')

            get_response().breadcrumb.append(('edit', _('Edit')))
            html_top('services', title = _('Service: %s') % self.service.name)
            '<h2>%s</h2>' % self.service.name
            form.render()

    def submit(self, form):
        old_metadata_url = self.service.cdg59metadataURL
        changed = []
        for k, l, attrs in self.attrs:
            widget = form.get_widget(k)
            if widget:
                v = widget.parse()
                old_v = getattr(self.service, k)
                if v != old_v:
                    setattr(self.service, k, v)
                    changed.append(k)

        if 'cdg59metadataURL' in changed:
            if not self.service.cdg59metadataURL:
                d = get_cfg('providers', {})
                for k in d.keys():
                    if d[k].get('metadata_url') == old_metadata_url:
                        del d[k]
                        get_publisher().write_cfg()
                        break
            else:
                try:
                    rfd = urllib2.urlopen(self.service.cdg59metadataURL)
                except:
                    raise
                    form.set_error('cdg59metadataURL', _('Failed to retrieve file'))
                    return

                s = rfd.read()
                (bfd, metadata_pathname) = tempfile.mkstemp('.metadata')
                open(metadata_pathname, 'w').write(s)
                try:
                    p = lasso.Provider(lasso.PROVIDER_ROLE_SP, metadata_pathname, None, None)
                except lasso.Error:
                    form.set_error('cdg59metadataURL',
                            _('Failed to create Lasso provider with those metadata'))
                    return

                key_provider_id = misc.get_provider_key(p.providerId)

                dir = get_publisher().app_dir
                metadata_fn = 'provider-%s-metadata.xml' % key_provider_id

                d = get_cfg('providers', {})
                get_publisher().cfg['providers'] = d

                d[key_provider_id] = {}
                d[key_provider_id]['role'] = lasso.PROVIDER_ROLE_SP
                d[key_provider_id]['metadata'] = metadata_fn
                d[key_provider_id]['metadata_url'] = self.service.cdg59metadataURL
                file(misc.get_abs_path(metadata_fn), 'w').write(s)
                get_publisher().write_cfg()

        self.service.save(changed)

    def update(self):
        try:
            rfd = urllib2.urlopen(self.service.cdg59metadataURL)
        except:
            get_session().message = ('error', _('Failed to load metadata'))
            return redirect('.')

        s = rfd.read()
        (bfd, metadata_pathname) = tempfile.mkstemp('.metadata')
        open(metadata_pathname, 'w').write(s)
        try:
            p = lasso.Provider(lasso.PROVIDER_ROLE_SP, metadata_pathname, None, None)
        except lasso.Error:
            get_session().message = ('error',
                    _('Failed to create Lasso provider with those metadata'))
            return redirect('.')

        key_provider_id = misc.get_provider_key(p.providerId)

        dir = get_publisher().app_dir
        metadata_fn = 'provider-%s-metadata.xml' % key_provider_id

        d = get_cfg('providers', {})
        get_publisher().cfg['providers'] = d

        d[key_provider_id] = {}
        d[key_provider_id]['role'] = lasso.PROVIDER_ROLE_SP
        d[key_provider_id]['metadata'] = metadata_fn
        d[key_provider_id]['metadata_url'] = self.service.cdg59metadataURL
        file(misc.get_abs_path(metadata_fn), 'w').write(s)
        get_publisher().write_cfg()

        get_session().message = ('info', _('Metadata have been successfully updated.'))

        return redirect('.')

    def delete [html] (self):
        form = Form(enctype='multipart/form-data')
        form.widgets.append(HtmlWidget('<p>%s</p>' % _(
                        'You are about to unsubscribe the collectivity from this service.')))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_submit() == 'cancel':
            return redirect('..')
        if not form.is_submitted() or form.has_errors():
            get_response().breadcrumb.append(('delete', _('Delete')))
            html_top('services', title = _('Unsubscribing from Service'))
            '<h2>%s</h2>' % _('Unsubscring from Service: %s') % self.service.name
            form.render()
        else:
            self.service.delete()
            # XXX: remove lasso provider if it exists
            return redirect('..')



class ServiceDirectory(Directory):
    _q_exports = ['', 'edit', 'delete', 'update']

    attrs = [
        ('cn', _('Name'), {'required': True}),
        ('description', _('Description'), {'widget_class': TextWidget, 'cols': 60, 'rows': 5}),
        ('cdg59URL', _('URL to service root'),
             {'widget_class': ValidUrlWidget, 'size': 80}),
        ('cdg59metadataURL', _('URL to service metadata'),
             {'widget_class': ValidUrlWidget, 'size': 80}),
        ('cdg59isGlobal', _('Global Service'), {'widget_class': CheckboxWidget}),
    ]

    def __init__(self, service):
        self.service = service

    def _q_index [html] (self):
        html_top('services', title = _('Service: %s') % self.service.cn)

        '<h2>%s</h2>' % self.service.cn

        get_session().display_message()
        
        '<p>'
        self.service.description
        '</p>'

        '<p>'
        '<a href="edit">%s</a> - ' % _('Edit')
        '<a href="delete" rel="popup">%s</a>' % _('Delete')
        if self.service.cdg59metadataURL:
            ' - <a href="update">%s</a>' % _('Update SAML Metadata')
        '</p>'

    def edit [html] (self):
        form = Form(enctype='multipart/form-data')
        for k, l, attrs in self.attrs:
            if not attrs:
                attrs = {}
            if attrs.has_key('widget_class'):
                widget_class = attrs.get('widget_class')
                attrs = attrs.copy()
                del attrs['widget_class']
            else:
                widget_class = StringWidget
            form.add(widget_class, k, title = _(l),
                    value = getattr(self.service, k),
                    **attrs)
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_submit() == 'cancel':
            return redirect('../..')

        if form.is_submitted() and not form.has_errors():
            self.submit(form)
            if not form.has_errors():
                return redirect('..')

        get_response().breadcrumb.append(('edit', _('Edit')))
        html_top('services', title = _('Service: %s') % self.service.cn)
        '<h2>%s</h2>' % self.service.cn
        form.render()


    def submit(self, form):
        changed = []
        old_metadata_url = self.service.cdg59metadataURL
        for k, l, attrs in self.attrs:
            widget = form.get_widget(k)
            if widget:
                v = widget.parse()
                old_v = getattr(self.service, k)
                if v != old_v:
                    setattr(self.service, k, v)
                    changed.append(k)

        if 'cdg59metadataURL' in changed:
            if not self.service.cdg59metadataURL:
                d = get_cfg('providers', {})
                for k in d.keys():
                    if d[k].get('metadata_url') == old_metadata_url:
                        del d[k]
                        get_publisher().write_cfg()
                        break
            else:
                try:
                    rfd = urllib2.urlopen(self.service.cdg59metadataURL)
                except:
                    form.set_error('cdg59metadataURL', _('Failed to retrieve file'))
                    return

                s = rfd.read()
                (bfd, metadata_pathname) = tempfile.mkstemp('.metadata')
                open(metadata_pathname, 'w').write(s)
                try:
                    p = lasso.Provider(lasso.PROVIDER_ROLE_SP, metadata_pathname, None, None)
                except lasso.Error:
                    form.set_error('cdg59metadataURL',
                            _('Failed to create Lasso provider with those metadata'))
                    return

                key_provider_id = misc.get_provider_key(p.providerId)

                dir = get_publisher().app_dir
                metadata_fn = 'provider-%s-metadata.xml' % key_provider_id

                d = get_cfg('providers', {})
                get_publisher().cfg['providers'] = d

                d[key_provider_id] = {}
                d[key_provider_id]['role'] = lasso.PROVIDER_ROLE_SP
                d[key_provider_id]['metadata'] = metadata_fn
                d[key_provider_id]['metadata_url'] = self.service.cdg59metadataURL
                file(misc.get_abs_path(metadata_fn), 'w').write(s)
                get_publisher().write_cfg()

        self.service.save(changed)

    def update(self):
        try:
            rfd = urllib2.urlopen(self.service.cdg59metadataURL)
        except:
            get_session().message = ('error', _('Failed to load metadata'))
            return redirect('.')

        s = rfd.read()
        (bfd, metadata_pathname) = tempfile.mkstemp('.metadata')
        open(metadata_pathname, 'w').write(s)
        try:
            p = lasso.Provider(lasso.PROVIDER_ROLE_SP, metadata_pathname, None, None)
        except lasso.Error:
            get_session().message = ('error',
                    _('Failed to create Lasso provider with those metadata'))
            return redirect('.')

        key_provider_id = misc.get_provider_key(p.providerId)

        dir = get_publisher().app_dir
        metadata_fn = 'provider-%s-metadata.xml' % key_provider_id

        d = get_cfg('providers', {})
        get_publisher().cfg['providers'] = d

        d[key_provider_id] = {}
        d[key_provider_id]['role'] = lasso.PROVIDER_ROLE_SP
        d[key_provider_id]['metadata'] = metadata_fn
        d[key_provider_id]['metadata_url'] = self.service.cdg59metadataURL
        file(misc.get_abs_path(metadata_fn), 'w').write(s)
        get_publisher().write_cfg()

        get_session().message = ('info', _('Metadata have been successfully updated.'))

        return redirect('.')

    def delete [html] (self):
        form = Form(enctype='multipart/form-data')
        form.widgets.append(HtmlWidget('<p>%s</p>' % _(
                        'You are about to irrevocably delete this service.')))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_submit() == 'cancel':
            return redirect('../..')
        service_instances = directory.get_service_instances_by_service_type(self.service.cdg59sid)
        if service_instances:
            error_text = htmltext('<p>%s :</p>' % _('Cannot delete service. There are still service instances for this service'))
            error_text += htmltext('<ul>')
            for si in service_instances:
                sid=si.cdg59siid
                try:
                    if not hasattr(ldap.dn, 'str2dn'):
                        raise KeyError
                    ou=[x[0][1] for x in ldap.dn.str2dn(si.dn, flags=ldap.DN_FORMAT_LDAPV3) if x[0][0] == 'ou' ][0]
                    collectivity = directory.get_collectivity(ou)
                    ou = collectivity.ou
                    link = url_quote("../../%s/%s/delete" % (ou,sid))
                    error_text += htmltext('<li> %s - %s <a href="%s" target="_delete_%s">%s</a></li>' % (collectivity.cn, si.name, link, ou, _('Delete')))
                except KeyError:
                    error_text += htmltext('<li>%s</li>' % htmlescape(si.dn))

            error_text += htmltext('</ul>')
            get_session().message = ('error', error_text)

        if not form.is_submitted() or form.has_errors() or service_instances:
            get_response().breadcrumb.append(('delete', _('Delete')))
            html_top('services', title = _('Delete Service'))
            get_session().display_message()
            '<h2>%s</h2>' % _('Deleting Service: %s') % self.service.cn
            form.render()
        else:
            self.service.delete()
            return redirect('../..')


class ServiceLookupDirectory(Directory):
    _q_exports = ['', 'new']

    def _q_index(self):
        return redirect('..')

    def new [html] (self):
        form = Form(enctype='multipart/form-data')
        form.add(StringWidget, 'cdg59sid', title = _('Service Identifier'), required = True,
                hint = _('All lowercase, no space or special characters'))
        for k, l, attrs in ServiceDirectory.attrs:
            if not attrs:
                attrs = {}
            if attrs.has_key('widget_class'):
                widget_class = attrs.get('widget_class')
                attrs = attrs.copy()
                del attrs['widget_class']
            else:
                widget_class = StringWidget
            form.add(widget_class, k, title = _(l), **attrs)
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_submit() == 'cancel':
            return redirect('../..')

        if form.is_submitted():
            sid = form.get_widget('cdg59sid').parse() or ''
            if sid and misc.simplify(sid) != sid:
                form.get_widget('cdg59sid').set_error(
                        _('All lowercase, no space or special characters'))


        if not form.is_submitted() or form.has_errors():
            get_response().breadcrumb.append(('edit', _('Edit')))
            html_top('services', title = _('New Service Declaration'))
            '<h2>%s</h2>' % _('New Service Declaration')
            form.render()
        else:
            return self.submit_new(form)

    def submit_new(self, form):
        values = {}
        values['cdg59sid'] = form.get_widget('cdg59sid').parse()
        for k, l, attrs in ServiceDirectory.attrs:
            widget = form.get_widget(k)
            if widget:
                v = widget.parse()
                if v:
                    values[k] = v
        directory.add_service(values)
        return redirect(form.get_widget('cdg59sid').parse() + '/')



    def _q_lookup(self, component):
        # lookup for service instance
        try:
            service = directory.get_service(component)
            get_response().breadcrumb.append(('service/' + component + '/', service.cn))
            return ServiceDirectory(service)
        except KeyError:
            raise errors.TraversalError()
        return Directory._q_lookup(self, component)



class ServicesDirectory(Directory):
    _q_exports = ['', 'service', 'subscribe']

    collectivity = None
    service = ServiceLookupDirectory()

    def __init__(self, collectivity = None):
        Directory.__init__(self)
        self.collectivity = collectivity

    def _q_traverse(self, path):
        user = get_session().get_user_object()
        if (user.is_admin() and not self.collectivity) or (not user.is_admin()):
            get_response().breadcrumb.append(('services/', _('Services Management')))
        return Directory._q_traverse(self, path)

    def _q_index [html] (self):
        html_top('services', _('Service Management'))

        user = get_session().get_user_object()
        if user.is_admin() and not self.collectivity:
            '<h3>%s</h3>' % _('List of Services')
            '<ul>'
            for service in directory.get_services():
                '<li><a href="service/%s/">' % service.cdg59sid
                service.cn
                '</a></li>'
            '</ul>'

            '<p><a href="service/new">%s</a></p>' % _('Declare new service')

            '<h3>%s</h3>' % _('List of Collectivities')
            # list all collectivities, but the admin group
            '<ul>'
            for collectivity in directory.get_sorted_collectivities():
                if collectivity.ou == 'admin':
                    continue
                '<li><a href="%s/">' % collectivity.ou
                collectivity.cn
                '</a></li>'
            '</ul>'
        else:
            '<h2>'
            self.collectivity.cn
            '</h2>'

            '<p>'
            if user.is_admin():
                '<a href="../../identities/%s/">%s</a>' % (
                        self.collectivity.ou, _('Identities Management'))
            else:
                '<a href="../identities/">%s</a>' % _('Identities Management')
            '</p>'

            '<ul class="biglist">'
            service_instances = directory.get_service_instances(self.collectivity)
            for service in service_instances:
                '<li class="biglistitem">'
                '<strong class="label">%s</strong>' % service.name
                '<p class="commands">'
                command_icon('%s/' % service.cdg59siid, 'view')
                command_icon('%s/edit' % service.cdg59siid, 'edit')
                command_icon('%s/delete' % service.cdg59siid, 'remove', popup = True)
                '</p></li>'
            '</ul>'

            if user.is_admin():
                all_services = directory.get_services()
                instanciated_services = [x.cdg59serviceType for x in service_instances]
                available_services = []
                for service in all_services:
                    if not service.cdg59sid in instanciated_services:
                        available_services.append((service.cdg59sid, service.cn, service.cdg59sid))

                if available_services:
                    '<div id="new-field">'
                    form = Form(enctype='multipart/form-data', action = 'subscribe')
                    form.widgets.append(HtmlWidget('<table><tr><td>'))
                    form.add(SingleSelectWidget, 'sid', title = _('Subscribe to new service:'),
                            options = available_services)
                    form.widgets.append(HtmlWidget('</td></tr></table>'))
                    form.widgets.append(HtmlWidget(
                                '<p class="commands">%s</p>' % command_icon(None, 'add')))
                    form.render()
                    '</div>'

            if user.is_admin():
                '<p>'
                '<a href="../">%s</a>' % _('Back')
                '</p>'

    def subscribe(self):
        user = get_session().get_user_object()
        if not user.is_admin():
            raise errors.AccessForbiddenError()
        if not self.collectivity:
            raise TraversalError()

        all_services = directory.get_services()
        available_services = [x.cdg59sid for x in all_services]
        form = Form(enctype='multipart/form-data', action = 'subscribe')
        form.add(SingleSelectWidget, 'sid', title = _('Subscribe to new service:'),
                options = available_services, required = True)
        if form.has_errors() or not form.is_submitted():
            return redirect('.')

        sid = form.get_widget('sid').parse()

        si = directory.ServiceInstance()
        si.cdg59siid = sid
        si.cdg59serviceType = sid
        associated_service = [x for x in all_services if x.cdg59sid == sid][0]

        si.add(self.collectivity)

        if associated_service.cdg59isGlobal:
            return redirect('.')
        else:
            return redirect(sid + '/edit')

    def _q_lookup(self, component):
        if not self.collectivity:
            for collectivity in directory.get_collectivities():
                if collectivity.ou == component:
                    get_response().breadcrumb.append((component + '/', collectivity.cn))
                    return ServicesDirectory(collectivity)
        else:
            # lookup for service instance
            try:
                service = directory.get_service_instance(self.collectivity, component)
            except KeyError:
                pass
            else:
                try:
                    return ServiceInstanceDirectory(service)
                except KeyError:
                    return template.error_page(_('Invalid Service Type (was it removed?)'))
        raise errors.TraversalError()