routes-account.js 30.6 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')
13
const superagent = require('superagent')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
14

15
module.exports = function (app, config, passport, i18n) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
16
17
18
19
20
21
22
23
24
25

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

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

Varun Srivastava's avatar
Varun Srivastava committed
26
27
28
29
  const mailSignature = 'Mit den besten Grüßen,<br/>das Transferportal-Team der HFT Stuttgart<br/><br/>' +
    'Transferportal der Hochschule für Technik Stuttgart<br/>' +
    'Schellingstr. 24   70174 Stuttgart<br/>' +
    'm4lab@hft-stuttgart.de<br/>' +
Rosanny Sihombing's avatar
Rosanny Sihombing committed
30
    '<a href="https://transfer.hft-stuttgart.de">https://transfer.hft-stuttgart.de</a><br/>' +
31
32
33
34
35
    '<a href="http://www.hft-stuttgart.de/Aktuell/"><img border="0" alt="HFT" src="https://m4lab.hft-stuttgart.de/img/signature/hft_logo.png" width="30" height="30"></a>  &nbsp;' +
    '<a href="http://www.facebook.com/hftstuttgart"><img border="0" alt="Facebook" src="https://m4lab.hft-stuttgart.de/img/signature/fb_bw.png" width="30" height="30"></a>  &nbsp;' +
    '<a href="https://www.instagram.com/hft_stuttgart/"><img border="0" alt="Instagram" src="https://m4lab.hft-stuttgart.de/img/signature/instagram_bw.png" width="30" height="30"></a>  &nbsp;' +
    '<a href="https://twitter.com/hft_presse"><img border="0" alt="Twitter" src="https://m4lab.hft-stuttgart.de/img/signature/twitter_bw.png" width="30" height="30"></a>  &nbsp;' +
    '<a href="https://www.youtube.com/channel/UCi0_JfF2qMZbOhOnNH5PyHA"><img border="0" alt="Youtube" src="https://m4lab.hft-stuttgart.de/img/signature/youtube_bw.png" width="30" height="30"></a>  &nbsp;' +
Varun Srivastava's avatar
Varun Srivastava committed
36
    '<a href="http://www.hft-stuttgart.de/Aktuell/Presse-Marketing/SocialMedia/Snapcode HFT_Stuttgart.jpg/photo_view">' +
37
38
    '<img border="0" alt="Snapchat" src="https://m4lab.hft-stuttgart.de/img/signature/snapchat_bw.png" width="30" height="30"></a>' +
    '<br/><img border="0" src="https://m4lab.hft-stuttgart.de/img/signature/inno_bw.png" width="150" height="100">'
Varun Srivastava's avatar
Varun Srivastava committed
39

Rosanny Sihombing's avatar
Rosanny Sihombing committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  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
59
60
61
62
63
64
65
66
  },
  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
67
    });
68
  });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
69
70
  
  passport.use(samlStrategy);
71
72
73
74
75

  // ============= SAML ==============
  app.post(config.passport.saml.path,
    passport.authenticate(config.passport.strategy,
      {
76
        failureRedirect: '/account/',
77
78
79
        failureFlash: true
      }),
    function (req, res) {
80
      res.redirect('/account/');
81
82
83
84
    }
  );

  // to generate Service Provider's XML metadata
85
  app.get('/saml/metadata',
86
87
88
89
90
91
    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
92
93
94
95
96
97
98

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

Wolfgang Knopki's avatar
Wolfgang Knopki committed
100
  var lang = 'DE'
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
101

Wolfgang Knopki's avatar
Wolfgang Knopki committed
102
  // ======== APP ROUTES - ACCOUNT ====================
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
103
  var updatePasswordMailSubject = "Ihr Passwort für das Transferportal wurde gespeichert."
Varun Srivastava's avatar
Varun Srivastava committed
104
105
106
107
108
109
110
  // 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 = '<div>Lieber Nutzer,<br/><br/>Ihr Passwort wurde erfolgreich geändert.<br/><br/>' + mailSignature + '</div>';
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
111

Rosanny Sihombing's avatar
Rosanny Sihombing committed
112
  app.get('/', function (req, res) {
113
114
115
    if (req.isAuthenticated()) {
      methods.getUserByEmail(req.user.email, function(data, err){
        if (!err) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
116
          res.render(lang+'/account/home', {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
117
            user: data
118
119
120
121
          });
        }
      })
    } else {
122
123
      res.redirect('/login'); // localhost
    }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
124
125
  });

