routes.js 13.1 KB
Newer Older
Rosanny Sihombing's avatar
Rosanny Sihombing committed
1
2
const fs = require('fs');
const SamlStrategy = require('passport-saml').Strategy;
3
4
const dbconn = require('./dbconn');
const methods = require('./methods');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
5
6
7
// pwd encryption
const bcrypt = require('bcryptjs');
const saltRounds = 10;
8
const salt = 64; // salt length
Rosanny Sihombing's avatar
Rosanny Sihombing committed
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
// forgot pwd
const async = require('async');
const crypto = require('crypto');
const nodemailer = require('nodemailer');

module.exports = function (app, config, passport) {

  // =========== PASSPORT =======
  passport.serializeUser(function (user, done) {
    done(null, user);
  });

  passport.deserializeUser(function (user, done) {
    done(null, user);
  });

  var samlStrategy = new SamlStrategy({
      // URL that goes from the Identity Provider -> Service Provider
      callbackUrl: config.passport.saml.path,
      // Base address to call logout requests
      logoutUrl: config.passport.saml.logoutUrl,
      
      entryPoint: config.passport.saml.entryPoint,
      issuer: config.passport.saml.issuer,
      identifierFormat: null,
      
      // Service Provider private key
      decryptionPvk: fs.readFileSync(__dirname + '/cert/key.pem', 'utf8'),
      // Service Provider Certificate
      privateCert: fs.readFileSync(__dirname + '/cert/key.pem', 'utf8'),
      // Identity Provider's public key
      cert: fs.readFileSync(__dirname + '/cert/cert_idp.pem', 'utf8'),
      
      validateInResponseTo: false,
      disableRequestedAuthnContext: true
    },
    function (profile, done) {
      return done(null,
        {
          id: profile.nameID,
          idFormat: profile.nameIDFormat,
          email: profile.email,
          firstName: profile.givenName,
          lastName: profile.sn
        });
    });
  
  passport.use(samlStrategy);
  // ============================
/*
  app.all('/', function(req, res){
    req.flash('test', 'it worked');
    res.redirect('/test')
  });
  app.all('/test', function(req, res){
    res.send(JSON.stringify(req.flash('test')));
  });
  */
67
  app.get('/', function (req, res) {
68
    res.redirect('/account/profile')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
69
70
  });

71
  app.get('/login',
Rosanny Sihombing's avatar
Rosanny Sihombing committed
72
73
    passport.authenticate(config.passport.strategy,
      {
74
75
        successRedirect: '/account/',
        failureRedirect: '/account/login'
Rosanny Sihombing's avatar
Rosanny Sihombing committed
76
77
78
79
80
81
      })
  );

  app.post(config.passport.saml.path,
    passport.authenticate(config.passport.strategy,
      {
82
        failureRedirect: '/account/',
Rosanny Sihombing's avatar
Rosanny Sihombing committed
83
84
85
        failureFlash: true
      }),
    function (req, res) {
86
      res.redirect('/account/');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
87
88
89
    }
  );

90
  app.get('/profile', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
91
92
93
94
95
    if (req.isAuthenticated()) {   
      res.render('profile', {
        user: req.user // useful for view engine, useless for HTML
      });
    } else {
96
      res.redirect('/account/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
97
98
99
    }
  });

100
  app.get('/services', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
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
    if (req.isAuthenticated()) {
      async.waterfall([
        // get userId by email from userdb
        function(done) {
          methods.getUserIdByEmail(req.user.email, function(userId, err) {
            if (!err) {
              done(err, userId)
            }
          })
        },
        // get user-project-role from userdb
        function(userId, done) {
          methods.getUserProjectRole(userId, function(userProjects, err) {
            if (!err) {
              done(err, userProjects)
            }
          })
        },
        // get all projects from projectdb
        function(userProjects, done) {
          methods.getAllProjects(function(projectsOverview, err) {
            if (!err) {
              done(err, userProjects, projectsOverview)
            }
          })
        },
        // create JSON object of projects and user status for front-end
        function(userProjects, projectsOverview, done) {
          var allProjects = []  // JSON object
          
          var userProjectId = []  // array of user's project_id
          for (var i = 0; i < userProjects.length; i++) {
            userProjectId.push(userProjects[i].project_id)
          }

          for (var i = 0; i < projectsOverview.length; i++) {
            // check if projectId is exist in userProjectId[]
            var status = "You cannot access this service"
            if (userProjectId.indexOf(projectsOverview[i].id) > -1) {
              status = "You can access this service"
            }
            // add data to JSON object
            allProjects.push({
              id: projectsOverview[i].id,
              title: projectsOverview[i].title,
              summary: projectsOverview[i].onelinesummary,
              cp: projectsOverview[i].contact_email,
              userStatus: status
            });
          }

          // render the page
          res.render('services', {
            user: req.user,
            project: allProjects
          });
        }
      ])
    } else {
160
      res.redirect('/account/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
161
162
163
    }
  });

164
  app.get('/security', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
165
166
167
168
169
    if (req.isAuthenticated()) {
      res.render('security', {
        user: req.user // useful for view engine, useless for HTML
      });
    } else {
170
      res.redirect('/account/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
171
172
173
    }
  });

174
  app.post('/updateProfile', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
175
176
177
178
179
180
181
182
183
184
185
186
    var userData = {
      title: req.body.inputTitle,
      firstname: req.body.inputFirstname,
      lastname: req.body.inputLastname,
      email: req.body.inputEmail,
      organisation: req.body.inputOrganisation,
      industry: req.body.inputIndustry,
      speciality: req.body.inputSpeciality,
    }
    
    if (req.isAuthenticated()) {
      if (userData.email) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
187
        dbconn.user.query('UPDATE user SET ? WHERE email = "' +userData.email+'"', userData, function (err, rows, fields) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
188
189
190
191
192
193
194
            //if (err) throw err;
            if (err) {
              req.flash('error', "Failed");
            }
            else {
              req.flash('success', 'Profile updated!');
            }
195
            res.redirect('/account/profile');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
196
197
198
        })
      }
    } else {
199
      res.redirect('/account/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
200
201
202
203
204
    }
  });

  // todo: user registration with captcha
  
