-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
111 lines (94 loc) · 2.62 KB
/
server.js
File metadata and controls
111 lines (94 loc) · 2.62 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// note: this is a base code, this could be far improved
import express from "express";
import crypto from "crypto";
// import fs from "fs"
const app = express();
app.use(express.json());
const allowedUsers = [{
id: '123',
name: 'TestUser'
},
{
id: '456',
name: 'AnotherUser'
}
// you can load a json file for this (db would be far better but this is just a base for u guys to improve on)
// const allowedUsers = JSON.parse(fs.readFileSync('./users.json', 'utf8'));
];
const activeTokens = new Map();
// generate a token tied to user + fingerprint
function CreateToken(userId, fingerprint) {
const token = crypto.randomBytes(32).toString('hex');
activeTokens.set(token, {
userId,
fingerprint,
expires: Date.now() + 60 * 60 * 1000 // this should be self-explanatory but edit it to be like 3-7 days, not 1 hour
});
return token;
}
function IsUserAllowed(userId) {
return allowedUsers.some(u => u.id === String(userId));
}
app.post('/auth', (req, res) => {
const {
userId,
fingerprint
} = req.body;
if (!userId || !fingerprint || typeof fingerprint !== 'string') {
return res.status(400).json({
ok: false,
error: 'missing or invalid data'
});
}
if (!IsUserAllowed(userId)) {
return res.status(403).json({
ok: false,
error: 'user not allowed'
});
}
const token = CreateToken(userId, fingerprint);
res.json({
ok: true,
token
});
});
app.post('/validate', (req, res) => {
const {
token,
fingerprint
} = req.body;
if (!token || !fingerprint) {
return res.json({
ok: false
});
}
const data = activeTokens.get(token);
if (!data) return res.json({
ok: false
});
if (data.expires < Date.now()) {
activeTokens.delete(token);
return res.json({
ok: false
});
}
if (data.fingerprint !== fingerprint) {
return res.json({
ok: false
});
}
res.json({
ok: true
});
});
// this is optional but its a small housekeeping to clear expired tokens
setInterval(() => {
const now = Date.now();
for (const [token, data] of activeTokens.entries()) {
if (data.expires < now) activeTokens.delete(token);
}
}, 5 * 60 * 1000);
const portending = 8080;
app.listen(portending, () => {
console.log('auth server running on port: ', portending);
});