-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
91 lines (73 loc) · 2.48 KB
/
app.js
File metadata and controls
91 lines (73 loc) · 2.48 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
import express from 'express';
import cookieParser from 'cookie-parser';
import fileUpload from 'express-fileupload';
import taskRouter from './routes/task';
import authRouter from './routes/userAuth';
import quillRouter from './routes/quillTest';
import { router } from './routes/index';
import {getHashedCookie} from "./utility/hash";
import chatRouter from './routes/chatRouter';
import { createServer } from "http";
import { Server } from "socket.io";
import MessageService from './service/MessageService';
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer);
// Set the view engine to ejs
app.set('view engine', 'ejs');
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));
app.use(cookieParser());
app.use(fileUpload());
// serve static files
app.use(express.static('uploads'));
app.use(express.static('public'));
const salt = process.env.SECRET_KEY;
app.use((request, _response, next) => {
// set the default value
request.isUserLoggedIn = false;
// check to see if the cookies you need exists
if (request.cookies.loggedInHash && request.cookies.userID) {
// get the hased value that should be inside the cookie
const hash = getHashedCookie(request.cookies.userID, salt);
// test the value of the cookie
if (request.cookies.loggedInHash === hash) {
request.isUserLoggedIn = true;
}
}
next();
});
app.use('/', router);
app.use('/auth', authRouter);
app.use('/task', taskRouter);
app.use('/quill', quillRouter);
app.use('/chat',chatRouter);
const messageService = new MessageService();
// server-side
io.on('connection', (socket) => {
console.log('a user is connected');
console.log("socket id: ", socket.id);
// joining chatrooms
let chatroom = "default";
socket.on("subscribe", async () => {
let chatHistory = await messageService.getMessage();
socket.join(chatroom);
console.log("a user has joined our room: " + chatroom);
io.to(chatroom).emit("joinRoom", chatHistory);
});
socket.on('chat message', async (data) => {
const message = data[0];
const sender_id = data[2];
await messageService.createMessage(sender_id,message);
io.to(chatroom).emit('chat message', data);
});
socket.on('disconnect', () => {
socket.leave(chatroom);
socket.disconnect();
console.log(`user ${socket.id} has left room ${chatroom}`);
io.to(chatroom).emit("leaveRoom", chatroom);
});
});
httpServer.listen(3004,() => {
console.log('listening on *:3004');
});