-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
328 lines (253 loc) · 9.92 KB
/
Copy pathapp.js
File metadata and controls
328 lines (253 loc) · 9.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const http = require('http');
const { Server } = require("socket.io");
var config = require('./config.js');
var passport = require('passport');
const OAuth2Strategy = require('passport-oauth2');
var session = require('express-session');
//const fetch = require('node-fetch');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
var db = require('./lib/database');
var user = require('./lib/user');
var room = require('./lib/room');
var indexRouter = require('./routes/index');
var errorRouter = require('./routes/error');
const { on } = require('cluster');
var app = express();
const server = http.createServer(app);
const io = new Server(server);
// tentative de pouvoir utiliser la session dans le socket
const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);
const sessionMiddleware = session({
secret: config.web.sessionSecret,
resave: true,
saveUninitialized: true,
cookie: {
path: '/',
httpOnly: true,
secure: false,
SameSite: 'None',
maxAge: 86400,
}
});
app.use(sessionMiddleware);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new OAuth2Strategy({
authorizationURL: config.oauth2.authendpoint,
tokenURL: config.oauth2.tokenurl,
clientID: config.oauth2.clientid,
clientSecret: config.oauth2.clientsecret,
callbackURL: config.oauth2.callback,
scope: 'profile openid',
state: true
},
async function (accessToken, refreshToken, profile, cb) {
const accessSplit = accessToken.split('.');
const accessObject = JSON.parse(Buffer.from(accessSplit[1], 'base64').toString('utf-8'));
const headers = {
'cache-control': 'no-cache',
'content-type': 'application/x-www-form-urlencoded',
'accept': '*',
'accept-encoding': 'gzip, deflate',
'authorization': "bearer " + accessToken,
'scope': 'profile openid'
};
const userProfilePromise = await fetch(config.oauth2.profileurl, { method: 'GET', headers: headers });
const userProfile = await userProfilePromise.json();
let userMZChat = {
id: userProfile.sub,
nom: userProfile.nom,
key: accessObject.id,
}
let userItem;
let currentUserExists = await user.exists(userMZChat);
if (!currentUserExists) {
const currentUser = await user.create(userMZChat);
const newRoom = await room.create(currentUser.nom);
await room.addUser(newRoom, currentUser);
await user.setCurrentRoom(currentUser, newRoom);
}
let currentUser = await user.getInfos(userMZChat);
currentUser.roomInfos = await room.getInfos(currentUser.currentroomid);
session.userMZChat = currentUser;
return cb(null, userMZChat);
}
));
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
app.use('/', indexRouter);
app.use('/error', errorRouter);
app.get('/auth/mh/',
passport.authenticate('oauth2', { scope: 'profile openid' })
);
app.get('/auth/mh/callback',
passport.authenticate('oauth2', { failureRedirect: '/error' }),
function (req, res) {
// Successful authentication, redirect home.
res.redirect('/');
});
let roomList;
io.use(wrap(session({
secret: config.web.sessionSecret,
resave: true,
saveUninitialized: true
})));
function onlyForHandshake(middleware) {
return (req, res, next) => {
const isHandshake = req._query.sid === undefined;
if (isHandshake) {
middleware(req, res, next);
} else {
next();
}
};
}
io.engine.use(onlyForHandshake(sessionMiddleware));
io.engine.use(onlyForHandshake(passport.session()));
io.engine.use(
onlyForHandshake((req, res, next) => {
if (req.user) {
next();
} else {
res.writeHead(401);
res.end();
}
}),
);
io.on('connection', async (socket) => {
// première connexion
console.log('user connected');
const session = passport.session;
const sessionUser = socket.request.user;
const currentUser = await user.getInfos(sessionUser);
let roomList = await user.getRooms(currentUser);
console.log(roomList);
roomList.forEach((room) => {
const roomId = room.id;
socket.join(roomId);
});
//TODO
/**
* - rajouter un socket.join(roomId pour chaque room de la liste ?);
* - remplacer tous les emit par un to(roomId).emit;
*/
if (currentUser.currentroomid === null || currentUser.currentroomid === undefined) {
currentUser.currentroomid = roomList[0].id;
}
let currentRoom = await room.getInfos(currentUser.currentroomid);
currentUser.roomInfos = currentRoom;
let messageList = await room.getLastMessages(currentRoom, 25);
io.to(currentRoom.id).emit('refresh room', messageList, currentUser, roomList, currentRoom);
socket.on('add room user', async (roomId, addUsersList) => {
let newRoom = await room.getInfos(roomId);
if (await room.isUserAllowed(newRoom, currentUser)) {
var usersListArray = addUsersList.match(/-?\d+/g);
usersListArray.forEach(async (userId) => {
addedUser = await user.getInfosFromId(userId);
if (addedUser !== null && addedUser !== undefined) {
await room.addUser(newRoom, addedUser);
}
});
}
let messageList = await room.getLastMessages(newRoom, 25);
let roomList = await user.getRooms(currentUser);
io.to(currentRoom.id).emit('refresh room', messageList, currentUser, roomList, newRoom);
});
socket.on('chat message', async (msg) => {
let newRoom = await room.getInfos(msg.roomId);
if (await room.isUserAllowed(newRoom, currentUser)) {
await room.addMessage(currentUser, newRoom, msg.message);
}
let messageList = await room.getLastMessages(newRoom, 25);
let roomList = await user.getRooms(currentUser);
io.to(currentRoom.id).emit('refresh room', messageList, currentUser, roomList, newRoom);
});
socket.on('change room', async (roomId) => {
let newRoom = await room.getInfos(roomId);
if (await room.isUserAllowed(newRoom, currentUser)) {
await user.setCurrentRoom(currentUser, newRoom);
currentUser.currentroomid = roomId;
currentUser.roomInfos = await room.getInfos(currentUser.currentroomid);
}
let messageList = await room.getLastMessages(newRoom, 25);
let roomList = await user.getRooms(currentUser);
io.to(currentRoom.id).emit('refresh room', messageList, currentUser, roomList, newRoom);
});
socket.on('add room', async (infoMessage) => {
const newRoom = await room.create(infoMessage.roomName);
let usersListArray = infoMessage.usersList.match(/-?\d+/g);
if (usersListArray !== null || usersListArray !== undefined) {
usersListArray = new Array();
}
if (usersListArray.indexOf(currentUser.id) < 0) {
usersListArray.push(currentUser.id);
}
usersListArray.forEach(async (userId) => {
const addedUser = await user.getInfosFromId(userId);
if (addedUser !== null && addedUser !== undefined) {
await room.addUser(newRoom, addedUser);
}
});
await user.setCurrentRoom(currentUser, newRoom);
currentUser.currentroomid = newRoom.id;
currentUser.roomInfos = await room.getInfos(newRoom.id);
let roomList = await user.getRooms(currentUser);
let messageList = await room.getLastMessages(newRoom.id, 25);
io.to(currentRoom.id).emit('refresh room', messageList, currentUser, roomList, newRoom);
});
socket.on('leave room', async (roomInfos) => {
const thisRoom = await room.getInfos(roomInfos.roomId);
let newRoom;
if (await room.isUserAllowed(thisRoom,currentUser )) {
await room.removeUser(thisRoom, currentUser);
const roomList = await user.getRooms(currentUser);
currentUser.currentroomid = roomList[0].id;
newRoom = roomList[0];
await user.setCurrentRoom(currentUser, newRoom);
}
currentUser.roomInfos = await room.getInfos(currentUser.currentroomid);
let roomList = await user.getRooms(currentUser);
let messageList = await room.getLastMessages(newRoom, 25);
io.to(currentRoom.id).emit('refresh room', messageList, currentUser, roomList, newRoom);
});
socket.on('update session', async (key, value) => {
currentUser[key] = value;
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
server.listen(config.web.port, () => {
console.log('server running at ' + config.web.host + ':' + config.web.port);
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;