routes-account.js 25.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
const async = require('async')
const crypto = require('crypto')
12
const mailer = require('./mailer')
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,
      {
61
        failureRedirect: '/account/',
62
63
64
        failureFlash: true
      }),
    function (req, res) {
65
      res.redirect('/account/');
66
67
68
69
    }
  );

  // to generate Service Provider's XML metadata
70
  app.get('/saml/metadata',
71
72
73
74
75
76
    function(req, res) {
      res.type('application/xml');
      var spMetadata = samlStrategy.generateServiceProviderMetadata(fs.readFileSync(__dirname + '/cert/cert.pem', 'utf8'));
      res.status(200).send(spMetadata);
    }
  );
Wolfgang Knopki's avatar
Wolfgang Knopki committed
77
78
79
80
81
82
83

  // ================ test i18n ==================
  i18n.setLocale('de');
  app.get('/de', function(req, res) {
    var greeting = i18n.__('Hello World')
    res.send(greeting)
  });
84

Wolfgang Knopki's avatar
Wolfgang Knopki committed
85
  var lang = 'DE'
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
86

Wolfgang Knopki's avatar
Wolfgang Knopki committed
87
  // ======== APP ROUTES - ACCOUNT ====================
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
88
89
90
91
92
93
94
95
96
  var updatePasswordMailSubject = "Ihr Passwort für das Transferportal wurde gespeichert."
  var mailSignature = "Mit den besten Grüßen,\ndas Transferportal-Team der HFT Stuttgart\n\n"+
    "Transferportal der Hochschule für Technik Stuttgart\n"+
    "Schellingstr. 24\n"+
    "70174 Stuttgart\n"+
    "m4lab@hft-stuttgart.de\n"+
    "https://transfer.hft-stuttgart.de"
  var updatePasswordMailContent = "Lieber Nutzer,\n\n"+"Ihr Passwort wurde erfolgreich geändert.\n\n"+mailSignature

Rosanny Sihombing's avatar
Rosanny Sihombing committed
97
  app.get('/', function (req, res) {
98
99
100
    if (req.isAuthenticated()) {
      methods.getUserByEmail(req.user.email, function(data, err){
        if (!err) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
101
          res.render(lang+'/account/home', {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
102
            user: data
103
104
105
106
          });
        }
      })
    } else {
107
108
      res.redirect('/login'); // localhost
    }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
109
110
  });

Rosanny Sihombing's avatar
Rosanny Sihombing committed
111
112
113
  app.get('/login',
    passport.authenticate(config.passport.strategy,
      {
114
        successRedirect: '/',
115
        failureRedirect: '/login'
Rosanny Sihombing's avatar
Rosanny Sihombing committed
116
117
118
      })
  );

119
120
  app.get('/logout', function (req, res) {
    if (req.user == null) {
121
      return res.redirect('/');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
122
    }
Wolfgang Knopki's avatar
Wolfgang Knopki committed
123

124
125
126
127
    req.user.nameID = req.user.id;
    req.user.nameIDFormat = req.user.idFormat;
    return samlStrategy.logout(req, function(err, uri) {
      req.logout();
128

129
130
131
132
133
134
135
      if ( req.session ) {
        req.session.destroy((err) => {
          if(err) {
              return console.log(err);
          }
        });
      }
136

137
138
139
      return res.redirect(uri);
    });
  });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
140
141

  app.get('/profile', function (req, res) {
142
143
144
    if (req.isAuthenticated()) {
      methods.getUserByEmail(req.user.email, function(data, err){
        if (!err) {
145
146
147
148
149
150
151
152
153
154
155
156
          if (data.verificationStatus == 1) {
            console.log(data)
            res.render(lang+'/account/profile', {
              user: data,
              email: req.user.email
            })
          }
          else {
            res.render(lang+'/account/home', {
              user: data
            });
          }
157
158
        }
      })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
159
    } else {
160
      res.redirect('/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
161
162
163
164
165
    }
  });

  app.get('/services', function (req, res) {
    if (req.isAuthenticated()) {
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
      methods.getUserByEmail(req.user.email, function(data, err){
        if (!err) {
          if (data.verificationStatus == 1) {
            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 = false
                  if (userProjectId.indexOf(projectsOverview[i].id) > -1) {
                    status = true
                  }
                  // 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(lang+'/account/services', {
                  user: data,
                  project: allProjects
                });
              }
            ])
Rosanny Sihombing's avatar
Rosanny Sihombing committed
226
          }
227
228
229
          else {
            res.render(lang+'/account/home', {
              user: data
Rosanny Sihombing's avatar
Rosanny Sihombing committed
230
231
232
            });
          }
        }
233
      })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