Rosanny Sihombing's avatar
Rosanny Sihombing committed
126
127
128
  app.get('/login',
    passport.authenticate(config.passport.strategy,
      {
129
        successRedirect: '/',
130
        failureRedirect: '/login'
Rosanny Sihombing's avatar
Rosanny Sihombing committed
131
132
133
      })
  );

134
135
  app.get('/logout', function (req, res) {
    if (req.user == null) {
136
      return res.redirect('/');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
137
    }
Wolfgang Knopki's avatar
Wolfgang Knopki committed
138

139
140
141
142
    req.user.nameID = req.user.id;
    req.user.nameIDFormat = req.user.idFormat;
    return samlStrategy.logout(req, function(err, uri) {
      req.logout();
143

144
145
146
147
148
149
150
      if ( req.session ) {
        req.session.destroy((err) => {
          if(err) {
              return console.log(err);
          }
        });
      }
151

152
153
154
      return res.redirect(uri);
    });
  });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
155
156

  app.get('/profile', function (req, res) {
157
158
159
    if (req.isAuthenticated()) {
      methods.getUserByEmail(req.user.email, function(data, err){
        if (!err) {
160
161
162
163
164
165
166
167
168
169
170
171
          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
            });
          }
172
173
        }
      })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
174
    } else {
175
      res.redirect('/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
176
177
178
179
180
    }
  });

  app.get('/services', function (req, res) {
    if (req.isAuthenticated()) {
181
182
183
      methods.getUserByEmail(req.user.email, function(data, err){
        if (!err) {
          if (data.verificationStatus == 1) {
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
            // start =============== RS: MLAB-183
            let userId = data.id
            methods.getGitlabId(userId, function(data, err){
              if (!err) {
                if (data) {
                  console.log("TODO: GitLab is already activated for this user. Allow project creation.")
                }
                else {
                  superagent.get('https://transfer.hft-stuttgart.de/gitlab/api/v4/users?private_token='+config.gitlab.token_readWriteProjects+'&search='+req.user.email)
                  .then(res => {
                    if (res.body.length > 0) {
                      let gitlabActivationData = {
                        user_id: userId,
                        gitlab_userId: res.body[0].id
                      }
                      methods.addGitlabUser(gitlabActivationData, function(err){})
                    }
                    else {
                      console.log('TODO: Show gitlab activation button: transfer.hft-stuttgart.de/gitlab')
                    }
                  })
                  .catch(err => {
                      console.log(err.message)
                  });
                }
              }
            })
            // end =============== RS: MLAB-183
212
213
214
215
            res.render(lang+'/account/services', {
              user: data
            });
            /* !!! DO NOT DELETE. TEMPORARILY DISABLED FOR FUTURE USE. !!!
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
            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
                });
              }
            ])
273
            */
Rosanny Sihombing's avatar
Rosanny Sihombing committed
274
          }
275
276
277
          else {
            res.render(lang+'/account/home', {
              user: data
Rosanny Sihombing's avatar
Rosanny Sihombing committed
278
279
280
            });
          }
        }
281
      })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
282
    } else {
283
      res.redirect('/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
284
285
286
287
288
    }
  });

  app.get('/security', function (req, res) {
    if (req.isAuthenticated()) {
289
290
      methods.getUserByEmail(req.user.email, function(data, err){
        if (!err) {
291
          if (data.verificationStatus == 1 && data.m4lab_idp == 1) {
292
293
294
295
296
297
298
299
300
301
302
            res.render(lang+'/account/security', {
              user: data
            })
          }
          else {
            res.render(lang+'/account/home', {
              user: data
            });
          }
        }        
      })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
303
    } else {
304
      res.redirect('/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
305
306
307
308
309
    }
  });

  app.post('/updateProfile', function (req, res) {
    var userData = {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
310
      salutation: req.body.inputSalutation,
Rosanny Sihombing's avatar
Rosanny Sihombing committed
311
312
313
314
315
316
317
318
      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,
    }
319

Rosanny Sihombing's avatar
Rosanny Sihombing committed
320
321
    if (req.isAuthenticated()) {
      if (userData.email) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
322
        dbconn.user.query('UPDATE user SET ? WHERE email = "' +userData.email+'"', userData, function (err, rows, fields) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
323
324
325
326
327
            //if (err) throw err;
            if (err) {
              req.flash('error', "Failed");
            }
            else {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
328
329
              //req.flash('success', 'Profile updated!');
              req.flash('success', 'Ihr Benutzerprofil wurde aktualisiert!');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
330
            }
Wolfgang Knopki's avatar
Wolfgang Knopki committed
331
            res.redirect('/account/profile');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
332
333
334
        })
      }
    } else {
335
      res.redirect('/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
336
337
    }
  });
338

Rosanny Sihombing's avatar
Rosanny Sihombing committed
339
340
341
342
343
344
  app.post('/changePwd', function (req, res) {
    if (req.isAuthenticated()) {
      var currPwd = req.body.inputCurrPwd
      var newPwd = req.body.inputNewPwd
      var retypePwd = req.body.inputConfirm

345
346
347
348
349
      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
350
              console.error(err)
Rosanny Sihombing's avatar
Rosanny Sihombing committed
351
352
353
              res.status(500).render(lang+'/500', {
                error: err
              })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
354
            }
355
356
357
358
359
            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
360
                console.error(err)
Rosanny Sihombing's avatar
Rosanny Sihombing committed
361
362
363
                res.status(500).render(lang+'/500', {
                  error: err
                })
364
365
              }
              else if (!isMatch) {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
366
367
                //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.")
368
                //res.redirect('/security')
Wolfgang Knopki's avatar
Wolfgang Knopki committed
369
                res.redirect('/account/security')
370
371
372
              }
              else {
                if ( newPwd != retypePwd ) {
373
374
                  //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
375
                  res.redirect('/account/security')
376
377
378
379
380
381
382
383
384
385
386
                }
                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
387
388
                          //req.flash('error', "Database error: Password cannot be modified.")
                          req.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.")
389
390
391
                          throw err
                        }
                        else {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
392
393
                          //req.flash('success', "Pasword updated!")
                          req.flash('success', "Passwort aktualisiert!")
394
                          mailer.options.to = req.user.email
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
395
                          //mailOptions.subject = "Your M4_LAB Password has been updated."
396
                          mailer.options.subject = updatePasswordMailSubject
Varun Srivastava's avatar
Varun Srivastava committed
397
                          mailer.options.html = updatePasswordMailContent
398
                          mailer.transport.sendMail(mailer.options, function(err) {
399
400
401
402
                            if (err) {
                              console.log(err)
                            }
                          });
403
                        }
Wolfgang Knopki's avatar
Wolfgang Knopki committed
404
                        res.redirect('/account/security')
405
406
407
408
409
                      })
                    });
                  });
                }
              }
