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

14
module.exports = function (app, config, passport, i18n) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
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

  // =========== 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
44
45
46
47
48
49
50
51
  },
  function (profile, done) {
    return done(null, {
      id: profile.nameID,
      idFormat: profile.nameIDFormat,
      email: profile.email,
      firstName: profile.givenName,
      lastName: profile.sn
Rosanny Sihombing's avatar
Rosanny Sihombing committed
52
    });
53
  });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
54
55
  
  passport.use(samlStrategy);
56
57
58
59
60

  // ============= SAML ==============
  app.post(config.passport.saml.path,
    passport.authenticate(config.passport.strategy,
      {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
61
        failureRedirect: '/',
62
63
64
        failureFlash: true
      }),
    function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
65
      res.redirect('/');
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    }
  );

  // to generate Service Provider's XML metadata
  app.get('/saml/metadata', 
    function(req, res) {
      res.type('application/xml');
      var spMetadata = samlStrategy.generateServiceProviderMetadata(fs.readFileSync(__dirname + '/cert/cert.pem', 'utf8'));
      res.status(200).send(spMetadata);
    }
  );

  // ======== NODEMAILER ====================
  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
    } 
Rosanny Sihombing's avatar
Rosanny Sihombing committed
90
  });
91
92
93
94
95
96
97
  
  var mailOptions = {
    to: "",
    from: config.mailer.from,
    subject: "",
    text: ""
  };
98
99
100
101
102

  var updatePasswordMailContent = "Hello,\n\n"+
    "We would like to notify that your password has been successfully updated.\n\n"+
    "Thanks,\nM4_LAB Team"
  var updatePasswordMailSubject = "Your M4_LAB Password has been updated"
103
104
105
106
107
108
109

  // ================ test i18n ==================
  i18n.setLocale('de');
  app.get('/de', function(req, res) {
    var greeting = i18n.__('Hello World')
    res.send(greeting)
  });
110
111
  
  // ======== APP ROUTES ====================
112
113
114
115
116
117
118
119
120
121
122
123
  app.get('/account', function (req, res) {
    if (req.isAuthenticated()) {
      methods.getUserByEmail(req.user.email, function(data, err){
        if (!err) {
          res.render('home', {
            greeting: i18n.__('Hello'),
          });
        }
      })
    } else {
      res.redirect('/account/login');
    }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
124
125
126
127
  });

  app.get('/error', function (req, res) {
    res.render('error')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
128
129
  });

130
  app.get('/account/login',
Rosanny Sihombing's avatar
Rosanny Sihombing committed
131
132
    passport.authenticate(config.passport.strategy,
      {
133
134
        successRedirect: '/account/',
        failureRedirect: '/account/login'
Rosanny Sihombing's avatar
Rosanny Sihombing committed
135
136
137
      })
  );

138
139
  app.get('/logout', function (req, res) {
    if (req.user == null) {
140
      return res.redirect('https://m4lab.hft-stuttgart.de');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
141
    }
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    
    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);
    });
  });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
159

160
  app.get('/account/profile', function (req, res) {
161
162
163
164
165
166
167
168
169
    if (req.isAuthenticated()) {
      methods.getUserByEmail(req.user.email, function(data, err){
        if (!err) {
          res.render('profile', {
            user: data,
            email: req.user.email
          });
        }
      })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
170
    } else {
171
      res.redirect('/account/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
172
173
174
    }
  });

175
  app.get('/account/services', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
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
    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[]
Rosanny Sihombing's avatar
Rosanny Sihombing committed
213
            var status = false
Rosanny Sihombing's avatar
Rosanny Sihombing committed
214
            if (userProjectId.indexOf(projectsOverview[i].id) > -1) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
215
              status = true
Rosanny Sihombing's avatar
Rosanny Sihombing committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
            }
            // 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 {
235
      res.redirect('/account/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
236
237
238
    }
  });