234
    } else {
235
      res.redirect('/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
236
237
238
239
240
    }
  });

  app.get('/security', function (req, res) {
    if (req.isAuthenticated()) {
241
242
      methods.getUserByEmail(req.user.email, function(data, err){
        if (!err) {
243
          if (data.verificationStatus == 1 && data.m4lab_idp == 1) {
244
245
246
247
248
249
250
251
252
253
254
            res.render(lang+'/account/security', {
              user: data
            })
          }
          else {
            res.render(lang+'/account/home', {
              user: data
            });
          }
        }        
      })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
255
    } else {
256
      res.redirect('/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
257
258
259
260
261
    }
  });

  app.post('/updateProfile', function (req, res) {
    var userData = {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
262
      salutation: req.body.inputSalutation,
Rosanny Sihombing's avatar
Rosanny Sihombing committed
263
264
265
266
267
268
269
270
      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,
    }
271

Rosanny Sihombing's avatar
Rosanny Sihombing committed
272
273
    if (req.isAuthenticated()) {
      if (userData.email) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
274
        dbconn.user.query('UPDATE user SET ? WHERE email = "' +userData.email+'"', userData, function (err, rows, fields) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
275
276
277
278
279
            //if (err) throw err;
            if (err) {
              req.flash('error', "Failed");
            }
            else {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
280
281
              //req.flash('success', 'Profile updated!');
              req.flash('success', 'Ihr Benutzerprofil wurde aktualisiert!');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
282
            }
Wolfgang Knopki's avatar
Wolfgang Knopki committed
283
            res.redirect('/account/profile');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
284
285
286
        })
      }
    } else {
287
      res.redirect('/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
288
289
    }
  });
290

Rosanny Sihombing's avatar
Rosanny Sihombing committed
291
292
293
294
295
296
  app.post('/changePwd', function (req, res) {
    if (req.isAuthenticated()) {
      var currPwd = req.body.inputCurrPwd
      var newPwd = req.body.inputNewPwd
      var retypePwd = req.body.inputConfirm

297
298
299
300
301
      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) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
302
              console.error(err)
Rosanny Sihombing's avatar
Rosanny Sihombing committed
303
304
305
              res.status(500).render(lang+'/500', {
                error: err
              })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
306
            }
307
308
309
310
311
            var userPwd = rows[0].password

            // check if the password is correct
            bcrypt.compare(currPwd, userPwd, function(err, isMatch) {
              if (err) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
312
                console.error(err)
Rosanny Sihombing's avatar
Rosanny Sihombing committed
313
314
315
                res.status(500).render(lang+'/500', {
                  error: err
                })
316
317
              }
              else if (!isMatch) {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
318
319
                //req.flash('error', "Sorry, your password was incorrect. Please double-check your password.")
                req.flash('error', "Das Passwort ist leider falsch. Bitte überprüfen Sie Ihre Eingabe.")
320
                //res.redirect('/security')
Wolfgang Knopki's avatar
Wolfgang Knopki committed
321
                res.redirect('/account/security')
322
323
324
              }
              else {
                if ( newPwd != retypePwd ) {
325
326
                  //req.flash('error', "Passwords do no match. Please make sure you re-type your new password correctly.")
                  req.flash('error', 'Passwörter stimmen nicht überein. Bitte stellen Sie sicher, dass Sie das Passwort beide Male genau gleich eingeben.')
Wolfgang Knopki's avatar
Wolfgang Knopki committed
327
                  res.redirect('/account/security')
328
329
330
331
332
333
334
335
336
337
338
                }
                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) {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
339
340
                          //req.flash('error', "Database error: Password cannot be modified.")
                          req.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.")
341
342
343
                          throw err
                        }
                        else {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
344
345
                          //req.flash('success', "Pasword updated!")
                          req.flash('success', "Passwort aktualisiert!")
346
                          mailer.options.to = req.user.email
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
347
                          //mailOptions.subject = "Your M4_LAB Password has been updated."
348
349
350
                          mailer.options.subject = updatePasswordMailSubject
                          mailer.options.text = updatePasswordMailContent
                          mailer.transport.sendMail(mailer.options, function(err) {
351
352
353
354
                            if (err) {
                              console.log(err)
                            }
                          });
355
                        }
Wolfgang Knopki's avatar
Wolfgang Knopki committed
356
                        res.redirect('/account/security')
357
358
359
360
361
                      })
                    });
                  });
                }
              }
