-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
108 lines (92 loc) · 2.51 KB
/
index.ts
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
import express, { request } from 'express';
import cors from 'cors'
import { createServer } from "http";
import { Server } from "socket.io";
import { RateLimiterMemory } from 'rate-limiter-flexible';
import jwt, { TokenExpiredError } from 'jsonwebtoken'
const app: express.Application = express();
const httpServer = createServer(app);
const port: number = 5000;
// const corsOptions = {
// exposedHeaders: 'WWW-Authenticate',
// origin: "http://localhost:3000",
// credentials: true,
// };
// app.use(cors(corsOptions))
interface ServerToClientEvents {
noArg: () => void;
basicEmit: (a: number, b: string, c: Buffer) => void;
withAck: (d: string, callback: (e: number) => void) => void;
serverMessage: ({}: ServerMessage) => void
}
interface ClientToServerEvents {
hello: () => void;
}
interface InterServerEvents {
ping: () => void;
}
interface User {
id: string;
publicKey: string
createdAt: Date
updatedAt: Date
userName: 'string'
iat: number;
}
interface SocketData {
userName: string,
badge: string
}
interface ServerMessage {
type: string
userName: string,
message: string,
badge: string
}
const io = new Server<
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData
>(httpServer, {
cors: {
origin: "https://satsgg.up.railway.app/",
credentials: true
}
});
const chat = io.of("/chat");
chat.use(async (socket, next) => {
const token = socket.handshake.auth.token ?? undefined
const nym: any | undefined = socket.handshake.query.nym ?? undefined
if (token && jwt.verify(token, process.env.JWT_TOKEN ?? '')) {
const user: User = token ? jwt.verify(token, process.env.JWT_TOKEN ?? '') : token
socket.data.userName = user.userName
socket.data.badge = 'lnauth'
} else if (nym) {
socket.data.userName = nym
socket.data.badge = 'nym'
} else {
console.log('ERROR NOT USER OR NYM')
}
next()
});
chat.on("connection", (socket: any) => {
socket.join(socket.handshake.query.room);
socket.emit('serverMessage', {
type: 'serverMessage',
userName: undefined,
message: 'Welcome to the chat!',
badge: undefined
})
socket.on('clientMessage', (clientMessage: string) => {
return chat.to(socket.handshake.query.room).emit('serverMessage', {
type: 'userMessage',
userName: socket.data.userName,
message: clientMessage,
badge: socket.data.badge
});
})
})
httpServer.listen(port, () => {
console.log(`TypeScript with Express http://localhost:${port}/`);
})