Repository: orangehill/bootstrap-session-timeout Branch: master Commit: 08f8f2a6a954 Files: 16 Total size: 33.4 KB Directory structure: gitextract_r551hflo/ ├── .gitignore ├── .jshintrc ├── Gruntfile.js ├── LICENSE.md ├── README.md ├── bower.json ├── dist/ │ └── bootstrap-session-timeout.js ├── examples/ │ ├── basic.html │ ├── countdown-bar.html │ ├── countdown-timer.html │ ├── custom-callback.html │ ├── keep-alive.html │ ├── locked.html │ └── login.html ├── index.html └── package.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /bower_components/ /node_modules/ *.sublime-project *.sublime-workspace ================================================ FILE: .jshintrc ================================================ { "curly": true, "eqeqeq": true, "immed": true, "latedef": true, "newcap": true, "noarg": true, "sub": true, "undef": true, "unused": true, "boss": true, "eqnull": true, "node": true, "globals": { "document": true, "window": true, "jQuery": true, "$": true } } ================================================ FILE: Gruntfile.js ================================================ 'use strict'; module.exports = function(grunt) { // Show elapsed time at the end require('time-grunt')(grunt); // Load all grunt tasks require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ connect: { options: { port: 9000, // Enable hostname '0.0.0.0' to access the server from outside. hostname: '0.0.0.0', livereload: 36729 }, livereload: { options: { open: 'http://localhost:9000', middleware: function(connect) { return [ connect.static('./') ]; } } } }, jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, dist: { src: ['dist/bootstrap-session-timeout.js'] } }, watch: { dist: { files: '<%= jshint.dist.src %>', tasks: ['jshint:dist'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '*.html', 'examples/*.html', 'dist/*.js' ] } }, uglify: { dist: { files: { 'dist/bootstrap-session-timeout.min.js': ['<%= jshint.dist.src %>'] } } } }); // Default task. grunt.registerTask('default', ['jshint']); grunt.registerTask('dev', ['connect:livereload', 'watch']); grunt.registerTask('min', ['jshint', 'uglify']); }; ================================================ FILE: LICENSE.md ================================================ MIT License (MIT) Copyright (c) 2013 Travis Horn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # bootstrap-session-timeout Inspired by [jquery-sessionTimeout-bootstrap by maxfierke](https://github.com/maxfierke/jquery-sessionTimeout-bootstrap) There have been a number of major upgrades. For example, as long as the user is doing something on the page, he will never get a timeout. The original plugin launched a timeout warning dialog in a fixed amount of time regardless of user activity. See description and documentation for more information. You can easily upgrade from jquery-sessionTimeout-bootstrap to bootstrap-session-timeout, since the basic options have been inherited from jquery-sessionTimeout-bootstrap and have not been renamed. ## Description After a set amount of idle time, a Bootstrap warning dialog is shown to the user with the option to either log out, or stay connected. If "Logout" button is selected, the page is redirected to a logout URL. If "Stay Connected" is selected the dialog closes and the session is kept alive. If no option is selected after another set amount of idle time, the page is automatically redirected to a set timeout URL. Idle time is defined as no mouse, keyboard or touch event activity registered by the browser. As long as the user is active, the (optional) keep-alive URL keeps getting pinged and the session stays alive. If you have no need to keep the server-side session alive via the keep-alive URL, you can also use this plugin as a simple lock mechanism that redirects to your lock-session or log-out URL after a set amount of idle time. ## Getting Started 1. Download or git clone. 2. Run `bower install` to install dependencies or if you prefer to do it manually: include jQuery, Bootstrap JS and CSS (required if you want to use Bootstrap modal window). 3. Include `bootstrap-session-timeout.js` or the minified version `bootstrap-session-timeout.min.js` 4. Call `$.sessionTimeout();` on document ready. See available options below or take a look at the examples. ## Documentation ### Options **title**
Type: `String` Default: `'Your session is about to expire!'` This is the text shown to user via Bootstrap warning dialog after warning period. (modal title) **message**
Type: `String` Default: `'Your session is about to expire.'` This is the text shown to user via Bootstrap warning dialog after warning period. **logoutButton**
Type: `String` Default: `'Logout'` This is the text shown to user via Bootstrap warning dialog after warning period in the logout button. **keepAliveButton**
Type: `String` Default: `'Stay Connected'` This is the text shown to user via Bootstrap warning dialog after warning period in the Keep Alive button. **keepAliveUrl** Type: `String` Default: `'/keep-alive'` URL to ping via AJAX POST to keep the session alive. This resource should do something innocuous that would keep the session alive, which will depend on your server-side platform. **keepAlive** Type: `Boolean` Default: `true` If `true`, the plugin keeps pinging the `keepAliveUrl` for as long as the user is active. The time between two pings is set by the `keepAliveInterval` option. If you have no server-side session timeout to worry about, feel free to set this one to `false` to prevent unnecessary network activity. **keepAliveInterval** Type: `Integer` Default: `5000` (5 seconds) Time in milliseconds between two keep-alive pings. **ajaxType** Type: `String` Default: `'POST'` If you need to specify the ajax method **ajaxData** Type: `String` Default: `''` If you need to send some data via AJAX POST to your `keepAliveUrl`, you can use this option. **redirUrl** Type: `String` Default: `'/timed-out'` URL to take browser to if no action is take after the warning. **logoutUrl** Type: `String` Default: `'/log-out'` URL to take browser to if user clicks "Logout" on the Bootstrap warning dialog. **warnAfter** Type: `Integer` Default: `900000` (15 minutes) Time in milliseconds after page is opened until warning dialog is opened. **redirAfter** Type: `Integer` Default: `1200000` (20 minutes) Time in milliseconds after page is opened until browser is redirected to `redirUrl`. **ignoreUserActivity** Type: `Boolean` Default: `false` If `true`, this will launch the Bootstrap warning dialog / redirect (or callback functions) in a set amounts of time regardless of user activity. This in turn makes the plugin act much like the [jquery-sessionTimeout-bootstrap by maxfierke](https://github.com/maxfierke/jquery-sessionTimeout-bootstrap) plugin. **countdownSmart** Type: `Boolean` Default: `false` If `true`, displays minutes as well as seconds in the countdown timer (e.g. "3m 14s"). Displays only seconds when timer is under one minute (e.g. "42s"). **countdownMessage** Type: `String` or `Boolean` Default: `false` If you want a custom sentence to appear in the warning dialog with a timer showing the seconds remaining, use this option. Example: `countdownMessage: 'Redirecting in {timer}.'` Place the `{timer}` string where you want the numeric countdown to appear. Another example: `countdownMessage: '{timer} remaining.'`. Can be combined with countdownBar option or used independently. **countdownBar** Type: `Boolean` Default: `false` If `true`, ads a countdown bar (uses Bootstrap progress bar) to the warning dialog. Can be combined with countdownMessage option or used independently. **onStart** Type: `Function` or `Boolean` Default: `false` Optional callback fired when first calling the plugin and every time user refreshes the session (on any mouse, keyboard or touch action). Takes options object as the only argument. **onWarn** Type: `Function` or `Boolean` Default: `false` Custom callback you can use instead of showing the Bootstrap warning dialog. Takes options object as the only argument. Redirect action will still occur unless you also add the `onRedir` callback. **onRedir** Type: `Function` or `Boolean` Default: `false` Custom callback you can use instead of redirecting the user to `redirUrl`. Takes options object as the only argument. ## Examples You can play around with the examples in the `/examples` directory. **Basic Usage** Shows the warning dialog after one minute. The dialog is visible for another minute. If user takes no action (interacts with the page in any way), browser is redirected to `redirUrl`. On any user action (mouse, keyboard or touch) the timeout timer is reset. Of course, you will still need to close the dialog. ```js $.sessionTimeout({ message: 'Your session will be locked in one minute.', keepAliveUrl: 'keep-alive.html', logoutUrl: 'login.html', redirUrl: 'locked.html', warnAfter: 60000, redirAfter: 120000 }); ``` **With onWarn Callback** Shows the "Warning!" alert after one minute. If user takes no action (interacts with the page in any way), after one more minute the browser is redirected to `redirUrl`. On any user action (mouse, keyboard or touch) the timeout timer is reset. ```js $.sessionTimeout({ redirUrl: 'locked.html', warnAfter: 60000, redirAfter: 120000, onWarn: function () { alert('Warning!'); } }); ``` **With both onWarn and onRedir Callback** Console logs the "Your session will soon expire!" text after one minute. If user takes no action (interacts with the page in any way), after two more minutes the "Your session has expired!" alert gets shown. No redirection occurs. On any user action (mouse, keyboard or touch) the timeout timer is reset. ```js $.sessionTimeout({ warnAfter: 60000, redirAfter: 180000, onWarn: function () { console.log('Your session will soon expire!'); }, onRedir: function () { alert('Your session has expired!'); } }); ``` **With countdown message and bar displayed in warning dialog** Same as basic usage except you'll also see the countdown message and countdown bar in the warning dialog. Uses Bootstrap progress bar. In countdownMessage place the `{timer}` string where you want the numeric countdown (seconds) to appear. ```js $.sessionTimeout({ keepAliveUrl: 'keep-alive.html', logoutUrl: 'login.html', redirUrl: 'locked.html', warnAfter: 60000, redirAfter: 120000, countdownMessage: 'Redirecting in {timer} seconds.', countdownBar: true }); ``` ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add comments for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/). ## Release History * **1.0.3** `2015-07-17` * Fixes various reported bugs * **1.0.2** `2015-02-10` * Added optional onStart callback. * All custom callbacks nowreceive options object as argument. * Added optional countdown message. Added optional countdown bar. * **1.0.1** `2014-01-23` * Added an option to send data to the keep-alive URL. * **1.0.0** `2014-01-22` * Initial release. ## License Copyright (c) 2014 [Orange Hill](http://www.orangehilldev.com). Licensed under the MIT license. ================================================ FILE: bower.json ================================================ { "name": "bootstrap-session-timeout", "version": "1.0.3", "homepage": "https://github.com/orangehill/bootstrap-session-timeout", "authors": [ "Vedran Opacic " ], "description": "Session timeout and keep-alive control with a nice Bootstrap warning dialog.", "keywords": [ "timeout", "time-out", "keepalive", "keep-alive", "session", "bootstrap", "bootstrap 3", "jquery", "javascript", "dialog" ], "license": "MIT", "ignore": [ "node_modules", "bower_components", "test", "tests" ], "dependencies": { "bootstrap": "~3.3.2", "jquery": "~2.1.3" } } ================================================ FILE: dist/bootstrap-session-timeout.js ================================================ /* * bootstrap-session-timeout * www.orangehilldev.com * * Copyright (c) 2014 Vedran Opacic * Licensed under the MIT license. */ (function($) { /*jshint multistr: true */ 'use strict'; $.sessionTimeout = function(options) { var defaults = { title: 'Your Session is About to Expire!', message: 'Your session is about to expire.', logoutButton: 'Logout', keepAliveButton: 'Stay Connected', keepAliveUrl: '/keep-alive', ajaxType: 'POST', ajaxData: '', redirUrl: '/timed-out', logoutUrl: '/log-out', warnAfter: 900000, // 15 minutes redirAfter: 1200000, // 20 minutes keepAliveInterval: 5000, keepAlive: true, ignoreUserActivity: false, onStart: false, onWarn: false, onRedir: false, countdownMessage: false, countdownBar: false, countdownSmart: false }; var opt = defaults, timer, countdown = {}; // Extend user-set options over defaults if (options) { opt = $.extend(defaults, options); } // Some error handling if options are miss-configured if (opt.warnAfter >= opt.redirAfter) { console.error('Bootstrap-session-timeout plugin is miss-configured. Option "redirAfter" must be equal or greater than "warnAfter".'); return false; } // Unless user set his own callback function, prepare bootstrap modal elements and events if (typeof opt.onWarn !== 'function') { // If opt.countdownMessage is defined add a coundown timer message to the modal dialog var countdownMessage = opt.countdownMessage ? '

' + opt.countdownMessage.replace(/{timer}/g, '') + '

' : ''; var coundownBarHtml = opt.countdownBar ? '
\
\ \
\
' : ''; // Create timeout warning dialog $('body').append(''); // "Logout" button click $('#session-timeout-dialog-logout').on('click', function() { window.location = opt.logoutUrl; }); // "Stay Connected" button click $('#session-timeout-dialog').on('hide.bs.modal', function() { // Restart session timer startSessionTimer(); }); } // Reset timer on any of these events if (!opt.ignoreUserActivity) { var mousePosition = [-1, -1]; $(document).on('keyup mouseup mousemove touchend touchmove', function(e) { if (e.type === 'mousemove') { // Solves mousemove even when mouse not moving issue on Chrome: // https://code.google.com/p/chromium/issues/detail?id=241476 if (e.clientX === mousePosition[0] && e.clientY === mousePosition[1]) { return; } mousePosition[0] = e.clientX; mousePosition[1] = e.clientY; } startSessionTimer(); // If they moved the mouse not only reset the counter // but remove the modal too! if ($('#session-timeout-dialog').length > 0 && $('#session-timeout-dialog').data('bs.modal') && $('#session-timeout-dialog').data('bs.modal').isShown) { // http://stackoverflow.com/questions/11519660/twitter-bootstrap-modal-backdrop-doesnt-disappear $('#session-timeout-dialog').modal('hide'); $('body').removeClass('modal-open'); $('div.modal-backdrop').remove(); } }); } // Keeps the server side connection live, by pingin url set in keepAliveUrl option. // KeepAlivePinged is a helper var to ensure the functionality of the keepAliveInterval option var keepAlivePinged = false; function keepAlive() { if (!keepAlivePinged) { // Ping keepalive URL using (if provided) data and type from options $.ajax({ type: opt.ajaxType, url: opt.keepAliveUrl, data: opt.ajaxData }); keepAlivePinged = true; setTimeout(function() { keepAlivePinged = false; }, opt.keepAliveInterval); } } function startSessionTimer() { // Clear session timer clearTimeout(timer); if (opt.countdownMessage || opt.countdownBar) { startCountdownTimer('session', true); } if (typeof opt.onStart === 'function') { opt.onStart(opt); } // If keepAlive option is set to "true", ping the "keepAliveUrl" url if (opt.keepAlive) { keepAlive(); } // Set session timer timer = setTimeout(function() { // Check for onWarn callback function and if there is none, launch dialog if (typeof opt.onWarn !== 'function') { $('#session-timeout-dialog').modal('show'); } else { opt.onWarn(opt); } // Start dialog timer startDialogTimer(); }, opt.warnAfter); } function startDialogTimer() { // Clear session timer clearTimeout(timer); if (!$('#session-timeout-dialog').hasClass('in') && (opt.countdownMessage || opt.countdownBar)) { // If warning dialog is not already open and either opt.countdownMessage // or opt.countdownBar are set start countdown startCountdownTimer('dialog', true); } // Set dialog timer timer = setTimeout(function() { // Check for onRedir callback function and if there is none, launch redirect if (typeof opt.onRedir !== 'function') { window.location = opt.redirUrl; } else { opt.onRedir(opt); } }, (opt.redirAfter - opt.warnAfter)); } function startCountdownTimer(type, reset) { // Clear countdown timer clearTimeout(countdown.timer); if (type === 'dialog' && reset) { // If triggered by startDialogTimer start warning countdown countdown.timeLeft = Math.floor((opt.redirAfter - opt.warnAfter) / 1000); } else if (type === 'session' && reset) { // If triggered by startSessionTimer start full countdown // (this is needed if user doesn't close the warning dialog) countdown.timeLeft = Math.floor(opt.redirAfter / 1000); } // If opt.countdownBar is true, calculate remaining time percentage if (opt.countdownBar && type === 'dialog') { countdown.percentLeft = Math.floor(countdown.timeLeft / ((opt.redirAfter - opt.warnAfter) / 1000) * 100); } else if (opt.countdownBar && type === 'session') { countdown.percentLeft = Math.floor(countdown.timeLeft / (opt.redirAfter / 1000) * 100); } // Set countdown message time value var countdownEl = $('.countdown-holder'); var secondsLeft = countdown.timeLeft >= 0 ? countdown.timeLeft : 0; if (opt.countdownSmart) { var minLeft = Math.floor(secondsLeft / 60); var secRemain = secondsLeft % 60; var countTxt = minLeft > 0 ? minLeft + 'm' : ''; if (countTxt.length > 0) { countTxt += ' '; } countTxt += secRemain + 's'; countdownEl.text(countTxt); } else { countdownEl.text(secondsLeft + "s"); } // Set countdown message time value if (opt.countdownBar) { $('.countdown-bar').css('width', countdown.percentLeft + '%'); } // Countdown by one second countdown.timeLeft = countdown.timeLeft - 1; countdown.timer = setTimeout(function() { // Call self after one second startCountdownTimer(type); }, 1000); } // Start session timer startSessionTimer(); }; })(jQuery); ================================================ FILE: examples/basic.html ================================================ Bootstrap-session-timeout - Basic Usage

Bootstrap-session-timeout

Basic Usage


Shows the warning dialog after 3 seconds. If user takes no action (interacts with the page in any way), browser is redirected to redirUrl. On any user action (mouse, keyboard or touch) the timeout timer is reset.

            $.sessionTimeout({
                keepAliveUrl: 'keep-alive.html',
                logoutUrl: 'login.html',
                redirUrl: 'locked.html',
                warnAfter: 3000,
                redirAfter: 10000
            });
        
Back to Demo Index
================================================ FILE: examples/countdown-bar.html ================================================ Bootstrap-session-timeout - Countdown Timer

Bootstrap-session-timeout

Countdown Timer


Shows the warning dialog with countdown bar after 3 seconds. If user takes no action (interacts with the page in any way), browser is redirected to redirUrl. On any user action (mouse, keyboard or touch) the timeout timer as well as the countdown timer are reset (visible if you don't close the warning dialog).

Note: you can also combine the countdown bar with a countdown timer message.

            $.sessionTimeout({
                keepAliveUrl: 'keep-alive.html',
                logoutUrl: 'login.html',
                redirUrl: 'locked.html',
                warnAfter: 3000,
                redirAfter: 10000,
                countdownBar: true
            });
        
Back to Demo Index
================================================ FILE: examples/countdown-timer.html ================================================ Bootstrap-session-timeout - Countdown Timer

Bootstrap-session-timeout

Countdown Timer


Shows the warning dialog with countdown timer after 3 seconds. If user takes no action (interacts with the page in any way), browser is redirected to redirUrl. On any user action (mouse, keyboard or touch) the timeout timer as well as the countdown timer are reset (visible if you don't close the warning dialog).

            $.sessionTimeout({
                keepAliveUrl: 'keep-alive.html',
                logoutUrl: 'login.html',
                redirUrl: 'locked.html',
                warnAfter: 3000,
                redirAfter: 10000,
                countdownMessage: 'Redirecting in {timer} seconds.'
            });
        
Back to Demo Index
================================================ FILE: examples/custom-callback.html ================================================ Bootstrap-session-timeout - Countdown Timer

Bootstrap-session-timeout

Custom Callback


Shows an example of using custom callback functions for warning and redirect.

Session Status:

            $.sessionTimeout({
                keepAliveUrl: 'keep-alive.html',
                logoutUrl: 'login.html',
                warnAfter: 3000,
                redirAfter: 20000,
                onStart: function () {
                    $('.jumbotron').css('background', '#398439').find('p').addClass('hidden');
                    $('#fine').removeClass('hidden')
                },
                onWarn: function () {
                    $('.jumbotron').css('background', '#b92c28').find('p').addClass('hidden');
                    $('#warn').removeClass('hidden')
                },
                onRedir: function (opt) {
                    window.location = opt.logoutUrl;
                }
            });
        
Back to Demo Index
================================================ FILE: examples/keep-alive.html ================================================ Bootstrap-session-timeout - Basic Usage

Bootstrap-session-timeout

Dummy keep alive URL


This would be your server-side URL to refresh user session.

================================================ FILE: examples/locked.html ================================================ Bootstrap-session-timeout - Logged Out

Bootstrap-session-timeout

Logged Out


You have been redirected to a logout URL.

================================================ FILE: examples/login.html ================================================ Bootstrap-session-timeout - Login Page

Bootstrap-session-timeout

Login


This would be your login page.

================================================ FILE: index.html ================================================ Bootstrap-session-timeout - Basic Usage

Bootstrap-session-timeout demo


Basic Demo
Countdown Message Demo
Countdown Bar Demo
Custom Callback Demo
================================================ FILE: package.json ================================================ { "name": "bootstrap-session-timeout", "version": "1.0.3", "main": "dist/bootstrap-session-timeout.js", "description": "Session timeout and keep-alive control with a nice Bootstrap warning dialog.", "homepage": "https://github.com/orangehill/bootstrap-session-timeout", "bugs": "https://github.com/orangehill/bootstrap-session-timeout/issues", "author": "Vedran Opacic, vedran.opacic@orangehilldev.com", "repository": { "type": "git", "url": "https://github.com/orangehill/bootstrap-session-timeout" }, "licenses": [ { "type": "MIT" } ], "keywords": [ "timeout", "time-out", "keepalive", "keep-alive", "session", "bootstrap", "bootstrap 3", "jquery", "javascript", "dialog" ], "devDependencies": { "bower": "^1.3.5", "grunt-contrib-connect": "*", "grunt-contrib-jshint": "~0.7.0", "grunt-contrib-uglify": "~0.3.1", "grunt-contrib-watch": "~0.5.0", "jshint-stylish": "~0.1.3", "load-grunt-tasks": "~0.2.0", "time-grunt": "~0.2.0" } }