205
  app.post('/changePwd', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
206
207
208
209
210
211
    if (req.isAuthenticated()) {
      var currPwd = req.body.inputCurrPwd
      var newPwd = req.body.inputNewPwd
      var retypePwd = req.body.inputConfirm
      
      // Load hashed passwd from DB.
Rosanny Sihombing's avatar
Rosanny Sihombing committed
212
      dbconn.user.query('SELECT password FROM user WHERE email="'+req.user.email+'"', function (err, rows, fields) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
213
        if (err) {
214
          res.redirect('/account/500')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
215
216
217
218
219
220
221
          throw err
        }
        var userPwd = rows[0].password

        // check if the password is correct
        bcrypt.compare(currPwd, userPwd, function(err, isMatch) {
          if (err) {
222
            res.redirect('/account/500')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
223
224
225
226
            throw err
          }
          else if (!isMatch) {
            req.flash('error', "Sorry, your password was incorrect. Please double-check your password.")
227
            res.redirect('/account/security')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
228
229
230
          } else {
            if ( newPwd != retypePwd ) {
              req.flash('error', "Passwords do no match. Please make sure you re-type your new password correctly.")
231
              res.redirect('/account/security')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
            }
            else {
              // update password
              bcrypt.genSalt(saltRounds, function(err, salt) {
                bcrypt.hash(newPwd, salt, function(err, hash) {
                  methods.updatePassword(hash, req.user.email, function(err){
                    if (err) {
                      req.flash('error', "Database error: Password cannot be modified.")
                      throw err
                    }
                    else {
                      req.flash('success', "Pasword updated!")
                      console.log('pasword updated!')
                    }
246
                    res.redirect('/account/security')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
247
248
249
250
251
252
253
254
                  })
                });
              });
            }
          }
        })
      })
    } else {
255
      res.redirect('/account/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
256
257
258
    }
  });

259
  app.get('/forgotPwd', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
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
    res.render('forgotPwd', {
      user: req.user
    });
    /*
      if email found: send generated email or instruction to reset password
      if email not found: send notification, example: https://www.troyhunt.com/everything-you-ever-wanted-to-know/
    */
  });

  var smtpTransport = nodemailer.createTransport({
    host: config.mailer.host,
    secureConnection: config.mailer.secureConnection,
    port: config.mailer.port,
    auth: {
      user: config.mailer.authUser,
      pass: config.mailer.authPass
    },
    tls: {
        ciphers: config.mailer.tlsCiphers
    } 
  });
  var mailOptions = {
    to: "",
    from: config.mailer.from,
    subject: "",
    text: ""
  };