362
          })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
363
        })
364
        }
365
      })
366
367
    }
    else {
368
      res.redirect('/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
369
370
371
372
    }
  });

  app.get('/forgotPwd', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
373
    res.render(lang+'/account/forgotPwd', {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
374
375
376
377
378
379
      user: req.user
    });
  });

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

Rosanny Sihombing's avatar
Rosanny Sihombing committed
381
    var emailAddress = req.body.inputEmail;
382
  /*  var emailContent = "Hi there,\n\n"+
Rosanny Sihombing's avatar
Rosanny Sihombing committed
383
384
      "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";
385
    var emailSubject = "Account Access Attempted"; */
386

Rosanny Sihombing's avatar
Rosanny Sihombing committed
387
388
389
390
391
392
393
394
395
396
397
    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");
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
398
399
400
            //var emailSubject = "M4_LAB Password Reset";
            var emailSubject = "Ihre Passwort-Anfrage an das Transferportal der HFT Stuttgart";
            /* var emailContent = "Hi User,\n\n"+
Rosanny Sihombing's avatar
Rosanny Sihombing committed
401
              "we've received a request to reset your password. If you didn't make the request, just ignore this email.\n\n"+
402
              "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
403
              "This password reset is only valid for 1 hour.\n\n"+
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
404
405
406
              "Thanks,\nM4_LAB Team" */
            var emailContent = "Lieber Nutzer,\n\n"+
              "wir haben Ihre Anfrage zur Erneuerung Ihres Passwortes erhalten. Falls Sie diese Anfrage nicht gesendet haben, ignorieren Sie bitte diese E-Mail.\n\n"+
Wolfgang Knopki's avatar
Wolfgang Knopki committed
407
408
              "Sie können Ihr Passwort mit dem Klick auf diesen Link ändern: http://m4lab.hft-stuttgart.de/account/reset/" + token + "\n" + // test server
              //"Sie können Ihr Passwort mit dem Klick auf diesen Link ändern: http://localhost:9989/reset/" + token + "\n" + // localhost
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
409
410
              "Dieser Link ist aus Sicherheitsgründen nur für 1 Stunde gültig.\n\n"+mailSignature

411
412
413
414
415
416
            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
417
418
              done(err, token, user);
            });
419
420

            // send email
421
422
423
424
            mailer.options.to = emailAddress;
            mailer.options.subject = emailSubject;
            mailer.options.text = emailContent;
            mailer.transport.sendMail(mailer.options, function(err) {
425
426
              done(err, 'done');
            });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
427
428
          }
          else {
429
430
            //done(err, null, null);
            done(err, 'no user found');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
431
432
433
434
435
          }
        });
      }
    ], function(err) {
      if (err) {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
436
437
        //req.flash('error', 'An error occured. Please try again.');
        req.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
438
439
      }
      else {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
440
441
        //req.flash('success', 'If your email is registered, an e-mail has been sent to ' + emailAddress + ' with further instructions.');
        req.flash('success', 'Wenn Ihre E-Mail-Adresse registriert ist, wurde eine E-Mail mit dem weiteren Vorgehen an ' + emailAddress + ' versendet.');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
442
      }
443
      //res.redirect('/forgotPwd'); // deployment
Wolfgang Knopki's avatar
Wolfgang Knopki committed
444
      res.redirect('/account/forgotPwd'); // localhost
Rosanny Sihombing's avatar
Rosanny Sihombing committed
445
446
447
448
    });
  });

  app.get('/reset/:token', function(req, res) {
449
    methods.getUserByToken(req.params.token, function(err, user){
Rosanny Sihombing's avatar
Rosanny Sihombing committed
450
      if (!user) {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
451
452
        //req.flash('error', 'Password reset token is invalid or has expired.');
        req.flash('error', 'Der Schlüssel zum zurücksetzen des Passworts ist ungültig oder abgelaufen.');
453
        //res.redirect('/forgotPwd'); // deployment
Wolfgang Knopki's avatar
Wolfgang Knopki committed
454
        res.redirect('/account/forgotPwd'); // deployment
Rosanny Sihombing's avatar
Rosanny Sihombing committed
455
456
      }
      else {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
457
        res.render(lang+'/account/reset');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
458
459
460
461
462
      }
    });
  });

  app.post('/reset/:token', function(req, res) {
463
    var newPwd = req.body.inputNewPwd
464
    methods.getUserByToken(req.params.token, function(err, user){
Rosanny Sihombing's avatar
Rosanny Sihombing committed
465
      if (user) {
466
        // encrypt password
Rosanny Sihombing's avatar
Rosanny Sihombing committed
467
        bcrypt.genSalt(saltRounds, function(err, salt) {
Wolfgang Knopki's avatar
Wolfgang Knopki committed
468
          bcrypt.hash(newPwd, salt, function(err, hash) {
469
470
471
472
473
474
            var credentialData = {
              password: hash,
              user_id: user.user_id
            }
            // update password
            methods.updateCredential(credentialData, function(err){
Rosanny Sihombing's avatar
Rosanny Sihombing committed
475
              if (err) {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
476
477
                //req.flash('error', "Database error: Password cannot be modified.")
                req.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.")
Rosanny Sihombing's avatar
Rosanny Sihombing committed
478
479
480
                throw err
              }
              else {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
481
482
                //req.flash('success', "Your pasword has been updated.")
                req.flash('success', "Passwort aktualisiert!")
483
                // send notifiaction email
484
485
486
487
                mailer.options.to = user.email
                mailer.options.subject = updatePasswordMailSubject
                mailer.options.text = updatePasswordMailContent
                mailer.transport.sendMail(mailer.options, function(err) {
488
489
490
491
492
                  if (err) {
                    console.log(err)
                  }
                });
                // redirect to login page
493
                res.redirect('/login')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
494
495
496
497
498
499
500
              }
            })
          });
        });
      }
      else {
        req.flash('error', "User not found.")
501
        res.redirect('/login')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
502
503
      }
    });
504

Rosanny Sihombing's avatar
Rosanny Sihombing committed
505
506
  });

