{"id":15546849,"url":"https://github.com/elius94/users-session-manager","last_synced_at":"2026-02-03T08:03:45.215Z","repository":{"id":41972883,"uuid":"429393583","full_name":"Elius94/users-session-manager","owner":"Elius94","description":"A simple Node.js module to manage users sessions on a web application or any kind of JS apps It uses a Singleton pattern to ensure that only one instance of the module is running at a time. SessionManager is a singleton class that can be used to manage users sessions. For every user that logs in, a new session is created and stored in the database. Every session has a unique ID that is generated by the system. Every session has a setTimeout that expires after a certain time (setSessionTimeout). When a user logs out, the session is deleted from the class. Every action fires an event that can be used to listen to the session manager.","archived":false,"fork":false,"pushed_at":"2023-10-17T10:40:28.000Z","size":344,"stargazers_count":2,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-06-10T12:46:06.357Z","etag":null,"topics":["api","javascript","login","login-page","login-system","nodejs","npm","npm-module","npm-package","npmjs","session-management","sessions","socket-io","users","webapp","webapps","websocket"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/users-session-manager","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Elius94.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-11-18T10:53:50.000Z","updated_at":"2022-03-16T17:41:02.000Z","dependencies_parsed_at":"2024-10-21T20:22:18.379Z","dependency_job_id":null,"html_url":"https://github.com/Elius94/users-session-manager","commit_stats":{"total_commits":85,"total_committers":2,"mean_commits":42.5,"dds":0.03529411764705881,"last_synced_commit":"289160822519dcec6dc110177c593da59f742912"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"purl":"pkg:github/Elius94/users-session-manager","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Elius94%2Fusers-session-manager","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Elius94%2Fusers-session-manager/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Elius94%2Fusers-session-manager/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Elius94%2Fusers-session-manager/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Elius94","download_url":"https://codeload.github.com/Elius94/users-session-manager/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Elius94%2Fusers-session-manager/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263980141,"owners_count":23538919,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","javascript","login","login-page","login-system","nodejs","npm","npm-module","npm-package","npmjs","session-management","sessions","socket-io","users","webapp","webapps","websocket"],"created_at":"2024-10-02T13:05:03.591Z","updated_at":"2026-02-03T08:03:45.189Z","avatar_url":"https://github.com/Elius94.png","language":"JavaScript","readme":"[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/Elius94/users-session-manager/Node.js%20Package)](https://github.com/Elius94/users-session-manager/actions/workflows/release-package.yml) [![Coverage Status](https://coveralls.io/repos/github/Elius94/users-session-manager/badge.svg?branch=main)](https://coveralls.io/github/Elius94/users-session-manager?branch=main) [![npm version](https://badge.fury.io/js/users-session-manager.svg)](https://npmjs.com/package/users-session-manager) [![npm](https://img.shields.io/npm/dt/users-session-manager)](https://npmjs.com/package/users-session-manager) ![npm bundle size](https://img.shields.io/bundlephobia/min/users-session-manager) ![GitHub](https://img.shields.io/github/license/elius94/users-session-manager)\n\n# users-session-manager\nA simple Node.js module to manage users sessions on a web application or any kind of JS apps\nIt uses a Singleton pattern to ensure that only one instance of the module is running at a time.\nSessionManager is a singleton class that can be used to manage users sessions.\nFor every user that logs in, a new session is created and stored in the database.\nEvery session has a unique ID that is generated by the system.\nEvery session has a setTimeout that expires after a certain time (setSessionTimeout).\nWhen a user logs out, the session is deleted from the class.\nEvery action fires an event that can be used to listen to the session manager.\n\n [![Readme Card](https://github-readme-stats.vercel.app/api/pin/?username=elius94\u0026repo=users-session-manager\u0026theme=github_dark\u0026show_icons=true)](https://github.com/Elius94/users-session-manager) [![https://nodei.co/npm/users-session-manager.png?downloads=true\u0026downloadRank=true\u0026stars=true](https://nodei.co/npm/users-session-manager.png?downloads=true\u0026downloadRank=true\u0026stars=true)](https://www.npmjs.com/package/users-session-manager)\n\n## Installation\n\nInstall with:\n```sh\nnpm i users-session-manager\n```\n\nExample of usage:\n```js\n// Import module with ES6 syntax\nimport { SessionManager } from 'users-session-manager'\n// or\n// const SessionManager = require('users-session-manager')\n\n// Create a new instance of the SessionManager class\nconst SM = new SessionManager()\n\n// Change session Expiration time:\nSM.setSessionTimeOut(6)\n\n// Call this to initialize a new user session\nSM.loadNewSession(\"Luca\")\nSM.loadNewSession(\"Fabio\")\n\n// You can listen to events emitted from this library through eventEmitter object exported\nSM.on(\"activeUserDeleted\", (key) =\u003e {\n    console.log(`User ${key} has been deleted`)\n})\n\nsetInterval(() =\u003e {\n    console.log(SM.getLoggedUsers())\n}, 5000)\n```\n\n## Example of Frontend and Backend session exchange\n```js\n\n// Frontend\nlet session_key = \"\"\n\n/**\n * Function to call try_login API\n *\n * @param {*} user username text\n * @param {*} pwd password text\n * @return {*} false if wrong login or the user table ROW of the selected user JSON format\n */\nasync function TryLogin(user, pwd) {\n    //console.log(ENDPOINT)\n    let credentials = {\n        \"username\": user,\n        \"password\": md5(pwd)\n    }\n    const rawResponse = await fetch(ENDPOINT + API_ROUTE, {\n        method: 'POST',\n        headers: {\n            'Accept': 'application/json',\n            'Content-Type': 'application/json',\n            'api_name': 'try_login'\n        },\n        body: JSON.stringify(credentials)\n    })\n    const user_data = await rawResponse.json()\n    if (user_data.length \u003e 0)\n        session_key = user_data[0].session_key // save session key to the global variable.\n\n        //console.log(\"user_data: \", user_data)\n    return user_data\n}\n\n// And on the next calls, you can use the session_key to call the API\n\n/**\n * Function to call get_table_data API\n *\n * @param {*} siteid number\n * @return {*} JSON object\n */\nasync function GetTableData(page) {\n    let body = {\n        page\n    }\n    const rawResponse = await fetch(ENDPOINT + API_ROUTE, {\n        method: 'POST',\n        headers: {\n            'Accept': 'application/json',\n            'Content-Type': 'application/json',\n            'session_key': session_key,\n            'api_name': 'get_table_data'\n        },\n        body: JSON.stringify(body)\n    })\n    const sectors = await rawResponse.json()\n    if (sectors.logout) Logout()\n        //console.log(\"sectors: \", sectors)\n    return sectors\n}\n\n// Backend\n\n// API.js route (cutted from the original file)\n...\ncase 'try_login':\n    response = {\n        accepted: false,\n        message: '',\n        user_data: {}\n    }\n    if (typeof(req.body) === 'object') {\n        try {\n            const body = req.body\n            const db_response = await db.tryLogin(body.username, body.password, true) // true to get the session key\n            if (db_response !== false) {\n                response.accepted = true\n                response.message = 'Welcome! 😘'\n                response.user_data = db_response\n                response.user_data.session_key = loadNewSession(body.username) // generate a new session key\n            } else {\n                response.accepted = false\n                response.message = 'Wrong username or password... Are you a f**ing HACKER? 💩💩💩'\n            }\n        } catch (error) {\n            response.accepted = false\n            response.message = 'Error in API call!'\n            response.user_data = null\n        } finally {\n            res.send(JSON.stringify(response))\n        }\n    }\n    break\ncase 'get_table_data':\n    response = {\n        accepted: false,\n        message: '',\n        table_data: {}\n    }\n    if (typeof(req.body) === 'object') {\n        try {\n            const body = req.body\n            if (await db.validateApiRequest(req.headers.session_key, \"get_data\")) {\n                const dbResponse = await db.getTableData(body.table)\n                if (dbResponse !== false) {\n                    response.accepted = true\n                    response.message = 'OK'\n                    response.table_data = dbResponse\n                } else {\n                    response.accepted = false\n                    response.message = 'Error in API call!'\n                    response.table_data = null\n                }\n            } else {\n                response.accepted = false\n                response.message = 'Action not allowed!'\n                console.warn('Action not allowed! api_name:', api_name)\n            }\n        } catch (error) {\n            response.accepted = false\n            response.message = 'Error in API call!'\n            response.analytics = null\n        } finally {\n            res.send(JSON.stringify(response))\n        }\n    }\n    break\n...\n\n// In file db.js (cutted from the original file)\n...\n/** \n * @async\n * @description Validate the session key\n * @param {string} sessionKey Session key\n * @param {string} action Action to validate\n * @throws Will throw if query to DB will fail\n * @returns {Promise\u003cboolean\u003e} Return true if session key is valid, false otherwise\n */\nasync function validateApiRequest(sessionKey, action = undefined) {\n    const username = getUsernameFromSessionKey(sessionKey)\n    if (username) {\n        let user_data = undefined\n        const query_user_id = {\n            text: 'SELECT users_management, dataset_management ' +\n                'FROM users WHERE username = $1;',\n            values: [username]\n        }\n        try {\n            const userIdRes = await pool.query(query_user_id)\n                // console.log('[getUserProfilePic]', userProfilePicPathRes.rows)\n            if (!userIdRes.rows.length) {\n                user_data = undefined\n                return false\n            } else {\n                /* This may be a string or null */\n                user_data = userIdRes.rows[0]\n            }\n        } catch (err) {\n            console.error(err)\n            throw err.message\n        }\n        switch (action) {\n            case \"get_data\":\n                {\n                    // check data validity here\n                }\n                break\n            default:\n                return true\n        }\n    }\n    return false\n}\n...\n```\n\n## Integrate with Socket.io server to notify clients\n\n```js\n// Import module with ES6 syntax\nimport { SessionManager } from '../index.js';\n\nconst http = require('http')\n\n// Create a new instance of the SessionManager class\nconst SM = new SessionManager();\n\n/**\n * Create and start an ioSocket server\n * @param {*} app\n * \"Express\" handle\n * @param {*} port\n * Port the server should listen on\n * @returns {SocketIO.Server}\n * The newly created server\n */\n function startServer(app, port) {\n    // Create an http server\n    const server = http.createServer(app)\n    server.listen(port)\n    server.on('error', function(error) { onError(error, port) })\n    server.on('listening', function() { onListening(server) })\n\n    // Create the socketIO server\n    const ENDPOINT = `localhost:3000`;\n    const { Server } = require(\"socket.io\");\n    const io = new Server(server, {\n        cors: {\n            origin: ENDPOINT,\n            methods: [\"GET\", \"POST\"]\n        }\n    });\n\n    io.on('connection', (sk) =\u003e {\n        console.log('Browser Connected!')\n        sk.on('session_key', async function(data) {\n            const key = data.session_key\n            console.log(`User ${data.user} joined key ${key}`)\n            sk.join(key)\n        })\n    })\n\n    return io\n}\n\nSM.initSocketReferences(startServer(app, port)) // Initialize the socket references\n\nSM.on(\"notifyClientToLogout\", (io, key) =\u003e { // When a user logs out, notify the client\n    console.debug(`Session is expired for key ${key}... Logging out now!`)\n    io.in(key).emit('logout') // Emit the logout event to the client\n})\n```\n\n## Exported APIs\n\n - ```eventEmitter```:\n    Node.js Event Emitter object, is extended by the class. It fires the following events:\n    - 'error': Called when some error happens (eg: Session is rejected)\n    - 'sessionDeleted': Called when a session is deleted or if expired\n    - 'sessionCreated': Called when a user session is created\n    - 'notifyClientToLogout': Called when a session timer is expired, bind this to a Socket.io server to force clients to logout\n\n## Integrate with metrics tools like PM2\n\n```js\nconst io = require('@pm2/io') // Initialize the pm2 io module\n\n// The PM2 IO metrics to monitor the number of connected users\nconst realtimeUser = io.counter({\n    name: 'Realtime Users',\n    id: 'app/realtime/users',\n})\n\nSM.on(\"sessionCreated\", (key) =\u003e { // When a user logs out, notify the client\n    realtimeUser.inc() // Increment the number of active users\n})\n\nSM.on(\"sessionDeleted\", (key) =\u003e { // When a user logs out, notify the client\n    realtimeUser.dec() // Decrement the number of active users\n})\n```\n\n## Classes\n\n\u003cdl\u003e\n\u003cdt\u003e\u003ca href=\"#SessionManager\"\u003eSessionManager\u003c/a\u003e ⇐ \u003ccode\u003eEventEmitter\u003c/code\u003e\u003c/dt\u003e\n\u003cdd\u003e\u003cp\u003eSessionManager is a class that manages the sessions of the users.\u003c/p\u003e\n\u003c/dd\u003e\n\u003c/dl\u003e\n\n## Constants\n\n\u003cdl\u003e\n\u003cdt\u003e\u003ca href=\"#sessions\"\u003esessions\u003c/a\u003e : \u003ccode\u003eObject\u003c/code\u003e\u003c/dt\u003e\n\u003cdd\u003e\u003cp\u003eThe sessions of the users.\u003c/p\u003e\n\u003c/dd\u003e\n\u003cdt\u003e\u003ca href=\"#MIN_SESSION_TIMEOUT\"\u003eMIN_SESSION_TIMEOUT\u003c/a\u003e : \u003ccode\u003enumber\u003c/code\u003e\u003c/dt\u003e\n\u003cdd\u003e\u003cp\u003eThe minimum session timeout.\u003c/p\u003e\n\u003c/dd\u003e\n\u003cdt\u003e\u003ca href=\"#settings\"\u003esettings\u003c/a\u003e : \u003ccode\u003eObject\u003c/code\u003e\u003c/dt\u003e\n\u003cdd\u003e\u003cp\u003eThe settings of the session manager.\u003c/p\u003e\n\u003c/dd\u003e\n\u003c/dl\u003e\n\n## Functions\n\n\u003cdl\u003e\n\u003cdt\u003e\u003ca href=\"#log\"\u003elog(msg)\u003c/a\u003e ⇒ \u003ccode\u003evoid\u003c/code\u003e\u003c/dt\u003e\n\u003cdd\u003e\u003cp\u003eLogs a message to the console if the debug flag is set to true in the config.\u003c/p\u003e\n\u003c/dd\u003e\n\u003c/dl\u003e\n\n\u003ca name=\"SessionManager\"\u003e\u003c/a\u003e\n\n## SessionManager ⇐ \u003ccode\u003eEventEmitter\u003c/code\u003e\nSessionManager is a class that manages the sessions of the users.\n\n**Kind**: global class\n**Extends**: \u003ccode\u003eEventEmitter\u003c/code\u003e\n\n* [SessionManager](#SessionManager) ⇐ \u003ccode\u003eEventEmitter\u003c/code\u003e\n    * [.setSessionTimeOut(sessionTimeout)](#SessionManager+setSessionTimeOut) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\n    * [.getSessionTimeout()](#SessionManager+getSessionTimeout) ⇒ \u003ccode\u003enumber\u003c/code\u003e\n    * [.getLoggedUsers()](#SessionManager+getLoggedUsers) ⇒ \u003ccode\u003earray\u003c/code\u003e\n    * [.initSocketReference(ioRef)](#SessionManager+initSocketReference) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\n    * [.getSocketReference()](#SessionManager+getSocketReference) ⇒ \u003ccode\u003eSocketIO.Server\u003c/code\u003e\n    * [.loadNewSession(username)](#SessionManager+loadNewSession) ⇒ \u003ccode\u003estring\u003c/code\u003e\n    * [.setSessionData(key, data)](#SessionManager+setSessionData) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\n    * [.getSessionData(key)](#SessionManager+getSessionData) ⇒ \u003ccode\u003eobject\u003c/code\u003e\n    * [.restartSessionTimer(key)](#SessionManager+restartSessionTimer) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\n    * [.getSessionDetails(key)](#SessionManager+getSessionDetails) ⇒ \u003ccode\u003eobject\u003c/code\u003e \\| \u003ccode\u003eboolean\u003c/code\u003e\n    * [.deleteSession(key)](#SessionManager+deleteSession) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\n    * [.deleteAllSessions()](#SessionManager+deleteAllSessions) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\n    * [.sendLogoutMessage(key)](#SessionManager+sendLogoutMessage) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\n    * [.createNewSessionTimer(key, username)](#SessionManager+createNewSessionTimer) ⇒ \u003ccode\u003eNodeJS.Timeout\u003c/code\u003e\n    * [.checkSessionStatus(key)](#SessionManager+checkSessionStatus) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\n    * [.getUsernameFromSessionKey(key)](#SessionManager+getUsernameFromSessionKey) ⇒ \u003ccode\u003estring\u003c/code\u003e\n\n\u003ca name=\"SessionManager+setSessionTimeOut\"\u003e\u003c/a\u003e\n\n### sessionManager.setSessionTimeOut(sessionTimeout) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\nThis function is used to set the session timeout\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003eboolean\u003c/code\u003e - true or false: true if ok\n\n| Param | Type | Description |\n| --- | --- | --- |\n| sessionTimeout | \u003ccode\u003enumber\u003c/code\u003e | The session timeout in seconds |\n\n**Example**\n```js\nsetSessionTimeOut(3000) // Returns true or false\n```\n\u003ca name=\"SessionManager+getSessionTimeout\"\u003e\u003c/a\u003e\n\n### sessionManager.getSessionTimeout() ⇒ \u003ccode\u003enumber\u003c/code\u003e\nThis function is used to get the session timeout\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003enumber\u003c/code\u003e - The session timeout in seconds\n**Example**\n```js\ngetSessionTimeOut() // Returns 3000\n```\n\u003ca name=\"SessionManager+getLoggedUsers\"\u003e\u003c/a\u003e\n\n### sessionManager.getLoggedUsers() ⇒ \u003ccode\u003earray\u003c/code\u003e\nThis function is used to get the list of logged users\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003earray\u003c/code\u003e - The list of logged users\n**Example**\n```js\ngetLoggedUsers() // Returns ['Gino', 'Gino2']\n```\n\u003ca name=\"SessionManager+initSocketReference\"\u003e\u003c/a\u003e\n\n### sessionManager.initSocketReference(ioRef) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\nFunction to copy the Socket IO http server reference\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003eboolean\u003c/code\u003e - true or false, true if ok\n\n| Param | Type |\n| --- | --- |\n| ioRef | \u003ccode\u003e\\*\u003c/code\u003e |\n\n\u003ca name=\"SessionManager+getSocketReference\"\u003e\u003c/a\u003e\n\n### sessionManager.getSocketReference() ⇒ \u003ccode\u003eSocketIO.Server\u003c/code\u003e\nFunction to get the socket reference\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003eSocketIO.Server\u003c/code\u003e - The socket reference\n\u003ca name=\"SessionManager+loadNewSession\"\u003e\u003c/a\u003e\n\n### sessionManager.loadNewSession(username) ⇒ \u003ccode\u003estring\u003c/code\u003e\nFunction to add users sessions in this module. Use it at login\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003estring\u003c/code\u003e - user unique key\n\n| Param | Type | Description |\n| --- | --- | --- |\n| username | \u003ccode\u003estring\u003c/code\u003e | The username provided on successful login |\n\n**Example**\n```js\naddSession('Gino') // Returns 'session_key'\n```\n\u003ca name=\"SessionManager+setSessionData\"\u003e\u003c/a\u003e\n\n### sessionManager.setSessionData(key, data) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\nFunction to set the property 'data' of a session. Use it for example to store something in the session, like the user actions history, etc.\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003eboolean\u003c/code\u003e - true or false, true if ok\n**Throws**:\n\n- \u003ccode\u003eError\u003c/code\u003e If the session_key is not found\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| key | \u003ccode\u003estring\u003c/code\u003e | The session_key provided on successful login |\n| data | \u003ccode\u003eobject\u003c/code\u003e | The data to be stored in the session |\n\n**Example**\n```js\nsetSessionData('session_key', {'actions': [\"logged in\", ...]}) // Returns true or false\n```\n\u003ca name=\"SessionManager+getSessionData\"\u003e\u003c/a\u003e\n\n### sessionManager.getSessionData(key) ⇒ \u003ccode\u003eobject\u003c/code\u003e\nFunction to get the property 'data' of a session. Use it for example to get the user actions history, etc.\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003eobject\u003c/code\u003e - The data stored in the session\n**Throws**:\n\n- \u003ccode\u003eError\u003c/code\u003e If the session_key is not found\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| key | \u003ccode\u003estring\u003c/code\u003e | The session_key provided on successful login |\n\n**Example**\n```js\ngetSessionData('session_key') // Returns {'actions': [\"logged in\", ...]}\n```\n\u003ca name=\"SessionManager+restartSessionTimer\"\u003e\u003c/a\u003e\n\n### sessionManager.restartSessionTimer(key) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\nFunction that restart the session timer. Use it after an API call to keep the session alive.\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003eboolean\u003c/code\u003e - true or false, true if ok\n**Throws**:\n\n- \u003ccode\u003eError\u003c/code\u003e If the session key is not found\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| key | \u003ccode\u003estring\u003c/code\u003e | The session_key |\n\n**Example**\n```js\nrestartSessionTimer('session_key') // Returns true or false\n```\n\u003ca name=\"SessionManager+getSessionDetails\"\u003e\u003c/a\u003e\n\n### sessionManager.getSessionDetails(key) ⇒ \u003ccode\u003eobject\u003c/code\u003e \\| \u003ccode\u003eboolean\u003c/code\u003e\nFunction to get details of a session. Use it to get the username, the creation date and the data.\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003eobject\u003c/code\u003e \\| \u003ccode\u003eboolean\u003c/code\u003e - The session details or false if not found\n**Throws**:\n\n- \u003ccode\u003eError\u003c/code\u003e If the session key is not found\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| key | \u003ccode\u003estring\u003c/code\u003e | The session_key |\n\n**Example**\n```js\ngetSessionDetails('session_key') // Returns {'username': 'Gino', 'createdAt': 1523456789, 'data': {'actions': [\"logged in\", ...]}}\n```\n\u003ca name=\"SessionManager+deleteSession\"\u003e\u003c/a\u003e\n\n### sessionManager.deleteSession(key) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\nFunction to delete users sessions in this module. Use it at client logout\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)  \n**Returns**: \u003ccode\u003eboolean\u003c/code\u003e - true or false, true if ok\n**Throws**:\n\n- \u003ccode\u003eError\u003c/code\u003e If the session_key is not found\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| key | \u003ccode\u003estring\u003c/code\u003e | The session_key provided on successful login |\n\n**Example**\n```js\ndeleteSession('session_key') // Returns true or false\n```\n\u003ca name=\"SessionManager+deleteAllSessions\"\u003e\u003c/a\u003e\n\n### sessionManager.deleteAllSessions() ⇒ \u003ccode\u003eboolean\u003c/code\u003e\nFunction to delete all sessions\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003eboolean\u003c/code\u003e - true or false, true if ok\n\u003ca name=\"SessionManager+sendLogoutMessage\"\u003e\u003c/a\u003e\n\n### sessionManager.sendLogoutMessage(key) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\nUse this to notify the client to logout with WebSocket\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003eboolean\u003c/code\u003e - true or false, true if ok\n\n| Param | Type | Description |\n| --- | --- | --- |\n| key | \u003ccode\u003estring\u003c/code\u003e | The session_key |\n\n**Example**\n```js\nsendLogoutMessage('session_key') // Returns true or false\n```\n\u003ca name=\"SessionManager+createNewSessionTimer\"\u003e\u003c/a\u003e\n\n### sessionManager.createNewSessionTimer(key, username) ⇒ \u003ccode\u003eNodeJS.Timeout\u003c/code\u003e\nFunction to return a new setTimeout object and start it.\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n\n| Param | Type | Description |\n| --- | --- | --- |\n| key | \u003ccode\u003estring\u003c/code\u003e | The session_key |\n| username | \u003ccode\u003estring\u003c/code\u003e | The username, only for logging features |\n\n**Example**\n```js\ncreateNewSessionTimer('session_key', 'username') // Returns a new setTimeout object\n```\n\u003ca name=\"SessionManager+checkSessionStatus\"\u003e\u003c/a\u003e\n\n### sessionManager.checkSessionStatus(key) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\nUse this before every API.js function execution.n the stored collection\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003eboolean\u003c/code\u003e - true or false: true if session is active\n**Throws**:\n\n- \u003ccode\u003eError\u003c/code\u003e if the session is not valid\n- \u003ccode\u003eError\u003c/code\u003e if the session is expired\n\n\n| Param | Type | Description |\n| --- | --- | --- |\n| key | \u003ccode\u003estring\u003c/code\u003e | the user key generated at login |\n\n**Example**\n```js\ncheckSessionStatus('my_session_key') // true or false\n```\n\u003ca name=\"SessionManager+getUsernameFromSessionKey\"\u003e\u003c/a\u003e\n\n### sessionManager.getUsernameFromSessionKey(key) ⇒ \u003ccode\u003estring\u003c/code\u003e\nFunction to get the username from a session key\n\n**Kind**: instance method of [\u003ccode\u003eSessionManager\u003c/code\u003e](#SessionManager)\n**Returns**: \u003ccode\u003estring\u003c/code\u003e - The username or false if not found\n\n| Param | Type | Description |\n| --- | --- | --- |\n| key | \u003ccode\u003estring\u003c/code\u003e | The session key |\n\n**Example**\n```js\ngetUsernameFromSessionKey('123456789_123456789') // 'username'\n```\n\u003ca name=\"sessions\"\u003e\u003c/a\u003e\n\n## sessions : \u003ccode\u003eObject\u003c/code\u003e\nThe sessions of the users.\n\n**Kind**: global constant\n\u003ca name=\"MIN_SESSION_TIMEOUT\"\u003e\u003c/a\u003e\n\n## MIN\\_SESSION\\_TIMEOUT : \u003ccode\u003enumber\u003c/code\u003e\nThe minimum session timeout.\n\n**Kind**: global constant\n\u003ca name=\"settings\"\u003e\u003c/a\u003e\n\n## settings : \u003ccode\u003eObject\u003c/code\u003e\nThe settings of the session manager.\n\n**Kind**: global constant\n\u003ca name=\"log\"\u003e\u003c/a\u003e\n\n## log(msg) ⇒ \u003ccode\u003evoid\u003c/code\u003e\nLogs a message to the console if the debug flag is set to true in the config.\n\n**Kind**: global function\n\n| Param | Type |\n| --- | --- |\n| msg | \u003ccode\u003estring\u003c/code\u003e |\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felius94%2Fusers-session-manager","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Felius94%2Fusers-session-manager","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felius94%2Fusers-session-manager/lists"}