Skip to content

Commit 77b189c

Browse files
committed
Feat: Added additional data to sessions\nAnd completed coverage of test units.
1 parent 41a9750 commit 77b189c

File tree

3 files changed

+321
-5
lines changed

3 files changed

+321
-5
lines changed

README.md

Lines changed: 157 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,77 @@ setInterval(() => {
4040
}, 5000)
4141
```
4242

43+
## Example of Frontend and Backend session exchange
44+
```js
45+
46+
// Frontend
47+
let session_key = "";
48+
49+
/**
50+
* Function to call try_login API
51+
*
52+
* @param {*} user username text
53+
* @param {*} pwd password text
54+
* @return {*} false if wrong login or the user table ROW of the selected user JSON format
55+
*/
56+
async function TryLogin(user, pwd) {
57+
//console.log(ENDPOINT)
58+
let credentials = {
59+
"username": user,
60+
"password": md5(pwd)
61+
}
62+
const rawResponse = await fetch(ENDPOINT + API_ROUTE, {
63+
method: 'POST',
64+
headers: {
65+
'Accept': 'application/json',
66+
'Content-Type': 'application/json',
67+
'api_name': 'try_login'
68+
},
69+
body: JSON.stringify(credentials)
70+
})
71+
const user_data = await rawResponse.json()
72+
if (user_data.length > 0)
73+
session_key = user_data[0].session_key // save session key to the global variable.
74+
75+
//console.log("user_data: ", user_data)
76+
return user_data
77+
}
78+
79+
// Backend
80+
81+
// API.js route (cutted from the original file)
82+
...
83+
case 'try_login':
84+
response = {
85+
accepted: false,
86+
message: '',
87+
user_data: {}
88+
}
89+
if (typeof(req.body) === 'object') {
90+
try {
91+
const body = req.body
92+
const db_response = await db.tryLogin(body.username, body.password, true) // true to get the session key
93+
if (db_response !== false) {
94+
response.accepted = true
95+
response.message = 'Welcome! 😘'
96+
response.user_data = db_response
97+
response.user_data.session_key = loadNewSession(body.username) // generate a new session key
98+
} else {
99+
response.accepted = false
100+
response.message = 'Wrong username or password... Are you a f**ing HACKER? 💩💩💩'
101+
}
102+
} catch (error) {
103+
response.accepted = false
104+
response.message = 'Error in API call!'
105+
response.user_data = null
106+
} finally {
107+
res.send(JSON.stringify(response))
108+
}
109+
}
110+
break
111+
...
112+
```
113+
43114
## Integrate with Socket.io server to notify clients
44115

45116
```js
@@ -171,6 +242,10 @@ SessionManager is a class that manages the sessions of the users.
171242
* [.initSocketReference(ioRef)](#SessionManager+initSocketReference) ⇒ <code>boolean</code>
172243
* [.getSocketReference()](#SessionManager+getSocketReference) ⇒ <code>SocketIO.Server</code>
173244
* [.loadNewSession(username)](#SessionManager+loadNewSession) ⇒ <code>string</code>
245+
* [.setSessionData(key, data)](#SessionManager+setSessionData) ⇒ <code>boolean</code>
246+
* [.getSessionData(key)](#SessionManager+getSessionData) ⇒ <code>object</code>
247+
* [.restartSessionTimer(key)](#SessionManager+restartSessionTimer) ⇒ <code>boolean</code>
248+
* [.getSessionDetails(key)](#SessionManager+getSessionDetails) ⇒ <code>object</code> \| <code>boolean</code>
174249
* [.deleteSession(key)](#SessionManager+deleteSession) ⇒ <code>boolean</code>
175250
* [.deleteAllSessions()](#SessionManager+deleteAllSessions) ⇒ <code>boolean</code>
176251
* [.sendLogoutMessage(key)](#SessionManager+sendLogoutMessage) ⇒ <code>boolean</code>
@@ -251,12 +326,93 @@ Function to add users sessions in this module. Use it at login
251326
```js
252327
addSession('Gino') // Returns 'session_key'
253328
```
329+
<a name="SessionManager+setSessionData"></a>
330+
331+
### sessionManager.setSessionData(key, data) ⇒ <code>boolean</code>
332+
Function to set the property 'data' of a session. Use it for example to store something in the session, like the user actions history, etc.
333+
334+
**Kind**: instance method of [<code>SessionManager</code>](#SessionManager)
335+
**Returns**: <code>boolean</code> - true or false, true if ok
336+
**Throws**:
337+
338+
- <code>Error</code> If the session_key is not found
339+
340+
341+
| Param | Type | Description |
342+
| --- | --- | --- |
343+
| key | <code>string</code> | The session_key provided on successful login |
344+
| data | <code>object</code> | The data to be stored in the session |
345+
346+
**Example**
347+
```js
348+
setSessionData('session_key', {'actions': ["logged in", ...]}) // Returns true or false
349+
```
350+
<a name="SessionManager+getSessionData"></a>
351+
352+
### sessionManager.getSessionData(key) ⇒ <code>object</code>
353+
Function to get the property 'data' of a session. Use it for example to get the user actions history, etc.
354+
355+
**Kind**: instance method of [<code>SessionManager</code>](#SessionManager)
356+
**Returns**: <code>object</code> - The data stored in the session
357+
**Throws**:
358+
359+
- <code>Error</code> If the session_key is not found
360+
361+
362+
| Param | Type | Description |
363+
| --- | --- | --- |
364+
| key | <code>string</code> | The session_key provided on successful login |
365+
366+
**Example**
367+
```js
368+
getSessionData('session_key') // Returns {'actions': ["logged in", ...]}
369+
```
370+
<a name="SessionManager+restartSessionTimer"></a>
371+
372+
### sessionManager.restartSessionTimer(key) ⇒ <code>boolean</code>
373+
Function that restart the session timer. Use it after an API call to keep the session alive.
374+
375+
**Kind**: instance method of [<code>SessionManager</code>](#SessionManager)
376+
**Returns**: <code>boolean</code> - true or false, true if ok
377+
**Throws**:
378+
379+
- <code>Error</code> If the session key is not found
380+
381+
382+
| Param | Type | Description |
383+
| --- | --- | --- |
384+
| key | <code>string</code> | The session_key |
385+
386+
**Example**
387+
```js
388+
restartSessionTimer('session_key') // Returns true or false
389+
```
390+
<a name="SessionManager+getSessionDetails"></a>
391+
392+
### sessionManager.getSessionDetails(key) ⇒ <code>object</code> \| <code>boolean</code>
393+
Function to get details of a session. Use it to get the username, the creation date and the data.
394+
395+
**Kind**: instance method of [<code>SessionManager</code>](#SessionManager)
396+
**Returns**: <code>object</code> \| <code>boolean</code> - The session details or false if not found
397+
**Throws**:
398+
399+
- <code>Error</code> If the session key is not found
400+
401+
402+
| Param | Type | Description |
403+
| --- | --- | --- |
404+
| key | <code>string</code> | The session_key |
405+
406+
**Example**
407+
```js
408+
getSessionDetails('session_key') // Returns {'username': 'Gino', 'createdAt': 1523456789, 'data': {'actions': ["logged in", ...]}}
409+
```
254410
<a name="SessionManager+deleteSession"></a>
255411

256412
### sessionManager.deleteSession(key) ⇒ <code>boolean</code>
257413
Function to delete users sessions in this module. Use it at client logout
258414

259-
**Kind**: instance method of [<code>SessionManager</code>](#SessionManager)
415+
**Kind**: instance method of [<code>SessionManager</code>](#SessionManager)
260416
**Returns**: <code>boolean</code> - true or false, true if ok
261417
**Throws**:
262418

index.js

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,13 +116,92 @@ export class SessionManager extends EventEmitter {
116116
this.sessions[newSessionKey] = {
117117
username,
118118
key: newSessionKey,
119+
createdAt: Date.now(),
119120
timer: this.createNewSessionTimer(newSessionKey, username)
120121
}
121122
this.emit('sessionCreated', newSessionKey)
122123
//log("[Session Manager]: Active sessions:", sessions)
123124
return newSessionKey
124125
}
125126

127+
/**
128+
* Function to set the property 'data' of a session. Use it for example to store something in the session, like the user actions history, etc.
129+
*
130+
* @param {string} key The session_key provided on successful login
131+
* @param {object} data The data to be stored in the session
132+
* @return {boolean} true or false, true if ok
133+
* @throws {Error} If the session_key is not found
134+
*
135+
* @example setSessionData('session_key', {'actions': ["logged in", ...]}) // Returns true or false
136+
*
137+
*/
138+
setSessionData(key, data) {
139+
if (this.checkSessionStatus(key)) {
140+
if (this.sessions[key]) {
141+
this.sessions[key].data = data // Set the data
142+
return true
143+
}
144+
}
145+
return false
146+
}
147+
148+
/**
149+
* Function to get the property 'data' of a session. Use it for example to get the user actions history, etc.
150+
*
151+
* @param {string} key The session_key provided on successful login
152+
* @return {object} The data stored in the session
153+
* @throws {Error} If the session_key is not found
154+
*
155+
* @example getSessionData('session_key') // Returns {'actions': ["logged in", ...]}
156+
*/
157+
getSessionData(key) {
158+
if (this.checkSessionStatus(key)) {
159+
if (this.sessions[key]) {
160+
return this.sessions[key].data
161+
}
162+
}
163+
return false
164+
}
165+
166+
/** Function that restart the session timer. Use it after an API call to keep the session alive.
167+
*
168+
* @param {string} key The session_key
169+
* @return {boolean} true or false, true if ok
170+
* @throws {Error} If the session key is not found
171+
*
172+
* @example restartSessionTimer('session_key') // Returns true or false
173+
*/
174+
restartSessionTimer(key) {
175+
if (this.checkSessionStatus(key)) {
176+
clearTimeout(this.sessions[key].timer)
177+
this.sessions[key].timer = this.createNewSessionTimer(key, this.sessions[key].username)
178+
return true
179+
}
180+
return false
181+
}
182+
183+
/**
184+
* Function to get details of a session. Use it to get the username, the creation date and the data.
185+
*
186+
* @param {string} key The session_key
187+
* @return {object|boolean} The session details or false if not found
188+
* @throws {Error} If the session key is not found
189+
*
190+
* @example getSessionDetails('session_key') // Returns {'username': 'Gino', 'createdAt': 1523456789, 'data': {'actions': ["logged in", ...]}}
191+
*/
192+
getSessionDetails(key) {
193+
if (this.checkSessionStatus(key)) {
194+
if (this.sessions[key]) {
195+
return {
196+
username: this.sessions[key].username,
197+
createdAt: this.sessions[key].createdAt,
198+
data: this.sessions[key].data ? this.sessions[key].data : undefined
199+
}
200+
}
201+
}
202+
return false
203+
}
204+
126205
/**
127206
* Function to delete users sessions in this module. Use it at client logout
128207
* @param {string} key The session_key provided on successful login

0 commit comments

Comments
 (0)