507
  // ============= NEW USERS REGISTRATION ===========================
508
  app.get('/registration', function(req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
509
    res.render(lang+'/account/registration')
510
511
512
513
514
  })
  app.post('/registration', function(req, res) {
    // user data
    var curDate = new Date()
    var userData = {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
515
      salutation: req.body.inputSalutation,
516
517
518
519
520
521
522
523
      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
524
    }
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548

    let token
    async.waterfall([
      function(done) {
        crypto.randomBytes(20, function(err, buf) {
          token = buf.toString('hex');
          done(err, token);
        });
      },
      // encrypt password
      function(token, done) {
        bcrypt.genSalt(saltRounds, function(err, salt) {
          bcrypt.hash(req.body.inputPassword, salt, function(err, hash) {
            var newAccount = {
              profile: userData,
              password: hash,
              verificationToken: token
            }
            done(err, newAccount)
          });
        });
      },
      // save data
      function(newAccount, err) {
549
550
        methods.registerNewUser(newAccount, function(err){
          if (err) {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
551
            req.flash('error', "Fehlgeschlagen")
Rosanny Sihombing's avatar
Rosanny Sihombing committed
552
          }
553
          else {
554
555
556
            // send email
            var emailSubject = "Bitte bestätigen Sie Ihr M4_LAB Benutzerkonto"
            var emailContent = "Lieber Nutzer,\n\n"+
557
558
559
560
                "vielen Dank für Ihre Anmeldung am Transferportal der HFT Stuttgart.\n"+ 
                "Um Ihre Anmeldung zu bestätigen, klicken Sie bitte diesen Link: "+config.app.host+"/verifyAccount?token="+token+"\n"+
                "Ohne Bestätigung Ihres Kontos müssen wir Ihr Konto leider nach 7 Tagen löschen.\n\n"+
                "Sollten Sie sich selbst nicht mit Ihren Daten am Transferportal registriert haben, ignorieren Sie diese E-Mail bitte.\n\n"+mailSignature
561
562
563
564
565
566
567
568
569
570
571
            
            mailer.options.to = req.body.inputEmail;
            mailer.options.subject = emailSubject;
            mailer.options.text = emailContent;
            mailer.transport.sendMail(mailer.options, function(err) {
              if (err) {
                console.log('cannot send email')
                throw err
              }
            })
            // user feedback
572
573
574
            req.flash('success', 'Vielen Dank für Ihre Registrierung!'+'\r\n\r\n'+
              'Wir haben Ihnen eine E-Mail an Ihre verwendete Adresse gesendet. Diese enthält einen Link zur Bestätigung Ihres Accounts.'+'\r\n'+
              'Wenn Sie die Mail nicht in ihrem Postfach vorfinden, prüfen Sie bitte auch Ihren Spam-Ordner.')
575
          }
576
          res.redirect('/account/registration')
577
        })
578
579
580
581
582
583
      }
    ])
  })

  // ============= USER VERIFICATION ================================
  app.get("/verifyAccount", function(req, res){
584
    console.log(req.query)
585
586
587
588
589
590
591
592
593
594
595
596
597
598
    methods.getUserIdByVerificationToken(req.query.token, function(userId, err){
      if (userId) {
        let userData = {
          id: userId,
          verificationStatus: 1
        }
        methods.verifyUserAccount(userData, function(err){
          if (err) {
            console.log("Error: "+err)
            res.render(lang+'/account/verification', {
              status: false
            });
          }
          else {
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
            // send welcome email after successful account verification
            methods.getUserById(userId, function(data, err){
              if (err) {
                console.log("Error: "+err)
              }
              else {
                // send email
                var emailSubject = "Herzlich willkommen"
                var emailContent = "Lieber Nutzer,\n\n"+
                    "herzlich willkommen beim Transferportal der HFT Stuttgart!\n"+ 
                    "Sie können nun alle Dienste des Portals nutzen.\n\n"+mailSignature
                
                mailer.options.to = data.email;
                mailer.options.subject = emailSubject;
                mailer.options.text = emailContent;
                mailer.transport.sendMail(mailer.options, function(err) {
                  if (err) {
                    console.log('cannot send email')
                    throw err
                  }
                })
              }
            })

623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
            res.render(lang+'/account/verification', {
              status: true
            });
          }
        })
      }
      else {
        res.render(lang+'/account/verification', {
          status: null
        });
      }
    })
  })
  app.get("/resendVerificationEmail", function(req, res){
    if (req.isAuthenticated()) {
      var emailAddress = req.user.email
      
      methods.getUserIdByEmail(req.user.email, function(userId, err) {
        if (!err) {
          // get token
          methods.getVerificationTokenByUserId(userId, function(token, err){
            if (!err) {
              if (token) {
                // send email
                var emailSubject = "Bitte bestätigen Sie Ihr M4_LAB Benutzerkonto"
                var emailContent = "Lieber Nutzer,\n\n"+
                    "vielen Dank für Ihre Anmeldung am Transferportal der HFT Stuttgart. "+ 
                    "\nUm Ihre Anmeldung zu bestätigen, klicken Sie bitte diesen Link: "+config.app.host+"/verifyAccount?token="+token+
                    "\n\nOhne Bestätigung Ihres Kontos müssen wir Ihr Konto leider nach 7 Tagen löschen.\n\n"+mailSignature
                
                mailer.options.to = emailAddress;
                mailer.options.subject = emailSubject;
                mailer.options.text = emailContent;
                mailer.transport.sendMail(mailer.options, function(err) {
                  if (err) {
                    console.log('cannot send email')
                    throw err
                  }
                })
                res.send(true)
              }
              else {
                res.send(false)
              }
            }
            else {
              console.log(err)
            }
          })
        }
      })
    }
675
  })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
