summaryrefslogtreecommitdiffstats
path: root/idp/extra/modules/root.ptl
blob: fbb7fba370ce87a6dc86a135fe0c2aa94b088427 (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
import lasso
import Cookie

from quixote import redirect, get_session
from qommon import get_cfg, get_logger
from qommon.form import *
from qommon import template
import authentic.root

from qommon.admin.texts import TextsDirectory
from qommon.admin.emails import EmailsDirectory
from qommon import emails
from qommon import errors


from authentic import identities
from authentic import misc

import directory
import store
import admin

OldRootDirectory = authentic.root.RootDirectory

from saml2 import AlternateSaml2Directory

from identities_ui import AgentDirectory



class AlternateRootDirectory(OldRootDirectory):
    backoffice = None
    admin = admin.AdminRootDirectory()

    saml = AlternateSaml2Directory()

    def __init__(self):
        OldRootDirectory.__init__(self)
        self._q_exports = OldRootDirectory._q_exports + [
                'backoffice', 'profile', 'issue', 'password']

    def _q_index [html] (self):
        session = get_session()
        if not session or not session.user:
            return self.login()

        user = get_session().get_user_object()
        if user.is_admin():
            return redirect('/backoffice/')

        agent = user.get_as_agent()
        template.html_top(_('Welcome, %s') % agent.cn)

        if hasattr(session, str('previousConnectionTime')):
            '<p>'
            _('Last session started: %s') % misc.localstrftime(
                    time.localtime(session.previousConnectionTime))
            if session.previousConnectionDuration:
                _(' (duration: %dm)') % int(session.previousConnectionDuration/60)
            '</p>'

        all_services = directory.get_services()

        collectivity = directory.get_collectivity(agent.get_collectivity())
        service_instances = directory.get_service_instances(collectivity)

        providers = get_cfg('providers', {})
        accesses = user.get_as_agent().cdg59serviceAccesses or []
        '<ul id="services">'
        for service in service_instances:
            try:
                service_type = directory.get_service(service.cdg59serviceType)
            except KeyError:
                # ignore service type that has been removed globally
                continue
            service_label = service_type.cn
            service_description = service_type.description

            if service_type.cdg59isGlobal:
                url = service_type.cdg59URL
            else:
                url = service.cdg59URL

            metadata_url = service.cdg59metadataURL or service_type.cdg59metadataURL

            if not service.cdg59siid in accesses and metadata_url:
                # only skip access to liberty/saml services
                continue

            if metadata_url:
                try:
                    klp = [x for x, y in providers.items() if \
                          metadata_url == y.get('metadata_url')] [0]
                except IndexError:
                    # bad, unregistered saml provider
                    pass
                else:
                    try:
                        provider, unused_label = misc.get_provider_and_label(klp)
                    except KeyError:
                        pass
                    else:
                        if provider.getProtocolConformance() == lasso.PROTOCOL_SAML_2_0:
                            url = 'saml/sp/%s/login' % klp
                        else:
                            url = 'liberty/sp/%s/login' % klp

            if not url:
                continue

            if url in (service_type.cdg59URL, service.cdg59URL):
                label = _('Go to %s') % service_label
            else:
                label = _('Log on %s') % service_label

            '<li><a href="%s">%s</a>' % (url, label)
            if service_description:
                ' <p class="service_description">%s</p>' % service_description
            '</li>'

        '</ul>'

        t = TextsDirectory.get_html_text('pratic-platform-status')
        if t:
            '<div id="platform-status">'
            '<h3>%s</h3>' % _('Platform Status')
            '<div>'
            htmltext(t)
            '</div>'
            if not user.is_admin():
                '<p id="report-issue">'
                '<a href="/issue">%s</a>' % _('Report an issue')
                '</p>'
            '</div>'


        '<p id="commands">'
        '<a href="/profile">%s</a> - ' % _('View Profile')

        passwords_cfg = get_cfg('passwords', {})
        if passwords_cfg.get('can_change', False):
            '<a href="/password">%s</a> - ' % _('Change Password')
        if user.is_admin():
            '<a href="/admin/">%s</a> - ' % _('Administration Interface')
            '<a href="/backoffice/">%s</a> - ' % _('Back Office Interface')
            '<a href="/singleLogout">%s</a>' % _('Logout')
        elif user.is_local_admin():
            '<a href="/backoffice/">%s</a> - ' % _('Back Office Interface')
            '<a href="/singleLogout">%s</a>' % _('Logout')
        else:
            '<a href="/singleLogout">%s</a>' % _('Logout')
        '</p>'

    def _q_traverse(self, path):
        get_publisher().store = identities.load_store()

        try:
            store = directory.get_store()
        except directory.UnconfiguredError:
            if path and path[0] not in ['admin', 'qo', 'css', 'themes', 'js']:
                return template.error_page(_('Directory must first be configured'))

        if not self.backoffice:
            self.backoffice = get_publisher().backoffice_directory_class()
        session = get_session()
        if session:
            identities.get_store().connect(session)
        return OldRootDirectory._q_traverse(self, path)

    def get_login_form(self):
        form = OldRootDirectory.get_login_form(self)
        try:
            collectivities = directory.get_sorted_collectivities()
        except directory.UnconfiguredError:
            return form
        collectivities = [(x.dn, x.cn) for x in collectivities]
        password_widget = form.widgets[-1]
        form.widgets.remove(password_widget)
        try:
            collectivity = get_request().cookies['collectivity']
        except KeyError:
            collectivity = None
        if collectivity not in [x.dn for x in collectivities]:
            collectivity = None
        form.add(SingleSelectWidget, 'collectivity', title = _('Collectivity'), required = True,
                value = collectivity, options = collectivities)
        form.widgets.append(password_widget)
        return form

    def login_submit(self, form):
        try:
            store = directory.get_store()
        except directory.UnconfiguredError:
            return OldRootDirectory.login_submit(self, form)

        username = form.get_widget('username').parse()
        password = form.get_widget('password').parse()
        collectivity = form.get_widget('collectivity').parse()

        identity = store.get_identity_for_account(username, password, collectivity)
        if identity is None:
            get_logger().warn('Authentication Failure (un: %s)' % username)
            raise authentic.root.LoginError()

        session = get_session()
        session.set_user(identity.id)
        get_request().user = identity.id
        store.init_session(session, password)
        identity.register_new_session()

        get_response().set_cookie('collectivity', collectivity, path = '/',
                expires = Cookie._getdate(90*86400))

        return self.login_success(identity)

    def forgot_password(self):
        raise NotImplementedError()

    def profile [html] (self):
        if not get_request().user:
            raise errors.AccessUnauthorizedError()

        get_response().breadcrumb.append(('profile', _('Your Profile')))
        template.html_top(_('Your Profile'))

        user = get_session().get_user_object()
        agent = user.get_as_agent()

        '<dl class="profile">'
        for k, l, attrs in AgentDirectory.attrs:
            if k in ('cdg59isAdmin',):
                continue
            if attrs.has_key('widget_class'):
                widget_class = attrs.get('widget_class')
                attrs = attrs.copy()
                del attrs['widget_class']
            else:
                widget_class = StringWidget
            '<dt>%s</dt>' % _(l)
            if getattr(agent, k):
                '<dd>%s</dd>' % getattr(agent, k)
            else:
                '<dd>-</dd>'
        '</dl>'

        '<p>'
        '<a href=".">%s</a>' % _('Home')

    def password [html] (self):
        passwords_cfg = get_cfg('passwords', {})
        if not passwords_cfg.get('can_change', False):
            raise errors.AccessForbiddenError()

        if not get_request().user:
            raise errors.AccessUnauthorizedError()

        form = Form(enctype='multipart/form-data')

        form.add(PasswordWidget, 'new_password', title=_('New Password'), required=True)
        form.add(PasswordWidget, 'new2_password', title=_('New Password (confirmation)'),
                    required=True)

        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():
            new_password = form.get_widget('new_password').parse()
            new2_password = form.get_widget('new2_password').parse()

            if new_password != new2_password:
                form.set_error('new2_password', _('Passwords do not match'))
            else:
                min_length = int(passwords_cfg.get('min_length', 0))
                if len(new_password) < min_length:
                    form.set_error('new_password',
                            _('Password is too short.  It must be at least %d characters.') % min_length)
                max_length = int(passwords_cfg.get('max_length', 0))
                if max_length and len(new_password) > max_length:
                    form.set_error('new_password',
                            _('Password is too long.  It must be at most %d characters.') % max_length)

        if not form.is_submitted() or form.has_errors():
            get_response().breadcrumb.append(('password', _('Change Password')))
            template.html_top(_('Change Password'))
            form.render()
        else:
            user = get_session().get_user_object()
            agent = user.get_as_agent()

            agent.change_password(str(form.get_widget('new_password').parse()))
            return redirect('..')

    def issue [html] (self):
        user = get_session().get_user_object()
        if user.is_admin():
            return template.error_page(_('You are not one to report issues.'))

        form = Form(enctype='multipart/form-data')
        form.add(TextWidget, 'description', title = _('Description'), cols = 60, rows = 10)
        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(('issue', _('Issue Report')))
            template.html_top(_('Reporting an Issue'))
            '<p>'
            if user.is_local_admin():
                _('The issue will be sent to Pr@tic administrators.')
            else:
                _('The issue will be sent to your local administrators.')
            '</p>'
            form.render()
        else:
            self.issue_submit(form)
            return redirect('.')

    def issue_submit(self, form):
        user = get_session().get_user_object()
        agent = user.get_as_agent()
        description = form.get_widget('description').parse()

        admins = agent.get_admin_agents()
        admin_emails = [x.mail for x in admins if x.mail]

        data = {
            'agent': agent.cn,
            'description': description,
        }
        emails.custom_ezt_email('pratic-issue-report', data, admin_emails, fire_and_forget = True)

from qommon.publisher import get_publisher_class
get_publisher_class().root_directory_class = AlternateRootDirectory

TextsDirectory.register('pratic-platform-status', N_('Pr@tic Platform Status'))


EmailsDirectory.register('pratic-issue-report',
        N_('Pr@tic Issue Report'),
        N_('Available variables: agent, description'),
        default_subject = N_('Pr@tic Issue'),
        default_body = N_('''\
Agent [agent] reported the following problem:

[description]
'''))