You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

session-heartbeat.js 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
  3. *
  4. * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
  5. *
  6. * @license GNU AGPL version 3 or any later version
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License as
  10. * published by the Free Software Foundation, either version 3 of the
  11. * License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. import $ from 'jquery'
  22. import { generateUrl } from './OC/routing'
  23. import OC from './OC'
  24. import { setToken as setRequestToken } from './OC/requesttoken'
  25. /**
  26. * session heartbeat (defaults to enabled)
  27. * @returns {boolean}
  28. */
  29. const keepSessionAlive = () => {
  30. return OC.config.session_keepalive === undefined
  31. || !!OC.config.session_keepalive
  32. }
  33. /**
  34. * get interval in seconds
  35. * @returns {Number}
  36. */
  37. const getInterval = () => {
  38. let interval = NaN
  39. if (OC.config.session_lifetime) {
  40. interval = Math.floor(OC.config.session_lifetime / 2)
  41. }
  42. // minimum one minute, max 24 hours, default 15 minutes
  43. return Math.min(
  44. 24 * 3600,
  45. Math.max(
  46. 60,
  47. isNaN(interval) ? 900 : interval
  48. )
  49. )
  50. }
  51. /**
  52. * Calls the server periodically to ensure that session and CSRF
  53. * token doesn't expire
  54. */
  55. export const initSessionHeartBeat = () => {
  56. if (!keepSessionAlive()) {
  57. console.info('session heartbeat disabled')
  58. return
  59. }
  60. setInterval(() => {
  61. $.ajax(generateUrl('/csrftoken'))
  62. .then(resp => setRequestToken(resp.token))
  63. .fail(e => {
  64. console.error('session heartbeat failed', e)
  65. })
  66. }, getInterval() * 1000)
  67. }