-
Notifications
You must be signed in to change notification settings - Fork 0
/
ticketSystem.js
95 lines (79 loc) · 2.4 KB
/
ticketSystem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
63
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
const jwt = require('jsonwebtoken');
var keygen = require("keygenerator");
const fs = require('fs');
const StormDB = require("stormdb");
const dbfile = __dirname + '/token.stormdb';
const engine = new StormDB.localFileEngine(dbfile, {
async: true
});
const {secret} = JSON.parse(fs.readFileSync('secret.json', 'utf-8'));
const db = new StormDB(engine);
db.default({ list: [] });
//allows api access over socket network
//generate a token to send over sockets which can be exchanged for an access token
//token and access token are stored in a json database
//token is signed in a jwt token before sending, verifying it came from this server
async function generateToken(access_token) {
let duplicate = checkDuplicate(access_token);
if(duplicate.access_token == access_token){
const token = await jwt.sign(duplicate.sister_token, secret);
return token;
}else {
let sister_token = keygen.session_id();
let data = (sister, access) => `{ "sister_token": "${sister}", "access_token": "${access_token}"}`;
let jsondata = JSON.parse(data(sister_token, access_token));
db.get('list').push(jsondata);
db.save();
const token = await jwt.sign(sister_token, secret);
return token;
}
}
function checkDuplicate(access_token){
let res = {access_token: null, sister_token: null};
const list = db.get('list').value()
list.filter(i => {
if(i.access_token == access_token) {
if(readToken(i.sister_token) == access_token){
res.access_token = i.access_token;
res.sister_token = i.sister_token;
}
}
});
return res;
}
//read jwt token inbound from cookie over socket
function read(key, callback) {
jwt.verify(key, secret, (err, token) => {
const list = db.get('list').value()
let res = null;
list.filter(i => {
if(i.sister_token == token) {
res = i.access_token;
}else{
res = null;
}
});
callback(res);
});
}
//reads raw token instead of translating jwt
function readToken(token) {
let res = null;
const list = db.get('list').value()
list.filter(i => {
if(i.sister_token == token) {
res = i.access_token
}
});
return res;
}
//remove token after user disconnects
function remove(key) {
if(key){
const token = jwt.verify(key, secret, (err, token) => {
db.get('list').filter(i => i.sister_token != token);
db.save();
});
}
}
module.exports = {read, remove, generateToken}