239
  app.get('/account/security', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
240
241
242
243
244
    if (req.isAuthenticated()) {
      res.render('security', {
        user: req.user // useful for view engine, useless for HTML
      });
    } else {
245
      res.redirect('/account/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
    }
  });

  app.post('/updateProfile', function (req, res) {
    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
262
        dbconn.user.query('UPDATE user SET ? WHERE email = "' +userData.email+'"', userData, function (err, rows, fields) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
263
264
265
266
267
268
269
            //if (err) throw err;
            if (err) {
              req.flash('error', "Failed");
            }
            else {
              req.flash('success', 'Profile updated!');
            }
270
            res.redirect('/account/profile');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
271
272
273
        })
      }
    } else {
274
      res.redirect('/account/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
275
276
277
278
279
280
281
282
283
    }
  });
  
  app.post('/changePwd', function (req, res) {
    if (req.isAuthenticated()) {
      var currPwd = req.body.inputCurrPwd
      var newPwd = req.body.inputNewPwd
      var retypePwd = req.body.inputConfirm

284
285
286
287
288
      methods.getUserIdByEmail(req.user.email, function(userId, err) {
        if (!err) {
          // Load hashed passwd from DB
          dbconn.user.query('SELECT password FROM credential WHERE user_id='+userId, function (err, rows, fields) {
            if (err) {
289
              res.redirect('/account/500')
290
              throw err
Rosanny Sihombing's avatar
Rosanny Sihombing committed
291
            }
292
293
294
295
296
            var userPwd = rows[0].password

            // check if the password is correct
            bcrypt.compare(currPwd, userPwd, function(err, isMatch) {
              if (err) {
297
                res.redirect('/account/500')
298
299
300
301
                throw err
              }
              else if (!isMatch) {
                req.flash('error', "Sorry, your password was incorrect. Please double-check your password.")
302
                res.redirect('/account/security')
303
304
305
306
              }
              else {
                if ( newPwd != retypePwd ) {
                  req.flash('error', "Passwords do no match. Please make sure you re-type your new password correctly.")
307
                  res.redirect('/account/security')
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
                }
                else {
                  // update password
                  bcrypt.genSalt(saltRounds, function(err, salt) {
                    bcrypt.hash(newPwd, salt, function(err, hash) {
                      var credentialData = {
                        password: hash,
                        user_id: userId
                      }
                      methods.updateCredential(credentialData, function(err){
                        if (err) {
                          req.flash('error', "Database error: Password cannot be modified.")
                          throw err
                        }
                        else {
                          req.flash('success', "Pasword updated!")
324
325
326
327
328
329
330
331
                          mailOptions.to = req.user.email
                          mailOptions.subject = "Your M4_LAB Password has been updated"
                          mailOptions.text = updatePasswordMailContent
                          smtpTransport.sendMail(mailOptions, function(err) {
                            if (err) {
                              console.log(err)
                            }
                          });
332
                        }
333
                        res.redirect('/account/security')
334
335
336
337
338
339
                      })
                    });
                  });
                }
              }
          }) 
Rosanny Sihombing's avatar
Rosanny Sihombing committed
340
        })
341
342
343
344
        }
      })  
    }
    else {
345
      res.redirect('/account/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
346
347
348
349
350
351
352
353
354
355
356
    }
  });

  app.get('/forgotPwd', function (req, res) {
    res.render('forgotPwd', {
      user: req.user
    });
  });

  app.post('/forgotPwd', function(req, res, next) {
    //methods.currentDate();
357

Rosanny Sihombing's avatar
Rosanny Sihombing committed
358
    var emailAddress = req.body.inputEmail;
359
  /*  var emailContent = "Hi there,\n\n"+
Rosanny Sihombing's avatar
Rosanny Sihombing committed
360
361
      "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";
362
    var emailSubject = "Account Access Attempted"; */
Rosanny Sihombing's avatar
Rosanny Sihombing committed
363
364
365
366
367
368
369
370
371
372
373
374
    
    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");
375
376
            var emailSubject = "M4_LAB Password Reset";
            var emailContent = "Hi User,\n\n"+
Rosanny Sihombing's avatar
Rosanny Sihombing committed
377
              "we've received a request to reset your password. If you didn't make the request, just ignore this email.\n\n"+
378
              "Otherwise, you can reset your password using this link: http://m4lab.hft-stuttgart.de/account/reset/" + token + "\n" +
Rosanny Sihombing's avatar
Rosanny Sihombing committed
379
380
381
              "This password reset is only valid for 1 hour.\n\n"+
              "Thanks,\nM4_LAB Team"
            
382
383
384
385
386
387
            var credentialData = {
              user_id: user.id,
              resetPasswordToken: token,
              resetPasswordExpires: Date.now() + 3600000 // 1 hour
            }
            methods.updateCredential(credentialData, function(err) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
388
389
              done(err, token, user);
            });
390
391
392
393
394
395
396
397

            // send email
            mailOptions.to = emailAddress;
            mailOptions.subject = emailSubject;
            mailOptions.text = emailContent;
            smtpTransport.sendMail(mailOptions, function(err) {
              done(err, 'done');
            });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
398
399
          }
          else {
400
401
            //done(err, null, null);
            done(err, 'no user found');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
402
403
          }
        });