288
  app.post('/forgotPwd', function(req, res, next) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
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
    //methods.currentDate();
    /* do something: write down reset password procedure in Technical Req. Document
      ref: https://meanstackdeveloper.in/implement-reset-password-functionality-in-node-js-express.html
      https://medium.com/@terrychayes/adding-password-reset-functionality-to-a-react-app-with-a-node-backend-4681480195d4
      http://sahatyalkabov.com/how-to-implement-password-reset-in-nodejs/
    
      if email found: send generated email or instruction to reset password
      if email not found: send notification, example: https://www.troyhunt.com/everything-you-ever-wanted-to-know/
    */
    var emailAddress = req.body.inputEmail;
    var emailContent = "Hi there,\n\n"+
      "we've received a request to reset your password. However, this email address is not on our database of registered users.\n\n"+
      "Thanks,\nM4_LAB Team";
    var emailSubject = "Account Access Attempted";
    
    async.waterfall([
      function(done) {
        crypto.randomBytes(20, function(err, buf) {
          var token = buf.toString('hex');
          done(err, token);
        });
      },
      function(token, done) {
        methods.checkUserEmail(emailAddress, function(err, user){
          if (user) {
            console.log("email: user found");
            emailSubject = "M4_LAB Password Reset";
            emailContent = "Hi User,\n\n"+
              "we've received a request to reset your password. If you didn't make the request, just ignore this email.\n\n"+
318
              "Otherwise, you can reset your password using this link: https://" + config.app.hostname + "/reset/" + token + "\n" +
Rosanny Sihombing's avatar
Rosanny Sihombing committed
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
              "This password reset is only valid for 1 hour.\n\n"+
              "Thanks,\nM4_LAB Team"
            
            user.resetPasswordToken = token;
            user.resetPasswordExpires = Date.now() + 3600000; // 1 hour

            methods.updateUser(user, function(err) {
              done(err, token, user);
            });
          }
          else {
            done(err, null, null);
          }
        });
      },
      function(token, user, done) {
        mailOptions.to = emailAddress;
        mailOptions.subject = emailSubject;
        mailOptions.text = emailContent;
        smtpTransport.sendMail(mailOptions, function(err) {
          done(err, 'done');
        });
      }
    ], function(err) {
      if (err) {
        req.flash('error', 'An error occured. Please try again.');
      }
      else {
        req.flash('success', 'An e-mail has been sent to ' + emailAddress + ' with further instructions.');
      }
349
      res.redirect('/account/forgotPwd');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
350
351
352
    });
  });

353
  app.get('/reset/:token', function(req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
354
355
356
357
    methods.checkUserToken(req.params.token, function(err, user){
      //console.log(user);
      if (!user) {
        req.flash('error', 'Password reset token is invalid or has expired.');
358
        res.redirect('/account/forgotPwd');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
359
360
361
362
363
364
365
      }
      else {
        res.render('reset');
      }
    });
  });

366
  app.post('/reset/:token', function(req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
    methods.checkUserToken(req.params.token, function(err, user){
      if (user) {
        // update password
        bcrypt.genSalt(saltRounds, function(err, salt) {
          bcrypt.hash(req.params.inputNewPwd, salt, function(err, hash) {
            methods.updatePassword(hash, user.email, function(err){
              if (err) {
                req.flash('error', "Database error: Password cannot be modified.")
                throw err
              }
              else {
                req.flash('success', "Your pasword has been updated.")
                console.log('pasword updated!')
                // todo: send confirmation email
              }
            })
          });
        });
      }
      else {
        req.flash('error', "User not found.")
      }
    });
   
391
    res.redirect('/account/login')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
392
393
  });

394
  app.get('/logout', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
395
    if (req.user == null) {
396
      return res.redirect('/account/');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
    }
    
    req.user.nameID = req.user.id;
    req.user.nameIDFormat = req.user.idFormat;
    return samlStrategy.logout(req, function(err, uri) {
      req.logout();
      
      if ( req.session ) {
        req.session.destroy((err) => {
          if(err) {
              return console.log(err);
          }
        });
      }
     
      return res.redirect(uri);
    });

  });

  // to generate Service Provider's XML metadata
418
  app.get('/saml/metadata', 
Rosanny Sihombing's avatar
Rosanny Sihombing committed
419
420
421
422
423
424
425
426
    function(req, res) {
      res.type('application/xml');
      var spMetadata = samlStrategy.generateServiceProviderMetadata(fs.readFileSync(__dirname + '/cert/cert.pem', 'utf8'));
      res.status(200).send(spMetadata);
    }
  );

};