An error occurred while loading the file. Please try again.
-
Rosanny Sihombing authored6447e044
const fs = require('fs')
const SamlStrategy = require('passport-saml').Strategy
const dbconn = require('./dbconn')
const methods = require('./methods')
const gitlab = require('./gitlab')
// pwd encryption
const bcrypt = require('bcryptjs');
const saltRounds = 10;
const salt = 64; // salt length
// forgot pwd
const async = require('async')
const crypto = require('crypto')
const mailer = require('./mailer')
const logoDir = 'public/upload/'
const defaultLogo = 'public/default/logo.png'
const tpGitlabURL = 'https://transfer.hft-stuttgart.de/gitlab/'
const tpGitlabPagesURL = 'https://transfer.hft-stuttgart.de/pages/'
const portalUser = require('../classes/user')
const projectInformation = require('../classes/website')
const projectRepo = require('../classes/repo')
module.exports = function (app, config, passport, i18n) {
// =========== PASSPORT =======
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
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/>' +
'<a href="https://transfer.hft-stuttgart.de">https://transfer.hft-stuttgart.de</a><br/>' +
'<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> ' +
'<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> ' +
'<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> ' +
'<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> ' +
'<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> ' +
'<a href="http://www.hft-stuttgart.de/Aktuell/Presse-Marketing/SocialMedia/Snapcode HFT_Stuttgart.jpg/photo_view">' +
'<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">'
var samlStrategy = new SamlStrategy({
// URL that goes from the Identity Provider -> Service Provider
callbackUrl: config.passport.saml.path,
// Base address to call logout requests
logoutUrl: config.passport.saml.logoutUrl,
entryPoint: config.passport.saml.entryPoint,
issuer: config.passport.saml.issuer,
identifierFormat: null,
// Service Provider private key
decryptionPvk: fs.readFileSync(__dirname + '/cert/key.pem', 'utf8'),
// Service Provider Certificate
privateCert: fs.readFileSync(__dirname + '/cert/key.pem', 'utf8'),
// Identity Provider's public key
cert: fs.readFileSync(__dirname + '/cert/cert_idp.pem', 'utf8'),
validateInResponseTo: false,
disableRequestedAuthnContext: true
},
function (profile, done) {
return done(null, {
id: profile.nameID,
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
idFormat: profile.nameIDFormat,
email: profile.email,
firstName: profile.givenName,
lastName: profile.sn
});
});
passport.use(samlStrategy);
// ============= SAML ==============
app.post(config.passport.saml.path,
passport.authenticate(config.passport.strategy,
{
failureRedirect: '/account/',
failureFlash: true
}),
function (req, res) {
res.redirect('/account/');
}
);
// 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);
}
);
// ================ test i18n ==================
i18n.setLocale('de');
app.get('/de', function(req, res) {
var greeting = i18n.__('Hello World')
res.send(greeting)
});
var lang = 'DE'
// ======== APP ROUTES - ACCOUNT ====================
var updatePasswordMailSubject = "Ihr Passwort für das Transferportal wurde gespeichert."
var updatePasswordMailContent = '<div>Lieber Nutzer,<br/><br/>Ihr Passwort wurde erfolgreich geändert.<br/><br/>' + mailSignature + '</div>';
async function getLoggedInUserData(email) {
let user = await methods.getUserByEmail(email)
let loggedInUser = new portalUser(
user.id, email, user.salutation, user.title, user.firstname, user.lastname, user.industry, user.organisation, user.speciality, user.m4lab_idp, null, user.verificationStatus
)
let userGitlabId = await methods.getGitlabId(loggedInUser.id)
loggedInUser.setGitlabUserId(userGitlabId)
return loggedInUser
}
app.get('/', async function (req, res) {
if ( !req.isAuthenticated() ) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
res.render(lang+'/account/home', {
user: loggedInUser
});
}
});
app.get('/login',
passport.authenticate(config.passport.strategy, {
successRedirect: '/',
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
failureRedirect: '/login'
})
)
app.get('/logout', function (req, res) {
if (req.user == null) {
return res.redirect('/');
}
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);
});
});
app.get('/profile', async function (req, res) {
if ( !req.isAuthenticated() ) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
if(loggedInUser.getVerificationStatus() != 1) {
res.redirect('/account/')
} else {
res.render(lang+'/account/profile', {
user: loggedInUser
})
}
}
})
app.get('/services', async function(req, res){
if( !req.isAuthenticated() ) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
if(loggedInUser.getVerificationStatus() != 1) { // unverified users
res.redirect('/account/')
} else {
let gitlabReposArr = []
let gitlabPagesArr = []
if(loggedInUser.getGitlabUserId()) { // for users who have activated their gitlab account
let userProjects = await gitlab.getUserProjects(loggedInUser.getGitlabUserId())
if (!userProjects)
res.status(500).send("something went wrong :/")
for (project in userProjects) {
if (userProjects[project].tag_list.includes('website')) {
let page = {
projectInformation: new projectInformation(loggedInUser.getGitlabUserId(), userProjects[project].id, userProjects[project].name,
userProjects[project].description, userProjects[project].avatar_url, userProjects[project].path_with_namespace),
pipelineStatus: await gitlab.getProjectPipelineLatestStatus(userProjects[project].id)
}
gitlabPagesArr.push(page)
} else {
let repo = new projectRepo(loggedInUser.getGitlabUserId(), userProjects[project].id, userProjects[project].name,
userProjects[project].description, userProjects[project].avatar_url, userProjects[project].path_with_namespace)
gitlabReposArr.push(repo)
}
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
}
res.render(lang+'/account/services', {
user: loggedInUser,
gitlabRepos: gitlabReposArr,
gitlabPages: gitlabPagesArr
})
} else { // for users who have not activated their gitlab account yet
let gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail())
// RS: if error, then what?
let gitlabActivationData = {
user_id: loggedInUser.getId(),
gitlab_userId: gitlabUser.id}
// RS: update to await
methods.addGitlabUser(gitlabActivationData, function(err){
if(err) {
res.status(500).render(lang+'/500', { error: err })
} else {
loggedInUser.setGitlabUserId(gitlabActivationData.gitlab_userId)
res.redirect('/account/services')
}
})
}
}
}
})
app.get('/security', async function (req, res) {
if ( !req.isAuthenticated() ) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
if(loggedInUser.getVerificationStatus() == 1 && loggedInUser.getIdpStatus() == 1) {
res.render(lang+'/account/security', {
user: loggedInUser
})
} else {
res.redirect('/account/')
}
}
})
app.post('/updateProfile', async function (req, res) {
var userData = {
salutation: req.body.inputSalutation,
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() ) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
if (userData.email) {
dbconn.user.query('UPDATE user SET ? WHERE email = "' +userData.email+'"', userData, function (err, rows, fields) {
if (err) {
res.flash('error', "Failed")
}
else {
loggedInUser.updateProfile(userData.salutation, userData.title, userData.firstname, userData.lastname, userData.email,
userData.organisation, userData.industry, userData.speciality)
res.flash('success', 'Ihr Benutzerprofil wurde aktualisiert!')
}
res.redirect('/account/profile');
})
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
}
}
});
app.post('/changePwd', async function (req, res) {
if( !req.isAuthenticated() ) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
var currPwd = req.body.inputCurrPwd
var newPwd = req.body.inputNewPwd
var retypePwd = req.body.inputConfirm
// update - get userId from loggedInUser
dbconn.user.query('SELECT password FROM credential WHERE user_id='+loggedInUser.getId(), function (err, rows, fields) {
if (err) {
console.error(err)
res.status(500).render(lang+'/500', { error: err })
}
var userPwd = rows[0].password
// check if the password is correct
bcrypt.compare(currPwd, userPwd, function(err, isMatch) {
if (err) {
console.error(err)
res.status(500).render(lang+'/500', { error: err })
} else if (!isMatch) {
res.flash('error', "Das Passwort ist leider falsch. Bitte überprüfen Sie Ihre Eingabe.")
res.redirect('/account/security')
} else {
if ( newPwd != retypePwd ) {
res.flash('error', 'Passwörter stimmen nicht überein. Bitte stellen Sie sicher, dass Sie das Passwort beide Male genau gleich eingeben.')
res.redirect('/account/security')
} 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) {
res.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.")
throw err
} else {
res.flash('success', "Passwort aktualisiert!")
mailer.options.to = req.user.email
mailer.options.subject = updatePasswordMailSubject
mailer.options.html = updatePasswordMailContent
mailer.transport.sendMail(mailer.options, function(err) {
if (err) { console.log(err) }
});
}
res.redirect('/account/security')
})
});
});
}
}
})
})
}
});
app.get('/forgotPwd', function (req, res) {
res.render(lang+'/account/forgotPwd', {
user: req.user
});
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
});
app.post('/forgotPwd', function(req, res, next) {
let emailAddress = req.body.inputEmail
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");
var emailSubject = "Ihre Passwort-Anfrage an das Transferportal der HFT Stuttgart";
// 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://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>';
var credentialData = {
user_id: user.id,
resetPasswordToken: token,
resetPasswordExpires: Date.now() + 3600000 // 1 hour
}
methods.updateCredential(credentialData, function(err) {
done(err, token, user);
});
// send email
mailer.options.to = emailAddress;
mailer.options.subject = emailSubject;
mailer.options.html = emailContent;
mailer.transport.sendMail(mailer.options, function(err) {
done(err, 'done');
});
}
else {
done(err, 'no user found');
}
});
}
], function(err) {
if (err) {
res.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
}
else {
res.flash('success', 'Wenn Ihre E-Mail-Adresse registriert ist, wurde eine E-Mail mit dem weiteren Vorgehen an ' + emailAddress + ' versendet.');
}
res.redirect('/account/forgotPwd');
});
});
app.get('/reset/:token', function(req, res) {
methods.getUserByToken(req.params.token, function(err, user){
if (!user) {
res.flash('error', 'Der Schlüssel zum zurücksetzen des Passworts ist ungültig oder abgelaufen.')
res.redirect('/account/forgotPwd')
}
else {
res.render(lang+'/account/reset')
}
});
});
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
app.post('/reset/:token', function(req, res) {
var newPwd = req.body.inputNewPwd
methods.getUserByToken(req.params.token, function(err, user){
if (user) {
// encrypt password
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(newPwd, salt, function(err, hash) {
var credentialData = {
password: hash,
user_id: user.user_id
}
// update password
methods.updateCredential(credentialData, function(err){
if (err) {
res.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.")
throw err
}
else {
res.flash('success', "Passwort aktualisiert!")
// send notifiaction email
mailer.options.to = user.email
mailer.options.subject = updatePasswordMailSubject
mailer.options.html = updatePasswordMailContent
mailer.transport.sendMail(mailer.options, function(err) {
if (err) {
console.log(err)
}
});
// redirect to login page
res.redirect('/login')
}
})
});
});
}
else {
res.flash('error', "User not found.")
res.redirect('/login')
}
});
});
// ============= NEW GITLAB PAGES ===========================
app.get('/newInformation', async function(req, res){
if ( !req.isAuthenticated() ) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
let gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail())
if (!gitlabUser) { // no user found
res.redirect('/account/service')
} else {
res.render(lang+'/account/newInformation', {
user: loggedInUser,
gitlabUsername: gitlabUser.username
})
}
}
})
app.post('/newInformation', async function(req, res) {
if( !req.isAuthenticated() ) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
if (!req.body.name && !req.body.description) {
res.flash('error', 'Bitte geben Sie die benötigten Daten ein')
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
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
549
550
551
552
553
554
555
556
557
558
559
560
res.redirect('/account/newInformation')
} else {
let projectName = req.body.name.toLowerCase().replace(/\s/g, '-')
let projectDesc = req.body.description
let projectTemplate = req.body.template
let newInformation = new projectInformation(loggedInUser.getGitlabUserId(), null, projectName, projectDesc, null, null)
let newLogoFile = defaultLogo
if (req.files) { newLogoFile = req.files.logo }
async.waterfall([
function(callback){ // upload logo
if (!req.files) {
callback(null, newLogoFile)
} else {
newLogoFile.mv(logoDir + newLogoFile.name, function(err) {
newLogoFile = logoDir+newLogoFile.name
callback(err, newLogoFile)
})
}
},
async function(newLogoFile){ // create a new GitLab Page
let newPages = await gitlab.createNewPages(newInformation, newLogoFile, projectTemplate)
if (newPages.error) {
if(newPages.data.message.name == "has already been taken") {
res.flash("error", "Der Projektname '"+newInformation.getName()+"' ist bereits vergeben, bitte wählen Sie einen anderen Namen.")
} else {
res.flash("error", "Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut. ")
}
res.redirect('/account/newInformation')
} else {
let newPagesData = newPages.data
res.flash("success", "Ihre Webseite wurde erstellt, aber noch nicht veröffentlicht. Um Ihre Webseite endgültig zu veröffentlichen, "+
"schließen Sie die Einrichtung gemäß unten stehender Anleitung ab.")
/* res.flash("success", "Your website will be published AFTER you complete your website by following the provided guideline below."+
"\r\n Your website URL: "+tpGitlabPagesURL+newPagesData.path_with_namespace+"/home/") */
res.redirect('/account/updateInformation?id='+newPagesData.id)
}
}
], function (err) {
if(err) console.log(err)
// remove logo
if (req.files) {
fs.unlink(newLogoFile, (err) => {
if(err) console.log(err)
})
}
})
}
}
})
app.get('/updateInformation', async function(req, res){
if( !req.isAuthenticated() ) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
if(!req.query.id) {
res.redirect('/account/services')
} else {
let project = await gitlab.getProjectById(req.query.id)
if (!project) {
console.log(" =================== error or no project found")
res.redirect('/account/services')
} else if (project.owner.id != loggedInUser.getGitlabUserId()) {
console.log(" =================== not your project")
res.redirect('/account/services')
} else {
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
let curInformation = new projectInformation(loggedInUser.getGitlabUserId(), req.query.id, project.name, project.description,
project.avatar_url, project.path_with_namespace)
res.render(lang+'/account/updateInformation', {
user: loggedInUser,
information: curInformation
})
}
}
}
})
app.post('/updateInformation', async function(req, res){
if( !req.isAuthenticated() ) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
if (!req.body.name && !req.body.description) {
res.flash('error', 'Bitte geben Sie die benötigten Daten ein')
res.redirect('/account/updateInformation')
} else {
let projectName = req.body.name.toLowerCase().replace(/\s/g, '-')
let projectDesc = req.body.description
let updatedInformation = new projectInformation(loggedInUser.getGitlabUserId(), req.query.id, projectName, projectDesc, null, null)
let newLogoFile
async.waterfall([
function(callback){ // upload logo
if(!req.files) {
callback(null, newLogoFile)
} else {
newLogoFile = req.files.logo
newLogoFile.mv(logoDir + newLogoFile.name, function(err) {
newLogoFile = logoDir + newLogoFile.name
callback(err, newLogoFile)
})
}
},
async function(newLogoFile, callback){ // update gitlab page
let updatedPages = await gitlab.updateProject(updatedInformation, newLogoFile)
let pagesData = updatedPages.data
if (updatedPages.error) {
if(pagesData.message.name == "has already been taken") {
res.flash("error", "Der Projektname ist bereits vergeben, bitte wählen Sie einen anderen Namen.")
} else {
res.flash("error", "Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut. ")
}
} else {
updatedInformation.setLogo(pagesData.avatar_url)
updatedInformation.setPath(pagesData.path)
res.flash("success", "Ihre Website wurde aktualisiert")
}
res.redirect('/account/updateInformation?id='+updatedInformation.getId())
}
], function (err) {
if(err) console.log(err)
if(newLogoFile){ // remove logo
fs.unlink(newLogoFile, (err) => {
if(err) console.log(err)
})
}
})
}
}
})
// RS: delete projektInformation?
// ============= NEW USERS REGISTRATION ===========================
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
app.get('/registration', function(req, res) {
res.render(lang+'/account/registration')
})
app.post('/registration', function(req, res) {
// user data
var curDate = new Date()
var userData = {
salutation: req.body.inputSalutation,
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)
}
var userEmail = userData.email
var pos = userEmail.indexOf('@')
var emailLength = userEmail.length
var emailDomain = userEmail.slice(pos, emailLength);
if ( emailDomain.toLowerCase() == "@hft-stuttgart.de") {
res.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);
});
},
// 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) {
methods.registerNewUser(newAccount, function(err){
if (err) {
res.flash('error', "Fehlgeschlagen")
}
else {
// 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.\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>';
mailer.options.to = req.body.inputEmail;
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
mailer.options.subject = emailSubject;
mailer.options.html = emailContent;
mailer.transport.sendMail(mailer.options, function(err) {
if (err) {
console.log('cannot send email')
throw err
}
})
// user feedback
res.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')
})
}
])
}
})
// ============= USER VERIFICATION ================================
app.get("/verifyAccount", function(req, res){
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 {
// 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 = '<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;
mailer.options.to = data.email;
mailer.options.subject = emailSubject;
mailer.options.html = emailContent;
mailer.transport.sendMail(mailer.options, function(err) {
if (err) {
console.log('cannot send email')
throw err
}
})
}
})
res.render(lang+'/account/verification', {
status: true
});
}
})
}
else {
res.render(lang+'/account/verification', {
status: null
});
}
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
})
})
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
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>';
mailer.options.to = emailAddress;
mailer.options.subject = emailSubject;
mailer.options.html = 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)
}
})
}
})
}
})
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)
}
}
})
})
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;
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
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) {
res.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
}
else {
res.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('/account/contact')
})
})
}