404
405
      }
      /*,
Rosanny Sihombing's avatar
Rosanny Sihombing committed
406
407
408
409
410
411
412
      function(token, user, done) {
        mailOptions.to = emailAddress;
        mailOptions.subject = emailSubject;
        mailOptions.text = emailContent;
        smtpTransport.sendMail(mailOptions, function(err) {
          done(err, 'done');
        });
413
      } */
Rosanny Sihombing's avatar
Rosanny Sihombing committed
414
415
416
417
418
    ], function(err) {
      if (err) {
        req.flash('error', 'An error occured. Please try again.');
      }
      else {
419
        req.flash('success', 'If your email is registered, an e-mail has been sent to ' + emailAddress + ' with further instructions.');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
420
      }
421
      res.redirect('/account/forgotPwd');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
422
423
424
425
    });
  });

  app.get('/reset/:token', function(req, res) {
426
    methods.getUserByToken(req.params.token, function(err, user){
Rosanny Sihombing's avatar
Rosanny Sihombing committed
427
428
      if (!user) {
        req.flash('error', 'Password reset token is invalid or has expired.');
429
        res.redirect('/account/forgotPwd');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
430
431
432
433
434
435
436
437
      }
      else {
        res.render('reset');
      }
    });
  });

  app.post('/reset/:token', function(req, res) {
Wolfgang Knopki's avatar
Wolfgang Knopki committed
438
    var newPwd = req.body.inputNewPwd  
439
    methods.getUserByToken(req.params.token, function(err, user){
Rosanny Sihombing's avatar
Rosanny Sihombing committed
440
      if (user) {
441
        // encrypt password
Rosanny Sihombing's avatar
Rosanny Sihombing committed
442
        bcrypt.genSalt(saltRounds, function(err, salt) {
Wolfgang Knopki's avatar
Wolfgang Knopki committed
443
          bcrypt.hash(newPwd, salt, function(err, hash) {
444
445
446
447
448
449
            var credentialData = {
              password: hash,
              user_id: user.user_id
            }
            // update password
            methods.updateCredential(credentialData, function(err){
Rosanny Sihombing's avatar
Rosanny Sihombing committed
450
451
452
453
454
455
              if (err) {
                req.flash('error', "Database error: Password cannot be modified.")
                throw err
              }
              else {
                req.flash('success', "Your pasword has been updated.")
456
457
458
459
460
461
462
463
464
465
                // send notifiaction email
                mailOptions.to = user.email
                mailOptions.subject = updatePasswordMailSubject
                mailOptions.text = updatePasswordMailContent
                smtpTransport.sendMail(mailOptions, function(err) {
                  if (err) {
                    console.log(err)
                  }
                });
                // redirect to login page
466
                res.redirect('/account/login')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
467
468
469
470
471
472
473
              }
            })
          });
        });
      }
      else {
        req.flash('error', "User not found.")
474
        res.redirect('/account/login')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
475
476
477
478
479
      }
    });
   
  });

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
  // todo: user registration with captcha
  app.get('/registration', function(req, res) {
    res.render('registration')
  })

  app.post('/registration', function(req, res) {
    // TODO:
    // create gitlab account?
    // send email to activate profile?

    // user data
    var curDate = new Date()
    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,
      createdDate: curDate.toISOString().slice(0,10)
Rosanny Sihombing's avatar
Rosanny Sihombing committed
501
    }
502
503
504
505
506
507
508
509
510
511
512
    // encrypt password
    bcrypt.genSalt(saltRounds, function(err, salt) {
      bcrypt.hash(req.body.inputPassword, salt, function(err, hash) {
        // create account
        var newAccount = {
          profile: userData,
          password: hash
        }
        methods.registerNewUser(newAccount, function(err){
          if (err) {
            req.flash('error', "Failed");
Rosanny Sihombing's avatar
Rosanny Sihombing committed
513
          }
514
515
516
          else {
            req.flash('success', 'Your account has been created. Please log in.');
          }
517
          res.redirect('/account/registration');
518
519
        })
      });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
520
    });
521
  })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
522

523
  
524
525
526
527
528
529
530
531
532
533
534
535
  app.get('/email/:email', function(req, res) {
    methods.checkUserEmail(req.params.email, function(err, user){
      if (!err) {
        if (user) {
          res.send(false)
        }
        else {
          res.send(true)
        }  
      }
    })
  })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
536

537
};