-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
351 lines (320 loc) · 10.6 KB
/
server.js
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const session = require("express-session");
const cors = require("cors");
const errorHandler = require("errorhandler");
const FacebookStrategy = require("passport-facebook").Strategy;
const GoogleStrategy = require("passport-google-oauth").OAuth2Strategy;
const facebook = require("./routers/facebook");
const google = require("./routers/google");
const passport = require("passport");
const schedule = require('node-schedule');
const RateLimit = require('express-rate-limit');
const multer = require('multer');
const PATH = './uploads';
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, PATH);
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + '.png')
}
});
const fileFilter = (req, file, cb) => {
if (file.mimetype === "image/jpg" ||
file.mimetype === "image/jpeg" ||
file.mimetype === "image/png") {
cb(null, true);
} else {
cb(new Error("Image uploaded is not of type jpg/jpeg or png"), false);
}
};
const upload = multer({ storage: storage, fileFilter: fileFilter });
require("./models/User");
require("./models/Token");
require("./db/db");
require("./config/passport");
require("./models/comment");
require("./config/facebookconfig");
require("./config/googleconfig");
require("./models/message");
require("./models/booking");
require("./models/summary");
require("./models/hotel");
require("./models/facilities");
require("./models/room_detail");
require("./models/chat_message");
const cron = require('node-schedule');
const Tokens = require("./models/Token");
global.__root = __dirname + '/';
//Configure isProduction variable
//Initiate our server
const app = express();
const isProduction = process.env.NODE_ENV === "production";
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
// enabling CORS for all requests
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
// Request methods you wish to allow
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
// Request headers you wish to allow
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type",
"Content-Type"
);
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);
// Pass to next layer of middleware
next();
});
app.use(require("morgan")("dev"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "public")));
app.use("/facebook", facebook);
app.use("/google", google);
app.use("upload", function (request, response, next) {
next();
});
//CORS Middleware
app.use(function (req, res, next) {
//Enabling CORS
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, x-client-key,x-access-token, x-client-token, x-client-secret,x-access-user, Authorization"
);
next();
});
app.use(
session({
secret: "passport-tutorial",
cookie: { maxAge: 60000 },
resave: false,
saveUninitialized: false
})
);
require("./routers/user.router")(app);
require("./routers/token.router")(app);
require("./routers/comment.router")(app);
require("./routers/message.router")(app);
require("./routers/summary.router")(app);
require("./routers/hotel.router")(app);
require("./routers/chat-message.router")(app);
if (!isProduction) {
app.use(errorHandler());
}
app.use(
session({
key: "user",
secret: "somerandonstuffs",
resave: false,
cookie: {
expires: 600000
}
})
);
var sessionChecker = (req, res, next) => {
if (req.session.user && req.cookies.user) {
res.redirect("/login");
} else {
next();
}
};
// Passport session setup.
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
app.post("/logintest", function (req, res, next) {
passport.authenticate("local", function (err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.redirect("/login");
}
req.logIn(user, function (err) {
if (err) {
return next(err);
}
return res.redirect("/users/");
});
})(req, res, next);
});
passport.use(
new FacebookStrategy(
{
clientID: "538210533573481",
clientSecret: "c62ef6efba6694e8ff087b5826052d3a",
callbackURL: "http://localhost:3000/facebook/auth/facebook/callback"
},
function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
console.log("tests" + accessToken, refreshToken, profile, done);
return done(null, profile);
});
}
)
);
passport.use(
new GoogleStrategy(
{
clientID:
"119533488129-f4gqclpfefct9s9p5kdpop9p22pouqj9.apps.googleusercontent.com",
clientSecret: "EBg6MkFXITqBrnASBCWTY305",
callbackURL: "http://localhost:3000/google/auth/google/callback"
},
function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
console.log("tests" + accessToken, refreshToken, profile, done);
return done(null, profile);
});
}
)
);
app.get('/api', function (req, res) {
res.end('File catcher');
});
// POST File
app.post('/api/upload', upload.single('image'), function (req, res) {
if (!req.file) {
console.log("No file is available!");
return res.send({
success: false
});
} else {
console.log('File is available!', res.req.file.filename);
return res.send({
success: true,
filePath: res.req.file.filename
})
}
});
// GET File
var mime = require('mime');
var fs = require('fs');
app.get('/api/images/:imgName', function (req, res) {
let imgName = req.params.imgName;
//const file = `${__dirname}/uploads/`+imgName;
//res.download(file);
var file = `${__dirname}/uploads/` + imgName;
var filename = path.basename(file);
var mimetype = mime.lookup(file);
// res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-disposition', 'application/png');
// res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(file);
filestream.pipe(res);
});
const rule = new cron.RecurrenceRule();
rule.dayOfWeek = [5, 6, 0, 1, 2, 3, 4,];
rule.hour = 9;
rule.minute = 36;
cron.scheduleJob(rule, function () {
Tokens.deleteMany({}, function (error) {
if (error) console.log(error);
console.log('delete tokens successful')
})
console.log(new Date(), 'The 30th second of the minute.');
});
app.use(passport.initialize());
app.use(passport.session());
app.enable('trust proxy');
// only if you're behind a reverse proxy (Heroku, Bluemix, AWS if you use an ELB, custom Nginx setup, etc)
var limiter = new RateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 1000, // limit each IP to 100 requests per windowMs
delayMs: 0 // disable delaying - full speed until the max limit is reached
});
// apply to all requests
app.use(limiter);
// const http = require('http');
// const server = http.Server(app);
// const socketIO = require('socket.io');
// const io = socketIO(server);
server = require('http').createServer(app),
io = require('socket.io').listen(server)
const port = process.env.PORT || 8000;
listUserOnline = {}
io.sockets.on('connection', function (socket) {
let cookie = socket.request.headers.cookie;
console.log(socket.request.headers)
if (cookie !== undefined) {
let cookieArray = cookie.split(';');
let user = '';
cookieArray.forEach(key => {
if (key.indexOf('ObjectId') !== -1) {
let array = key.split('=');
user = array[1].trim();
}
});
if (user !== '') {
// console.log(user + '-' + socket.id)
listUserOnline[user] = socket.id;
}
}
// listUserOnline[check] = socket.id;
// tại đây khi mà io đc gửi lên e cho a cái hàm send message lại cho chính cái io đấy ở bên angular gửi tin nhắn đó
// socket.emit('wellcome',{mess: }
socket.on('setSocketId', function (socketData) {
let userName = socketData.name + '-' + socketData.userId;
// console.log(userName);
listUserOnline[userName] = socket;
// console.log(Object.keys(listUserOnline))
});
socket.on('new-message', (message) => {
let ObjectId = message.objectId;
let sendMessage = message.message;
let id = listUserOnline[ObjectId];
// console.log(' id nè' + id)
// console.log(' user nè ' + sendMessage)
// listUserOnline[message]=socket;
socket.broadcast.to(id).emit('message', sendMessage);
});
socket.on('new-notification', (notification) => {
let ObjectId = notification.objectId;
let sendNotification = notification.message;
let id = listUserOnline[ObjectId];
socket.broadcast.to(id).emit('notification', sendNotification);
});
socket.on('get-list-online', (message) => {
let ObjectId = message.objectId;
if(message.message==='remove user'){
listUserOnline[ObjectId]='';
}
let sendMessage = { 'get-list-online': listUserOnline };
let id = listUserOnline[ObjectId];
// console.log(' id nè1 ' + id)
// listUserOnline[message]=socket;
socket.broadcast.emit('message', sendMessage);
});
// console.log(Object.keys(listUserOnline))
});
server.listen(port, () => {
console.log(`started on port: ${port}`);
});
/*
var server = app.listen(process.env.PORT || 8000, function () {
var port = server.address().port;
console.log("Express is working on port " + port);
});
*/