676

677
678
679
680
681
682
683
684
685
686
687
688
  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)
        }  
      }
    })
  })
Wolfgang Knopki's avatar
Wolfgang Knopki committed
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725

  app.get('/contact', function (req, res) {
      res.render(lang+'/account/contact', {
        user: req.user
      });
    });

    app.post('/contact', function(req, res, next) {
      //methods.currentDate();
      let emailAddress = req.body.inputEmail;
      let supportAddress = "support-transfer@hft-stuttgart.de";
      let inputName = req.body.name;
      let inputContent = req.body.message;
      let emailContent = "Es wurde eine Anfrage an das Transferportal gestellt: \n\n NAME: " + inputName + "\n NACHRICHT:\n "+ inputContent;
      let emailSubject = "Ihre Anfrage an das Transferportal";
      async.waterfall([
        function(done) {
            // send email
            mailer.options.to = supportAddress;
            mailer.options.cc = emailAddress;
            mailer.options.subject = emailSubject;
            mailer.options.text = emailContent;
            mailer.transport.sendMail(mailer.options, function(err) {
                done(err, 'done');
              });
          }
      ], function(err) {
        if (err) {
          req.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
        }
        else {
          req.flash('success', 'Vielen Dank für Ihre Anfrage. Wir melden uns baldmöglichst bei Ihnen. Eine Kopie Ihrer Anfrage wurde an ' + emailAddress + ' versandt.');
        }
        //res.redirect('/forgotPwd'); // deployment
        res.redirect('/account/contact'); // localhost
      });
    });
726
};