410
          })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
411
        })
412
        }
413
      })
414
415
    }
    else {
416
      res.redirect('/login');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
417
418
419
420
    }
  });

  app.get('/forgotPwd', function (req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
421
    res.render(lang+'/account/forgotPwd', {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
422
423
424
425
426
427
      user: req.user
    });
  });

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

Rosanny Sihombing's avatar
Rosanny Sihombing committed
429
    var emailAddress = req.body.inputEmail;
430
  /*  var emailContent = "Hi there,\n\n"+
Rosanny Sihombing's avatar
Rosanny Sihombing committed
431
432
      "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";
433
    var emailSubject = "Account Access Attempted"; */
434

Rosanny Sihombing's avatar
Rosanny Sihombing committed
435
436
437
438
439
440
441
442
443
444
445
    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
446
447
448
            //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
449
              "we've received a request to reset your password. If you didn't make the request, just ignore this email.\n\n"+
450
              "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
451
              "This password reset is only valid for 1 hour.\n\n"+
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
452
              "Thanks,\nM4_LAB Team" */
Varun Srivastava's avatar
Varun Srivastava committed
453
454
455
456
457
458
459
460
461
462
463
            // 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"+
            //   "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
            //   "Dieser Link ist aus Sicherheitsgründen nur für 1 Stunde gültig.\n\n"+mailSignature

            var emailContent = '<div>Lieber Nutzer, Varun<br/><br/>' +
              '<p>wir haben Ihre Anfrage zur Erneuerung Ihres Passwortes erhalten. Falls Sie diese Anfrage nicht gesendet haben, ignorieren Sie bitte diese E-Mail.<br/><br/>' +
              'Sie können Ihr Passwort mit dem Klick auf diesen Link ändern: http://m4lab.hft-stuttgart.de/account/reset/' + token + '<br/>' + // test server
              'Dieser Link ist aus Sicherheitsgründen nur für 1 Stunde gültig.<br/></p>' + mailSignature + '</div>';
            
