LoginRefresh.ts 14 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

14
import $ from 'jquery';
15
import {AjaxResponse} from 'TYPO3/CMS/Core/Ajax/AjaxResponse';
16
import AjaxRequest = require('TYPO3/CMS/Core/Ajax/AjaxRequest');
17
import Notification = require('TYPO3/CMS/Backend/Notification');
18
19
20
21

enum MarkupIdentifiers {
  loginrefresh = 't3js-modal-loginrefresh',
  lockedModal = 't3js-modal-backendlocked',
22
  loginFormModal = 't3js-modal-backendloginform',
23
24
25
26
27
28
29
30
31
}

/**
 * Module: TYPO3/CMS/Backend/LoginRefresh
 * @exports TYPO3/CMS/Backend/LoginRefresh
 */
class LoginRefresh {
  private options: any = {
    modalConfig: {
32
33
      backdrop: 'static',
    },
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
  };
  private intervalTime: number = 60;
  private intervalId: number = null;
  private backendIsLocked: boolean = false;
  private isTimingOut: boolean = false;
  private $timeoutModal: JQuery = null;
  private $backendLockedModal: JQuery = null;
  private $loginForm: JQuery = null;
  private loginFramesetUrl: string = '';
  private logoutUrl: string = '';

  /**
   * Initialize login refresh
   */
  public initialize(): void {
    this.initializeTimeoutModal();
    this.initializeBackendLockedModal();
    this.initializeLoginForm();
    this.startTask();
  }

  /**
   * Start the task
   */
  public startTask(): void {
    if (this.intervalId !== null) {
      return;
    }
    // set interval to 60 seconds
63
    let interval: number = this.intervalTime * 1000;
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
    this.intervalId = setInterval(this.checkActiveSession, interval);
  }

  /**
   * Stop the task
   */
  public stopTask(): void {
    clearInterval(this.intervalId);
    this.intervalId = null;
  }

  /**
   * Set interval time
   *
   * @param {number} intervalTime
   */
  public setIntervalTime(intervalTime: number): void {
    // To avoid the integer overflow in setInterval, we limit the interval time to be one request per day
    this.intervalTime = Math.min(intervalTime, 86400);
  }

  /**
   * Set the logout URL
   *
   * @param {string} logoutUrl
   */
  public setLogoutUrl(logoutUrl: string): void {
    this.logoutUrl = logoutUrl;
  }

  /**
   * Set login frameset url
   */
  public setLoginFramesetUrl(loginFramesetUrl: string): void {
    this.loginFramesetUrl = loginFramesetUrl;
  }

  /**
   * Shows the timeout dialog. If the backend is not focused, a Web Notification
   * is displayed, too.
   */
  public showTimeoutModal(): void {
    this.isTimingOut = true;
    this.$timeoutModal.modal(this.options.modalConfig);
108
    this.$timeoutModal.modal('show');
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
    this.fillProgressbar(this.$timeoutModal);
  }

  /**
   * Hides the timeout dialog. If a Web Notification is displayed, close it too.
   */
  public hideTimeoutModal(): void {
    this.isTimingOut = false;
    this.$timeoutModal.modal('hide');
  }

  /**
   * Shows the "backend locked" dialog.
   */
  public showBackendLockedModal(): void {
    this.$backendLockedModal.modal(this.options.modalConfig);
125
    this.$backendLockedModal.modal('show');
126
127
128
129
130
131
132
133
134
135
136
137
138
139
  }

  /**
   * Hides the "backend locked" dialog.
   */
  public hideBackendLockedModal(): void {
    this.$backendLockedModal.modal('hide');
  }

  /**
   * Shows the login form.
   */
  public showLoginForm(): void {
    // log off for sure
140
    new AjaxRequest(TYPO3.settings.ajaxUrls.logout).get().then((): void => {
141
142
143
144
145
146
      if (TYPO3.configuration.showRefreshLoginPopup) {
        this.showLoginPopup();
      } else {
        this.$loginForm.modal(this.options.modalConfig);
        this.$loginForm.modal('show');
      }
147
148
149
150
151
152
153
154
155
156
    });
  }

  /**
   * Opens the login form in a new window.
   */
  public showLoginPopup(): void {
    const vHWin = window.open(
      this.loginFramesetUrl,
      'relogin_' + Math.random().toString(16).slice(2),
157
      'height=450,width=700,status=0,menubar=0,location=1',
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    );
    if (vHWin) {
      vHWin.focus();
    }
  }

  /**
   * Hides the login form.
   */
  public hideLoginForm(): void {
    this.$loginForm.modal('hide');
  }

  /**
   * Generates the modal displayed if the backend is locked.
   */
  protected initializeBackendLockedModal(): void {
    this.$backendLockedModal = this.generateModal(MarkupIdentifiers.lockedModal);
    this.$backendLockedModal.find('.modal-header h4').text(TYPO3.lang['mess.please_wait']);
    this.$backendLockedModal.find('.modal-body').append(
178
      $('<p />').text(TYPO3.lang['mess.be_locked']),
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
    );
    this.$backendLockedModal.find('.modal-footer').remove();

    $('body').append(this.$backendLockedModal);
  }

