-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
304 lines (265 loc) · 10.2 KB
/
server.js
File metadata and controls
304 lines (265 loc) · 10.2 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
//server.js
//load all dependencies
var express = require('express');
var app = express(); // create our app with express
var redis = require("redis"), // using redis db
client = redis.createClient(); // redis client
var morgan = require('morgan'); // log requests to the console () debugging
var bodyParser = require('body-parser'); // pull information from HTML POST ()
var methodOverride = require('method-override'); // simulate DELETE and PUT ()
var counterUserID = 1220; // random id for user
var counterTodosId = 4322; // random id for tasks
var nodemailer = require("nodemailer"); // to send mails to user
var path = require("path"); // path
var EmailTemplate = require("email-templates").EmailTemplate; // load email templates
var ejs = require('ejs'); // load ejs
var cron = require('node-schedule'); // cron scheduler
var passport = require('passport'); // passport for facebook login
var config = require('./configuration/auth'); // to read configuration
var FacebookStrategy = require('passport-facebook').Strategy ;// facebook login strategy
var GoogleStrategy = require('passport-google-oauth').OAuthStrategy; // gmail login strategy
// configuration =================
client.on('connect', function() { // connection to redis server
console.log('connected');
});
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use('/bower_components', express.static(__dirname + '/bower_components')); // use js from bower components
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.set('view engine', 'ejs');
// listen (start app with node server.js) ======================================
app.listen(8080);
console.log("App listening on port 8080");
// notification tracker
// keeps track of tasks whose notification hs been sent
var notificationSent =[];
// cron scheduler
/* This runs at the 15th mintue of every hour. */
/* cron runs through all the tasks and if its due date is less than or equalt to 15 it shoots a mail to concerned
user .*/
cron.scheduleJob('*/15 * * * *', function(){
console.log('This runs at the 15th mintue of every hour.');
client.hgetall("userTodos", function(err, objs) {
for(var k in objs) {
var task = JSON.parse(objs[k]);
if(notificationSent.indexOf(task.id) == -1 ){
var userId = task.userId;
var taskDate = task.dueDate;
var mins = 1000 * 60;
var selectedDate = new Date(taskDate);
var currentDate = new Date();
var dueTime = Math.round((selectedDate.getTime() - currentDate.getTime()) / mins );
// if due date is less than or equal to 15
if(dueTime > 0 && dueTime<=15){
client.hmget("usersData",userId,function (err,obj){
var user = JSON.parse(obj);
var notification ={
"user":{
"email":user.email,
"id":user.id,
"task":{
"id":task.id,
"name":task.task,
"dueDate":new Date (task.dueDate)
}
}
};
notificationSent.push(task.id);
// send mail
sendMail(notification);
});
}
}
}
});
});
// template for email that has 2 options to delete or snooze the task
var templatesDir = path.resolve(__dirname +'/public/templates') ;// load templates
var template = new EmailTemplate(path.join(templatesDir, 'notifications'));
// setup smtp connection
// enter your gmail userName and password
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: config.email,
pass: config.password
}
});
// function to send mail to concerned user
// enter your from user id here
function sendMail (mailer){
template.render(mailer, function (err, results) {
if (err) {
return console.error(err)
}
smtpTransport.sendMail({
from: config.email, // sender address
to: mailer.user.email, // comma separated list of receivers
subject: "Your personal Assistant", // Subject line
html: results.html,
text: results.text
}, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
});
});
}
// facebook login ==============================================================
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
passport.use(new FacebookStrategy({
clientID: config.facebook_api_key,
clientSecret:config.facebook_api_secret ,
callbackURL: config.facebook_callback_url
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function () {
//Check whether the User exists or not using profile.id
//Further DB code.
console.log("Welcome " + profile.displayName + " could not login you into the application .Please try normal method");
return done(null, profile);
});
}
));
//Passport Router
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/',
failureRedirect: '/'
}),
function(req, res) {
res.redirect('/');
});
// Gmail Login ================================================================
passport.use(new GoogleStrategy({
consumerKey: config.google_api_key,
consumerSecret: config.google_api_secret,
callbackURL: config.google_callback_url
},
function(token, tokenSecret, profile, done) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
// The request will be redirected to Google for authentication, so
// this function will not be called.
app.get('/auth/google',passport.authenticate('google'));
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
});
// routes ======================================================================
// this method registers a new user into the application
// by assigning a random user id
app.post('/register', function(req, res) {
var userData = req.body;
userData.id = counterUserID++;
client.hset('usersData',userData.id,JSON.stringify(userData));
return res.send(200,userData.id);
});
// this method logsin the user who is already registered.
// checks in the db if user id and password matches or not.
// send relevant messages
app.post('/signin', function(req, res) {
var userData = req.body;
var found= false;
client.hgetall("usersData", function(err, objs) {
for(var k in objs) {
var user = JSON.parse(objs[k]);
if(user.email == userData.email){
found =true;
if(user.password == userData.password){
return res.send(200,user.id);
}
else{
return res.send(403,"Password doesn't match");
}
}
}
if(!found){
return res.send(403,"Email doesn't exists");
}
});
});
// create todo task
app.post('/api/todos', function(req, res) {
var newTodo = req.body;
newTodo.id= counterTodosId++;
newTodo.dueDate = new Date(newTodo.dueDate);
client.hset("userTodos", newTodo.id, JSON.stringify(newTodo));
return res.send(200,newTodo.id);
});
// deletes a todo task when user selects this option from mail.
// verifies if the task exists and is assigned to that specific user or not.
app.get('/deleteTask/', function(req, res) {
task_id = req.query.task_id;
user_id = req.query.user_id;
var taskFound = false;
client.hmget("userTodos",task_id,function (err,obj){
try {
var task = JSON.parse(obj);
taskFound = true;
if(task.userId == user_id){
if(client.hdel("userTodos",task_id)){
return res.send(200,"Task Deleted");
}
}
else{
return res.send(403,"Invalid User");
}
}
catch (e) {
console.log("task not found");
}
if(!taskFound){
return res.send(403,"Task not found");
}
});
});
// snooze a todo task when user selects this option from mail.
// verifies if the task exists and is assigned to that specific user or not.
app.get('/snoozeTask/', function(req, res) {
task_id = req.query.task_id;
user_id = req.query.user_id;
var taskFound = false;
client.hmget("userTodos",task_id,function (err,obj){
try {
var task = JSON.parse(obj);
taskFound = true;
if(task.userId == user_id){
var selectedDate = new Date(task.dueDate);
selectedDate.setDate(selectedDate.getDate() + 1);
task.dueDate = new Date(selectedDate);
if(client.hset("userTodos", task.id, JSON.stringify(task))){
notificationSent.splice(notificationSent.indexOf(task.id));
return res.send(200,"Task pushed by 1 day");
}
}
else{
return res.send(403,"Invalid User");
}
}
catch (e) {
console.log(e);
}
if(!taskFound){
return res.send(403,"Task not found");
}
});
});