464
465
466
467
468
469
            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
470
471
              done(err, token, user);
            });
472
473

            // send email
474
475
            mailer.options.to = emailAddress;
            mailer.options.subject = emailSubject;
Varun Srivastava's avatar
Varun Srivastava committed
476
            mailer.options.html = emailContent;
477
            mailer.transport.sendMail(mailer.options, function(err) {
478
479
              done(err, 'done');
            });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
480
481
          }
          else {
482
483
            //done(err, null, null);
            done(err, 'no user found');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
484
485
486
487
488
          }
        });
      }
    ], function(err) {
      if (err) {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
489
490
        //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
491
492
      }
      else {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
493
494
        //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
495
      }
496
      //res.redirect('/forgotPwd'); // deployment
Wolfgang Knopki's avatar
Wolfgang Knopki committed
497
      res.redirect('/account/forgotPwd'); // localhost
Rosanny Sihombing's avatar
Rosanny Sihombing committed
498
499
500
501
    });
  });

  app.get('/reset/:token', function(req, res) {
502
    methods.getUserByToken(req.params.token, function(err, user){
Rosanny Sihombing's avatar
Rosanny Sihombing committed
503
      if (!user) {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
504
505
        //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.');
506
        //res.redirect('/forgotPwd'); // deployment
Wolfgang Knopki's avatar
Wolfgang Knopki committed
507
        res.redirect('/account/forgotPwd'); // deployment
Rosanny Sihombing's avatar
Rosanny Sihombing committed
508
509
      }
      else {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
510
        res.render(lang+'/account/reset');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
511
512
513
514
515
      }
    });
  });

  app.post('/reset/:token', function(req, res) {
516
    var newPwd = req.body.inputNewPwd
517
    methods.getUserByToken(req.params.token, function(err, user){
Rosanny Sihombing's avatar
Rosanny Sihombing committed
518
      if (user) {
519
        // encrypt password
Rosanny Sihombing's avatar
Rosanny Sihombing committed
520
        bcrypt.genSalt(saltRounds, function(err, salt) {
Wolfgang Knopki's avatar
Wolfgang Knopki committed
521
          bcrypt.hash(newPwd, salt, function(err, hash) {
522
523
524
525
526
527
            var credentialData = {
              password: hash,
              user_id: user.user_id
            }
            // update password
            methods.updateCredential(credentialData, function(err){
Rosanny Sihombing's avatar
Rosanny Sihombing committed
528
              if (err) {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
529
530
                //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
531
532
533
                throw err
              }
              else {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
534
535
                //req.flash('success', "Your pasword has been updated.")
                req.flash('success', "Passwort aktualisiert!")
536
                // send notifiaction email
537
538
                mailer.options.to = user.email
                mailer.options.subject = updatePasswordMailSubject
Varun Srivastava's avatar
Varun Srivastava committed
539
                mailer.options.html = updatePasswordMailContent
540
                mailer.transport.sendMail(mailer.options, function(err) {
541
542
543
544
545
                  if (err) {
                    console.log(err)
                  }
                });
                // redirect to login page
546
                res.redirect('/login')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
547
548
549
550
551
552
553
              }
            })
          });
        });
      }
      else {
        req.flash('error', "User not found.")
554
        res.redirect('/login')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
555
556
      }
    });
557

Rosanny Sihombing's avatar
Rosanny Sihombing committed
558
559
  });

560
  // ============= NEW USERS REGISTRATION ===========================
