-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
378 lines (287 loc) · 11 KB
/
server.js
File metadata and controls
378 lines (287 loc) · 11 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
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
var express = require('express');
var app = express();
var redis = require("redis");
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var morgan = require('morgan');
var passport =require('passport');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var client = redis.createClient();
var flash = require('connect-flash');
var moment=require('moment');
var LocalStrategy = require('passport-local').Strategy;
var server = require('http').Server(app);
var Schema = mongoose.Schema;
var ObjectId = mongoose.Types.ObjectId;
var db = mongoose.connection;
mongoose.connect('mongodb://localhost/Thirst_Keeper');
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.local._id = new ObjectId();
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
});
}));
var userSchema = mongoose.Schema({
local : {
_id : Schema.ObjectId,
email : String,
password : String,
timeoffset :{ type: String, default: moment().utcOffset()},
subscribe :{ type: Boolean,default: false},
send :{ type: Boolean,default: false},
device :[]
}
});
var dataSchema = mongoose.Schema({
_creator : { type: Schema.ObjectId, ref: 'User' },
_id : Schema.ObjectId,
date : String,
value : Number
});
// methods ======================
// generating a hash
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
var User = mongoose.model('User',userSchema);
var Data = mongoose.model('Data',dataSchema);
sessionStore = new redisStore({ host: 'localhost', port: 6379, client: client,ttl : 260});
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser());
app.set('view engine', 'ejs');
app.use(session({
secret: 'ssshhhhh',
// create new redis store.
cookie:{_expires : 35000000000},
store: sessionStore,
saveUninitialized: true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(express.static('public'));
app.use(express.static('node_modules/progressbar.js/dist'));
app.get('/', function(req, res) {
res.render('home.ejs'); // load the index.ejs file
});
app.get('/credit', function(req, res) {
// render the page and pass in any flash data if it exists
res.render('credit.ejs');
});
app.get('/login', function(req, res) {
// render the page and pass in any flash data if it exists
res.render('login.ejs', { message: req.flash('loginMessage') });
});
app.get('/home', function(req, res) {
// render the page and pass in any flash data if it exists
res.render('home.ejs');
});
app.get('/signup', function(req, res) {
// render the page and pass in any flash data if it exists
res.render('signup.ejs', { message: req.flash('signupMessage') });
});
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/today', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/today', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
app.get('/today', isLoggedIn, function(req, res) {
var today = moment().utcOffset(req.user.local.timeoffset).format("YYYY-MM-DD");
Data.findOne({ '_creator' : req.user.local._id, 'date' : today }, function(err, data) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no data is found, return the message
if (!data){
var newData = new Data();
// set the user's local credentials
newData._creator = req.user.local._id;
newData._id = new ObjectId();
newData.date = today;
newData.value = 0;
// save the data
newData.save(function(err) {
if (err)
throw err;
console.log("created new data");
});
res.render('today.ejs', {
data : newData // get the user out of session and pass to template
});
}else{
res.render('today.ejs', {
data : data // get the user out of session and pass to template
});
}
});
});
app.put('/api/drinkup', isLoggedIn , function(req, res) {
var today = moment().utcOffset(req.user.local.timeoffset).format("YYYY-MM-DD");
console.log(today);
Data.findOneAndUpdate({ '_creator' : req.user.local._id, 'date': today, 'value':{$lt : 8}},{$inc:{value:1}}, {new:true}, function(err, data) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no data is found, return the message
if (!data){
res.status(200).send("-.-");
}else{
console.log(data.value);
res.json({value:data.value});
}
});
// render the page and pass in any flash data if it exists
});
app.put('/api/synctime:offset', isLoggedIn , function(req, res) {
var theoffset = req.params.offset;
User.findOneAndUpdate({ 'local._id' : req.user.local._id},{$set:{'local.timeoffset':theoffset}}, {new: true}, function(err, data) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no data is found, return the message
if (!data){
res.status(400).send("Sorry can't find that!");
}else{
console.log(theoffset);
res.status(200).send("thanks!");
}
});
// render the page and pass in any flash data if it exists
});
app.get('/status', isLoggedIn ,function(req, res){
var myq;
let today = moment().utcOffset(req.user.local.timeoffset).format("YYYY-MM-DD");
var queries = [];
for(let i = 0;i<7 ;i++){
let nowDate = moment(today).subtract(i,'days').format("YYYY-MM-DD");
myq = Data.findOne({ '_creator' : req.user.local._id, 'date': nowDate});
queries.push(myq);
}
Promise.all(queries).then(function(results){
console.log(results);
var reData = {};
results.forEach(function (data, i, array) {
if (data) {
reData[i]= [moment(data.date).format("MM-DD-YYYY"), data.value];
} else {
let nowDate = moment(today).subtract(i,'days').format("MM-DD-YYYY");
reData[i]= [nowDate,0];
}
});
console.log(reData);
res.render('status.ejs', {data:reData});
});
});
app.put('/api/adddevice:device/:sub', isLoggedIn , function(req, res) {
var ifsub =false;
if(req.params.sub === "yes"){
ifsub = true;
}
User.findOneAndUpdate({ 'local._id' : req.user.local._id},{$addToSet: {"local.device": req.params.device}, $set: { "local.subscribe": ifsub }} ,{new:true},function(err, data) {
if (err)
return done(err);
if (!data){
res.status(400).send("Sorry can't find that!");
}else{
res.status(200).send("thanks");
}
});
});
app.get('/test', function(req, res) {
res.render('index.ejs');
});
app.get('/logout', function(req, res) {
req.session.destroy(function(err){
if(err){
console.log(err);
} else {
res.redirect('/login');
}
});
});
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/login');
}
server.listen(8000);
console.log('The magic happens on port 8000');