  /**
   * Generates the modal displayed on near session time outs
   */
  protected initializeTimeoutModal(): void {
    this.$timeoutModal = this.generateModal(MarkupIdentifiers.loginrefresh);
    this.$timeoutModal.addClass('modal-severity-notice');
    this.$timeoutModal.find('.modal-header h4').text(TYPO3.lang['mess.login_about_to_expire_title']);
    this.$timeoutModal.find('.modal-body').append(
      $('<p />').text(TYPO3.lang['mess.login_about_to_expire']),
      $('<div />', {class: 'progress'}).append(
        $('<div />', {
          class: 'progress-bar progress-bar-warning progress-bar-striped active',
          role: 'progressbar',
          'aria-valuemin': '0',
199
          'aria-valuemax': '100',
200
        }).append(
201
202
203
          $('<span />', {class: 'sr-only'}),
        ),
      ),
204
205
206
207
    );
    this.$timeoutModal.find('.modal-footer').append(
      $('<button />', {
        class: 'btn btn-default',
208
        'data-action': 'logout',
209
210
211
212
213
      }).text(TYPO3.lang['mess.refresh_login_logout_button']).on('click', () => {
        top.location.href = this.logoutUrl;
      }),
      $('<button />', {
        class: 'btn btn-primary t3js-active',
214
        'data-action': 'refreshSession',
215
      }).text(TYPO3.lang['mess.refresh_login_refresh_button']).on('click', () => {
216
217
        new AjaxRequest(TYPO3.settings.ajaxUrls.login_timedout).get().then((): void => {
          this.hideTimeoutModal();
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
    );
    this.registerDefaultModalEvents(this.$timeoutModal);

    $('body').append(this.$timeoutModal);
  }

  /**
   * Generates the login form displayed if the session has timed out.
   */
  protected initializeLoginForm(): void {
    if (TYPO3.configuration.showRefreshLoginPopup) {
      // dialog is not required if "showRefreshLoginPopup" is enabled
      return;
    }

    this.$loginForm = this.generateModal(MarkupIdentifiers.loginFormModal);
    this.$loginForm.addClass('modal-notice');
    let refresh_login_title = String(TYPO3.lang['mess.refresh_login_title']).replace('%s', TYPO3.configuration.username);
    this.$loginForm.find('.modal-header h4').text(refresh_login_title);
    this.$loginForm.find('.modal-body').append(
      $('<p />').text(TYPO3.lang['mess.login_expired']),
      $('<form />', {
        id: 'beLoginRefresh',
        method: 'POST',
244
        action: TYPO3.settings.ajaxUrls.login,
245
246
247
248
249
250
251
252
      }).append(
        $('<div />', {class: 'form-group'}).append(
          $('<input />', {
            type: 'password',
            name: 'p_field',
            autofocus: 'autofocus',
            class: 'form-control',
            placeholder: TYPO3.lang['mess.refresh_login_password'],
253
254
            'data-rsa-encryption': 't3-loginrefres-userident',
          }),
255
256
        ),
        $('<input />', {type: 'hidden', name: 'username', value: TYPO3.configuration.username}),
257
258
        $('<input />', {type: 'hidden', name: 'userident', id: 't3-loginrefres-userident'}),
      ),
259
260
261
262
    );
    this.$loginForm.find('.modal-footer').append(
      $('<a />', {
        href: this.logoutUrl,
263
        class: 'btn btn-default',
264
265
266
267
      }).text(TYPO3.lang['mess.refresh_exit_button']),
      $('<button />', {type: 'button', class: 'btn btn-primary', 'data-action': 'refreshSession'})
        .text(TYPO3.lang['mess.refresh_login_button'])
        .on('click', () => {
268
          this.$loginForm.find('form').trigger('submit');
269
        }),
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
    );
    this.registerDefaultModalEvents(this.$loginForm).on('submit', this.submitForm);
    $('body').append(this.$loginForm);
    if (require.specified('TYPO3/CMS/Rsaauth/RsaEncryptionModule')) {
      require(['TYPO3/CMS/Rsaauth/RsaEncryptionModule'], function(RsaEncryption: any): void {
        RsaEncryption.registerForm($('#beLoginRefresh').get(0));
      });
    }
  }

  /**
   * Generates a modal dialog as template.
   *
   * @param {string} identifier
   * @returns {JQuery}
   */
  protected generateModal(identifier: string): JQuery {
    return $('<div />', {
      id: identifier,
289
      class: 't3js-modal ' + identifier + ' modal modal-type-default modal-severity-notice modal-style-light modal-size-small fade',
290
291
292
293
    }).append(
      $('<div />', {class: 'modal-dialog'}).append(
        $('<div />', {class: 'modal-content'}).append(
          $('<div />', {class: 'modal-header'}).append(
294
            $('<h4 />', {class: 'modal-title'}),
295
296
          ),
          $('<div />', {class: 'modal-body'}),
297
298
299
          $('<div />', {class: 'modal-footer'}),
        ),
      ),
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
    );
  }

  /**
   * Fills the progressbar attached to the given modal.
   */
  protected fillProgressbar($activeModal: JQuery): void {
    if (!this.isTimingOut) {
      return;
    }

    const max = 100;
    let current = 0;
    const $progressBar = $activeModal.find('.progress-bar');
    const $srText = $progressBar.children('.sr-only');

    const progress = setInterval(() => {
      const isOverdue = (current >= max);
      if (!this.isTimingOut || isOverdue) {
        clearInterval(progress);

        if (isOverdue) {
          // show login form
          this.hideTimeoutModal();
          this.showLoginForm();
        }

        // reset current
        current = 0;
      } else {
        current += 1;
      }

      const percentText = (current) + '%';
      $progressBar.css('width', percentText);
      $srText.text(percentText);
    },                           300);
  }

  /**
   * Creates additional data based on the security level and "submits" the form
   * via an AJAX request.
   *
   * @param {JQueryEventObject} event
   */
345
  protected submitForm = (event: JQueryEventObject): void => {
346
347
348
349
350
351
352
353
    event.preventDefault();

    const $form = this.$loginForm.find('form');
    const $passwordField = $form.find('input[name=p_field]');
    const $useridentField = $form.find('input[name=userident]');
    const passwordFieldValue = $passwordField.val();

    if (passwordFieldValue === '' && $useridentField.val() === '') {
354
      Notification.error(TYPO3.lang['mess.refresh_login_failed'], TYPO3.lang['mess.refresh_login_emptyPassword']);
355
356
357
358
359
360
361
362
363
364
      $passwordField.focus();
      return;
    }

    if (passwordFieldValue) {
      $useridentField.val(passwordFieldValue);
      $passwordField.val('');
    }

    const postData: any = {
365
      login_status: 'login',
366
    };
367
    $.each($form.serializeArray(), function (i: number, field: any): void {
368
369
      postData[field.name] = field.value;
    });
370
371
372
373
374
375
    new AjaxRequest($form.attr('action')).post(postData).then(async (response: AjaxResponse): Promise<void> => {
      const data = await response.resolve();
      if (data.login.success) {
        // User is logged in
        this.hideLoginForm();
      } else {
376
        Notification.error(TYPO3.lang['mess.refresh_login_failed'], TYPO3.lang['mess.refresh_login_failed_message']);
377
378
        $passwordField.focus();
      }
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
    });
  }

  /**
   * Registers the (shown|hidden).bs.modal events.
   * If a modal is shown, the interval check is stopped. If the modal hides,
   * the interval check starts again.
   * This method is not invoked for the backend locked modal, because we still
   * need to check if the backend gets unlocked again.
   *
   * @param {JQuery} $modal
   * @returns {JQuery}
   */
  protected registerDefaultModalEvents($modal: JQuery): JQuery {
    $modal.on('hidden.bs.modal', () => {
      this.startTask();
    }).on('shown.bs.modal', () => {
      this.stopTask();
      // focus the button which was configured as active button
      this.$timeoutModal.find('.modal-footer .t3js-active').first().focus();
    });
    return $modal;
  }

  /**
   * Periodically called task that checks if
   *
   * - the user's backend session is about to expire
   * - the user's backend session has expired
   * - the backend got locked
   *
   * and opens a dialog.
   */
  protected checkActiveSession = (): void => {
413
414
415
    new AjaxRequest(TYPO3.settings.ajaxUrls.login_timedout).get().then(async (response: AjaxResponse): Promise<void> => {
      const data = await response.resolve();
      if (data.login.locked) {
416
417
418
        if (!this.backendIsLocked) {
          this.backendIsLocked = true;
          this.showBackendLockedModal();
419
        }
420
421
422
423
424
425
      } else {
        if (this.backendIsLocked) {
          this.backendIsLocked = false;
          this.hideBackendLockedModal();
        }
      }
426

427
      if (!this.backendIsLocked) {
428
429
        if (data.login.timed_out || data.login.will_time_out) {
          data.login.timed_out
430
431
            ? this.showLoginForm()
            : this.showTimeoutModal();
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
        }
      }
    });
  }
}

let loginRefreshObject;
try {
  // fetch from opening window
  if (window.opener && window.opener.TYPO3 && window.opener.TYPO3.LoginRefresh) {
    loginRefreshObject = window.opener.TYPO3.LoginRefresh;
  }

  // fetch from parent
  if (parent && parent.window.TYPO3 && parent.window.TYPO3.LoginRefresh) {
    loginRefreshObject = parent.window.TYPO3.LoginRefresh;
  }

  // fetch object from outer frame
  if (top && top.TYPO3 && top.TYPO3.LoginRefresh) {
    loginRefreshObject = top.TYPO3.LoginRefresh;
  }
454
} catch {
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
  // This only happens if the opener, parent or top is some other url (eg a local file)
  // which loaded the current window. Then the browser's cross domain policy jumps in
  // and raises an exception.
  // For this case we are safe and we can create our global object below.
}

if (!loginRefreshObject) {
  loginRefreshObject = new LoginRefresh();

  // attach to global frame
  if (typeof TYPO3 !== 'undefined') {
    TYPO3.LoginRefresh = loginRefreshObject;
  }
}

export = loginRefreshObject;