561
  app.get('/registration', function(req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
562
    res.render(lang+'/account/registration')
563
564
565
566
567
  })
  app.post('/registration', function(req, res) {
    // user data
    var curDate = new Date()
    var userData = {
Rosanny Sihombing's avatar
DE    
Rosanny Sihombing committed
568
      salutation: req.body.inputSalutation,
569
570
571
572
573
574
575
576
      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
577
    }
578

579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
    var userEmail = userData.email
    var pos = userEmail.indexOf('@')
    var emailLength = userEmail.length
    var emailDomain = userEmail.slice(pos, emailLength);

    if ( emailDomain.toLowerCase() == "@hft-stuttgart.de") {
        req.flash('error', "Fehlgeschlagen: HFT-Account")
        res.redirect('/account/registration');
    }
    else {
      let token
      async.waterfall([
        function(done) {
          crypto.randomBytes(20, function(err, buf) {
            token = buf.toString('hex');
            done(err, token);
595
          });
596
597
598
599
600
601
602
603
604
        },
        // 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
605
              }
606
607
608
609
610
611
612
613
614
615
616
617
618
              done(err, newAccount)
            });
          });
        },
        // save data
        function(newAccount, err) {
          methods.registerNewUser(newAccount, function(err){
            if (err) {
              req.flash('error', "Fehlgeschlagen")
            }
            else {
              // send email
              var emailSubject = "Bitte bestätigen Sie Ihr M4_LAB Benutzerkonto"
Varun Srivastava's avatar
Varun Srivastava committed
619
620
621
622
623
624
625
626
627
628
629
              // var emailContent = "Lieber Nutzer,\n\n"+
              //     "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
              var emailContent = '<div>Lieber Nutzer,<br/><br/>' +
                '<p>vielen Dank für Ihre Anmeldung am Transferportal der HFT Stuttgart. <br/>' +
                'Um Ihre Anmeldung zu bestätigen, klicken Sie bitte diesen Link: ' + config.app.host + '/verifyAccount?token=' + token +
                '<br/><br/>' +
                'Ohne Bestätigung Ihres Kontos müssen wir Ihr Konto leider nach 7 Tagen löschen.</p><br/>' + mailSignature +
                '</div>';
630
631
              mailer.options.to = req.body.inputEmail;
              mailer.options.subject = emailSubject;
Varun Srivastava's avatar
Varun Srivastava committed
632
              mailer.options.html = emailContent;
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
              mailer.transport.sendMail(mailer.options, function(err) {
                if (err) {
                  console.log('cannot send email')
                  throw err
                }
              })
              // user feedback
              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.')
            }
            res.redirect('/account/registration')
          })
        }
      ])
    }
649
650
651
652
  })

  // ============= USER VERIFICATION ================================
  app.get("/verifyAccount", function(req, res){
653
    console.log(req.query)
654
655
656
657
658
659
660
661
662
663
664
665
666
667
    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 {
668
669
670
671
672
673
674
675
            // 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"
Varun Srivastava's avatar
Varun Srivastava committed
676
677
678
679
680
681
                // 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
                var emailContent = '<div>Lieber Nutzer,<br/><br/>' +
                  '<p>herzlich willkommen beim Transferportal der HFT Stuttgart!<br/>' +
                  'Sie können nun alle Dienste des Portals nutzen.<p/><br/>' + mailSignature;
682
683
                mailer.options.to = data.email;
                mailer.options.subject = emailSubject;
Varun Srivastava's avatar
Varun Srivastava committed
684
                mailer.options.html = emailContent;
685
686
687
688
689
690
691
692
693
                mailer.transport.sendMail(mailer.options, function(err) {
                  if (err) {
                    console.log('cannot send email')
                    throw err
                  }
                })
              }
            })

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
            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"
Varun Srivastava's avatar
Varun Srivastava committed
719
720
721
722
723
724
725
726
727
728
                // 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
                var emailContent = '<div>Lieber Nutzer,<br/><br/>' +
                  '<p>vielen Dank für Ihre Anmeldung am Transferportal der HFT Stuttgart. <br/>' +
                  'Um Ihre Anmeldung zu bestätigen, klicken Sie bitte diesen Link: ' + config.app.host + '/verifyAccount?token=' + token +
                  '<br/><br/>' +
                  'Ohne Bestätigung Ihres Kontos müssen wir Ihr Konto leider nach 7 Tagen löschen.</p><br/>' + mailSignature +
                  '</div>';
729
730
                mailer.options.to = emailAddress;
                mailer.options.subject = emailSubject;
Varun Srivastava's avatar
Varun Srivastava committed
731
                mailer.options.html = emailContent;
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
                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)
            }
          })
        }
      })
    }
751
  })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
752

753
754
755
756
757
758
759
760
761
762
763
764
  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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801

  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
      });
    });
802
};