-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
301 lines (287 loc) · 8.92 KB
/
Copy pathserver.js
File metadata and controls
301 lines (287 loc) · 8.92 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import {createServer} from 'http';
import {Server} from "socket.io";
import fs from "fs/promises";
import pg from "pg";
import env from "dotenv";
import bcrypt from "bcrypt";
class Node {
constructor(key) {
this.key = key;
this.prev = null;
this.next = null;
}
}
class List {
constructor() {
this.head = null;
this.tail = null;
}
addNode(node) {
if (!this.head) {
this.head = node;
this.tail = node;
return;
}
node.next = this.head;
node.prev = null;
this.head.prev = node;
this.head = node;
}
remove(node) {
if (node === this.head && node === this.tail) {
this.head = null;
this.tail = null;
return;
}
if (node === this.head) {
this.head = node.next;
this.head.prev = null;
node.next = null;
return;
}
if (node === this.tail) {
this.tail = node.prev;
this.tail.next = null;
node.prev = null;
return;
}
node.prev.next = node.next;
node.next.prev = node.prev;
node.prev = null;
node.next = null;
}
makeHead(node) {
if (node === this.head) return;
this.remove(node);
this.addNode(node);
}
removeTail() {
if (!this.tail) return null;
const victim = this.tail;
this.remove(victim);
return victim;
}
}
env.config();
const db=new pg.Pool({
user:"postgres",
host:"localhost",
port:5432,
database:"Cachey",
password:process.env.DATABASE_PASSWORD,
});
//CURL for signup because I don't want to serve HTML that's a different deal
const app = createServer(async (req, res) => {
if (req.method === "POST" && req.url === "/signup") {
let body = "";
req.on("data", chunk => {
body += chunk.toString();
});
req.on("end", async () => {
try {
const data = JSON.parse(body);
const hash = await bcrypt.hash(data.password, 10);
const result1=await db.query("INSERT INTO users (username,password) VALUES ($1,$2) RETURNING user_id",[data.username,hash]);
const user_id=result1.rows[0].user_id;
const result2=await db.query("INSERT INTO rooms (room_name) VALUES ($1) RETURNING room_id",[data.username]);
const room_id=result2.rows[0].room_id;
await db.query("INSERT INTO membership VALUES ($1,$2)",[room_id,user_id]);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
} catch (e) {
console.error("SIGNUP ERROR:", e);
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: e.message }));
}
});
return;
}
res.writeHead(404);
res.end("Not found");
});
const port=3000;
const io=new Server(app);
var cache=new Map();
var lru=new List();
const maxSize=10000; //LRU max size
async function saveSnapshot() {
const snapshot = {};
for (const [key, entry] of cache) {
snapshot[key] = {
value: entry.value,
expiresAt: entry.expiresAt
};
}
await fs.writeFile(
"cache.json",
JSON.stringify(snapshot)
);
}
async function loadSnapshot() {
try {
const data = JSON.parse(
await fs.readFile("cache.json","utf8")
);
cache = new Map();
for (const [key, value] of Object.entries(data)) {
const node = new Node(key);
cache.set(key,{
value: value.value,
expiresAt: value.expiresAt,
node: node
});
lru.addNode(node);
}
} catch {}
}
process.on("SIGINT", async () => {
await saveSnapshot();
process.exit(0);
});
setInterval(saveSnapshot,600000); //every 10 minutes
setInterval(() => {
for (const [key, entry] of cache) {
if (entry.expiresAt && Date.now() > entry.expiresAt) {
lru.remove(entry.node);
cache.delete(key);
}
}
}, 300000); //every 5 minutes
async function verify(socket,username,key){
const result=await db.query("SELECT u.user_id,u.username,u.password,r.room_id,r.room_name FROM users u LEFT JOIN membership m ON m.user_id=u.user_id LEFT JOIN rooms r on r.room_id=m.room_id WHERE u.username=$1",[username]);
if (result.rows.length===0) return false;
const status=await bcrypt.compare(key,result.rows[0].password);
if (status){
const user={
username:result.rows[0].username,
userId:result.rows[0].user_id,
rooms:result.rows.filter(r=>r.room_id!==null).map(r=>({
roomId:r.room_id,
roomName:r.room_name,
}))
}
socket.data.user=user;
return true;
}else{
return false;
}
}
io.use(async (socket,next)=>{
const key=socket.handshake.auth?.key;
const username=socket.handshake.auth?.username;
if (!username) {
return next(new Error("Username required"));
}
else if (!key) {
return next(new Error("Key required"));
}
else{
const status=await verify(socket,username,key);
if (!status) return next(new Error("Wrong Password or Username"));
else next();
}
})
io.on('connection',async (socket)=>{
socket.on("join",(data)=>{
const allowed = socket.data.user.rooms.some(
r => r.roomName === data.roomName
);
if (!allowed) {
socket.emit("error",{error:"Unauthorized or wrong room name at join"});
return;
}
else{
socket.join(data.roomName);
io.to(data.roomName).emit("userJoined",`${socket.id} has joined ${data.roomName}`);
}
})
socket.on("set",(data)=>{
const allowed = socket.data.user.rooms.some(
r => r.roomName === data.roomName
);
if (!allowed) {
socket.emit("error",{error:"Unauthorized or wrong room name at set"});
return;
}
else{
if (!data.key) {
socket.emit("error",{error:"Key needed"});
return;
}
if (!data.value) {
socket.emit("error",{error:"Value needed"});
return;
}
const cacheKey=`${data.roomName}:${data.key}`;
if (cache.has(cacheKey)){
const result=cache.get(cacheKey);
lru.makeHead(result.node);
const node=lru.head;
cache.set(cacheKey,{
expiresAt:data.ttl?Date.now()+data.ttl*1000:null,
value:data.value,
node:node,
})
}else{
const node=new Node(cacheKey);
cache.set(cacheKey,{
value:data.value,
expiresAt:data.ttl?Date.now()+data.ttl*1000:null,
node:node,
});
lru.addNode(node);
if (cache.size>maxSize){
const key=lru.tail.key;
lru.removeTail();
cache.delete(key);
}
}
socket.emit("success",{message:"Value added successfully"});
}
})
socket.on("get",(data)=>{
const allowed = socket.data.user.rooms.some(
r => r.roomName === data.roomName
);
if (!allowed) {
socket.emit("error",{error:"Unauthorized or wrong room name"});
return;
}
else{
if (!data.key) {socket.emit("error",{error:"Key needed"});return;}
if (cache.has(`${data.roomName}:${data.key}`)){
const result=cache.get(`${data.roomName}:${data.key}`);
const node=result.node;
lru.makeHead(node);
socket.emit("getResult",{expiresAt:result.expiresAt,value:result.value});
}else{
socket.emit("error",{error:"Not found"});
}
}
})
socket.on("delete",(data)=>{
const allowed = socket.data.user.rooms.some(
r => r.roomName === data.roomName
);
if (!allowed) {
socket.emit("error",{error:"Unauthorized or wrong room name"});
return;
}
else{
if (!data.key) {socket.emit("error",{error:"Key needed"});return;}
if (cache.has(`${data.roomName}:${data.key}`)){
const result=cache.get(`${data.roomName}:${data.key}`);
const node=result.node;
lru.remove(node);
cache.delete(`${data.roomName}:${data.key}`);
socket.emit("success",{message:"Deleted Successfully"});
}else{
socket.emit("error",{error:"Not found"})
}
}
})
})
loadSnapshot();
app.listen(port,()=>{
console.log(`Server running on port ${port}`);
})