-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
382 lines (335 loc) · 15.6 KB
/
app.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
const md5 = require('md5');
const path = require('path');
const uuid = require('uuid');
const express = require('express');
const passport = require('passport');
const bcrypt = require('bcrypt-nodejs');
const admin = require('firebase-admin');
const session = require('express-session');
const body_parser = require('body-parser');
const node_uuid = require('node-time-uuid');
const cookie_parser = require('cookie-parser');
const react_views = require('express-react-views');
const memorystore = require('memorystore')(session);
const LocalStrategy = require('passport-local').Strategy;
const app = express();
if (app.settings.env === 'development') {
require('dotenv').config();
}
const http = require('http').Server(app);
const io = require('socket.io')(http);
admin.initializeApp({
credential: admin.credential.cert({
projectId: process.env.FIREBASE_PROJECT_ID,
privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
clientEmail: process.env.FIREBASE_CLIENT_EMAIL
}),
databaseURL: process.env.FIREBASE_DATABASE_URL
});
app.set('view engine', 'jsx');
app.set('views', path.join(__dirname, 'views'));
app.use(cookie_parser());
app.use(body_parser.urlencoded({extended: false}));
const session_middleware = session({
secret: 'secretsdontmakefriendsfriendsmakesecrets',
saveUninitialized: false,
resave: false,
store: new memorystore({
checkPeriod: 24 * 60 * 60 * 1000
})
});
app.use(session_middleware);
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, {email: user.email, id: user.id, conversations: user.conversations});
});
passport.deserializeUser(function(user, done) {
admin.database().ref('/users').child(user.id).once('value')
.then(function(snapshot) {
done(null, snapshot.val());
}, function(rejection_reason) {
console.log('$$$ could not finish deserializing user', rejection_reason);
done(rejection_reason, {});
}).catch(function(error) {
done(error, {});
});
});
passport.use('local-signup', new LocalStrategy({
usernameField: 'username',
passwordField: 'userpass',
passReqToCallback: true
},
function(req, email, password, done) {
process.nextTick(function() {
admin.database().ref('/users').child(md5(email)).once('value')
.then(function(snapshot) {
// will return `true` if snapshot.val() is `null` and email address isn't taken
if (!snapshot.val()) {
const new_user = {
id: md5(email),
email: email,
marinade: bcrypt.hashSync(password, bcrypt.genSaltSync(8), null),
conversations: {}
};
admin.database().ref('/users').child(md5(email)).set(new_user)
.then(function(data) {
return done(null, new_user);
}, function(rejection_reason) {
console.log('$$$ user could not be created', rejection_reason);
}).catch(function(error) {
return done(error)
});
} else {
return done(null, false);
}
}, function(rejection_reason) {
console.log('$$$ could not sign the user up', rejection_reason);
}).catch(function(error) {
console.log('$$$ a database error occurred when creating user', error);
return done(error);
});
});
}
));
passport.use('local-signin', new LocalStrategy({
usernameField: 'username',
passwordField: 'userpass',
passReqToCallback: true
},
function(req, email, password, done) {
process.nextTick(function() {
admin.database().ref('/users').child(md5(email)).once('value')
.then(function(snapshot) {
if (!snapshot.val()) {
return done(null, false);
}
const user = snapshot.val();
if (bcrypt.compareSync(password, user.marinade)) {
return done(null, user);
}
return done(null, false);
}, function(rejection_reason) {
console.log('$$$ COULD NOT SIGN A USER', rejection_reason);
return done(error);
}).catch(function(error) {
console.log('$$$ a database error occurred when searching for a user', error);
return done(error);
});
});
}
));
io.use(function(socket, next) {
session_middleware(socket.request, {}, next);
});
io.on('connection', function(socket) {
socket.on('open_conversation', function(counterpart_email) {
const current_user = socket.request.session.passport.user;
let previous_conversation = current_user.open_conversation;
if (isEmpty(previous_conversation)) {
previous_conversation = "";
}
current_user.open_conversation = counterpart_email;
// update the client side with server side set cookies
if (!current_user.hasOwnProperty('conversations') || !current_user.conversations[md5(counterpart_email)]) {
admin.database().ref('/users').child(current_user.id).once('value')
.then(function(snapshot) {
if (!snapshot.val()) {
console.log('$$$ COULD NOT FIND USER IN DATABASE WHEN UPDATING', snapshot);
} else {
current_user.conversations = snapshot.val().conversations;
admin.database().ref('/conversations').child(snapshot.val().conversations[md5(counterpart_email)])
.orderByKey().limitToLast(10).once('value')
.then(function(message_history) {
if (!message_history.val()) {
console.log('$$$ NO MESSAGE HISTORY FOR THESE NEW CONNECTIONS', message_history.val());
io.sockets.connected[socket.id].emit('show_conversation',
{
active_conversation: current_user.conversations[md5(counterpart_email)],
previous_conversation: current_user.conversations[md5(previous_conversation)],
message: 'Have fun chatting.'
}
);
} else {
io.sockets.connected[socket.id].emit('show_conversation',
{
active_conversation: current_user.conversations[md5(counterpart_email)],
previous_conversation: current_user.conversations[md5(previous_conversation)],
message: 'Have fun chatting.',
history: message_history.val()
}
);
}
})
}
}, function (rejection_reason) {
console.log('$$$ COULD NOT FINISH OPEING THE CONVERSATION', rejection_reason);
return;
}).catch(function(error) {
console.log('$$$ CAUGHT THE FOLLOWING ERROR WHEN UPDATING CONVERSATIONS', error);
return;
});
} else {
// get all the messages at this location and send them back to the client
admin.database().ref('/conversations').child(current_user.conversations[md5(counterpart_email)])
.orderByKey().limitToLast(10).once('value')
.then(function(snapshot) {
if (!snapshot.val()) {
console.log('$$$ NO MESSAGES WERE FOUND FOR THE TWO USERS', snapshot.val());
io.sockets.connected[socket.id].emit('show_conversation',
{
active_conversation: current_user.conversations[md5(counterpart_email)],
previous_conversation: current_user.conversations[md5(previous_conversation)],
message: 'Get to talking.'
}
);
} else {
io.sockets.connected[socket.id].emit('show_conversation',
{
active_conversation: current_user.conversations[md5(counterpart_email)],
previous_conversation: current_user.conversations[md5(previous_conversation)],
message: 'Keep it going.',
history: snapshot.val()
}
);
}
}, function(rejection_reason) {
console.log('$$$ PROMISE REJECTED COULD NOT FIND CONVERSATION', rejection_reason);
return;
}).catch(function(error) {
console.log('$$$ CAUGHT THE FOLLOWING ERROR WHEN LOOKING FOR MESSAGES', error);
return;
});
}
});
socket.on('write_message', function(message_text) {
const current_user = socket.request.session.passport.user;
const message_id = new node_uuid().toString('pretty');
const sender = current_user.email;
const new_message = {
text: message_text,
sender: sender
}
admin.database().ref('/conversations').child(current_user.conversations[md5(current_user.open_conversation)]).child(message_id)
.set(new_message)
.then(function() {
return;
}, function(rejection_reason) {
console.log('$$$ COULD NOT FINISH WRITING THE MESSAGE', rejection_reason);
}).catch(function(error) {
console.log('$$$ SOMETHING WENT WRONG WHEN WRITING THE MESSAGE', error);
return;
});
});
});
function checkAuth(request, response, next) {
if (request.isAuthenticated()) {
if (request.route.path === '/') {
response.redirect('/home');
} else {
next();
}
} else {
if (request.route.path === '/') {
next();
} else {
response.redirect('/logout');
}
}
};
app.use('/scripts', express.static(path.join(__dirname, 'scripts')));
app.use('/stylesheets', express.static(path.join(__dirname, 'stylesheets')));
app.engine('jsx', react_views.createEngine());
app.get('/', checkAuth, function(request, response) {
response.render('login');
});
app.get('/home', checkAuth, function(request, response) {
const current_user = request.session.passport.user;
admin.database().ref('/users').child(current_user.id).child('conversations').once('value')
.then(function(active_chats) {
if (!active_chats.val()) {
console.log('$$$ USER DID NOT HAVE ANY ACTIVE CHATS');
response.render('home', {email: current_user.email, conversation_counterparts: []});
return;
}
const users_to_lookup = Object.keys(active_chats.val());
const promises = users_to_lookup.map(function(user_id) {
return admin.database().ref('/users').child(user_id).once('value');
});
Promise.all(promises).then(function(snapshots) {
const user_display_names = snapshots.map(function(snapshot) {
return {email: snapshot.val().email};
});
response.render('home', {email: current_user.email, conversation_counterparts: user_display_names});
}, function(rejection_reason) {
console.log('$$$ COULD NOT LOG A USER IN', rejection_reason);
});
}, function(rejection_reason) {
console.log('$$$ SOMETHING WENT WRONG WHEN LOGGING A USER IN', rejection_reason);
response.redirect('/');
}).catch(function(error) {
console.log('$$$ SOMETHING WENT WRONG WHEN LOOKING IN THE DATABASE', error);
response.redirect('/');
});
});
app.post('/connect', checkAuth, function(request, response) {
const current_user = request.session.passport.user;
const submitted_value = request.body.search_query;
admin.database().ref('/users').child(md5(submitted_value)).once('value')
.then(function(snapshot) {
if (!snapshot.val()) {
console.log('$$$ YOU CANNOT CHAT WITH NON EXISTENT USERS');
response.send({error: 'You cannot chat with nonexistent users.'});
return;
}
const counterpart = snapshot.val();
// you're already chatting with this person, don't update the database
if (counterpart.hasOwnProperty('conversations') && counterpart.conversations.hasOwnProperty(current_user.id)) {
response.send({error: 'You cannot recreate existing chats'});
return;
}
const users_to_connect = [counterpart.id, current_user.id];
const conversation_id = uuid();
const promises = users_to_connect.map(function(user_id, index) {
return admin.database().ref('/users').child(user_id).child('conversations')
.child(users_to_connect[(users_to_connect.length - 1) - index])
.set(conversation_id);
});
Promise.all(promises).then(function(snapshots) {
response.send({
success: `Successfully connected you to ${counterpart.email}.`,
connection: counterpart.email
});
}, function(rejection_reason) {
console.log('$$$ COULD NOT CONNECT USERS', rejection_reason);
response.send({error: 'A database error occurred while looking for a user.'});
});
}, function(rejection_reason) {
console.log('$$$ COULD NOT CONNECT USERS', rejection_reason);
response.send({error: 'A database error occurred while looking for a user.'});
}).catch(function(error) {
console.log('$$$ A DATABASE ERROR OCCURRED WHILE LOOKING FOR A USER', error);
response.send({error: 'A database error occurred while looking for a user.'});
});
});
app.get('/logout', function(request, response) {
request.logout();
request.session.destroy(function(error) {
response.redirect('/');
});
});
app.post('/signin', passport.authenticate('local-signin'), function(request, response) {
response.redirect('/home');
});
app.post('/signup', passport.authenticate('local-signup'), function(request, response) {
response.redirect('/home');
});
app.post('/home', function(request, response) {
response.redirect('/home');
});
http.listen(process.env.PORT || 3000, function() {
console.log('Listening on port', this.address().port, 'in context', app.settings.env);
});
function isEmpty(value) {
return value === undefined || value === '' || value === null;
}