From 6836e43cc3a98de9e2761aa554d6b9a4ab7a0240 Mon Sep 17 00:00:00 2001 From: Rosanny <rosanny.sihombing@hft-stuttgart.de> Date: Fri, 12 Feb 2021 22:28:22 +0100 Subject: [PATCH] clean up codes --- routes/routes-account.js | 320 ++++++++++++++------------------------- 1 file changed, 113 insertions(+), 207 deletions(-) diff --git a/routes/routes-account.js b/routes/routes-account.js index 157ecf62..fe64fd54 100644 --- a/routes/routes-account.js +++ b/routes/routes-account.js @@ -11,7 +11,6 @@ const salt = 64; // salt length const async = require('async') const crypto = require('crypto') const mailer = require('./mailer') -const axios = require('axios') const logoDir = 'public/upload/' const tpGitlabURL = 'https://transfer.hft-stuttgart.de/gitlab/' @@ -113,7 +112,9 @@ module.exports = function (app, config, passport, i18n) { var updatePasswordMailContent = '<div>Lieber Nutzer,<br/><br/>Ihr Passwort wurde erfolgreich geändert.<br/><br/>' + mailSignature + '</div>'; app.get('/', function (req, res) { - if (req.isAuthenticated()) { + if ( !req.isAuthenticated() ) { + res.redirect('/login') + } else { methods.getUserByEmail(req.user.email, function(data, err){ if (!err) { // Initialize user @@ -128,17 +129,11 @@ module.exports = function (app, config, passport, i18n) { }) } - let userData = { - fullName: loggedInUser.getFullName(), - m4lab_idp: loggedInUser.getIdpStatus(), - verificationStatus: loggedInUser.getVerificationStatus()} res.render(lang+'/account/home', { - user: userData + user: loggedInUser }); } }) - } else { - res.redirect('/login'); // localhost } }); @@ -172,47 +167,30 @@ module.exports = function (app, config, passport, i18n) { }); app.get('/profile', function (req, res) { - if (req.isAuthenticated()) { - // RS: to be updated = get data from loggedinuser - console.log(loggedInUser) - methods.getUserByEmail(req.user.email, function(data, err){ - if (!err) { - 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 - }); - } - } - }) + if(!req.isAuthenticated() && !loggedInUser) { + res.redirect('/login') } else { - res.redirect('/login'); + if(loggedInUser.getVerificationStatus() != 1) { + res.redirect('/account/') + } else { + res.render(lang+'/account/profile', { + user: loggedInUser + }) + } } - }); + }) app.get('/services', function(req, res){ if(!req.isAuthenticated() && !loggedInUser) { res.redirect('/login') } else { - let userData = { - fullName: loggedInUser.getFullName(), - m4lab_idp: loggedInUser.getIdpStatus()} - - if(loggedInUser.getVerificationStatus() != 1) { - res.render(lang+'/account/home', { - user: userData - }) + if(loggedInUser.getVerificationStatus() != 1) { // unverified users + res.redirect('/account/') } else { let gitlabReposArr = [] let gitlabPagesArr = [] - if(loggedInUser.getGitlabUserId()) { + if(loggedInUser.getGitlabUserId()) { // for users who have activated their gitlab account async.waterfall([ // check projects in runners function(callback) { @@ -234,7 +212,6 @@ module.exports = function (app, config, passport, i18n) { if (gitlabData[i].tag_list.includes('website')) { let idxRunners = gitlabRunnersProjectIdsArr.indexOf(gitlabData[i].id) let isWebsitePublished = false - //let isWebsitePublished = true if (idxRunners > 0) { isWebsitePublished = true } @@ -248,29 +225,28 @@ module.exports = function (app, config, passport, i18n) { } res.render(lang+'/account/services', { - user: userData, + user: loggedInUser, gitlabRepos: gitlabReposArr, gitlabPages: gitlabPagesArr }) }) }) - } else { - // ========== to do next =================== - gitlab.getUserIdByEmail(req.user.email, function(data){ - if (!data.error) { + } else { // for users who have not activated their gitlab account yet + gitlab.getUserIdByEmail(loggedInUser.getEmail(), function(data){ + if (data.error) { + res.status(500).render(lang+'/500', { error: data.data }) + } else { let gitlabActivationData = { - user_id: loggedInUser.id, + user_id: loggedInUser.getId(), gitlab_userId: data.data} methods.addGitlabUser(gitlabActivationData, function(err){ - if(!err) { - loggedInUser.gitlabUserId = gitlabActivationData.gitlab_userId - res.redirect('/services') + if(err) { + res.status(500).render(lang+'/500', { error: err }) + } else { + loggedInUser.setGitlabUserId(gitlabActivationData.gitlab_userId) + res.redirect('/account/services') } }) - } else { - res.render(lang+'/account/services', { - user: userData - }) } }) } @@ -279,26 +255,18 @@ module.exports = function (app, config, passport, i18n) { }) app.get('/security', function (req, res) { - if (req.isAuthenticated()) { - // RS: to be updated = get data from loggedinuser - methods.getUserByEmail(req.user.email, function(data, err){ - if (!err) { - if (data.verificationStatus == 1 && data.m4lab_idp == 1) { - res.render(lang+'/account/security', { - user: data - }) - } - else { - res.render(lang+'/account/home', { - user: data - }); - } - } - }) + if (!req.isAuthenticated() && !loggedInUser) { + res.redirect('/login') } else { - res.redirect('/login'); + if(loggedInUser.getVerificationStatus() == 1 && loggedInUser.getIdpStatus() == 1) { + res.render(lang+'/account/security', { + user: loggedInUser + }) + } else { + res.redirect('/account/') + } } - }); + }) app.post('/updateProfile', function (req, res) { var userData = { @@ -312,104 +280,83 @@ module.exports = function (app, config, passport, i18n) { speciality: req.body.inputSpeciality, } - if (req.isAuthenticated()) { + if (!req.isAuthenticated() && !loggedInUser) { + res.redirect('/login') + } else { 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'); - // RS: to be updated = update loggedinuser }) } - } else { - res.redirect('/login'); } }); app.post('/changePwd', function (req, res) { - if (req.isAuthenticated()) { + if(!req.isAuthenticated() && !loggedInUser) { + res.redirect('/login') + } else { var currPwd = req.body.inputCurrPwd var newPwd = req.body.inputNewPwd var retypePwd = req.body.inputConfirm - // RS: to be updated = get data from loggedinuser - 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) { - console.error(err) - res.status(500).render(lang+'/500', { - error: err - }) - } - var userPwd = rows[0].password + // 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', "Sorry, your password was incorrect. Please double-check your password.") - res.flash('error', "Das Passwort ist leider falsch. Bitte überprüfen Sie Ihre Eingabe.") - //res.redirect('/security') - res.redirect('/account/security') - } - else { - if ( newPwd != retypePwd ) { - //res.flash('error', "Passwords do no match. Please make sure you re-type your new password correctly.") - 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', "Database error: Password cannot be modified.") - res.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.") - throw err - } - else { - //res.flash('success', "Pasword updated!") - res.flash('success', "Passwort aktualisiert!") - mailer.options.to = req.user.email - //mailOptions.subject = "Your M4_LAB Password has been updated." - mailer.options.subject = updatePasswordMailSubject - mailer.options.html = updatePasswordMailContent - mailer.transport.sendMail(mailer.options, function(err) { - if (err) { - console.log(err) - } - }); - } - res.redirect('/account/security') - }) - }); - }); - } - } - }) + // 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') + }) + }); + }); + } + } }) - } }) } - else { - res.redirect('/login'); - } }); app.get('/forgotPwd', function (req, res) { @@ -419,14 +366,7 @@ module.exports = function (app, config, passport, i18n) { }); app.post('/forgotPwd', function(req, res, next) { - //methods.currentDate(); - - var emailAddress = req.body.inputEmail; - /* var emailContent = "Hi there,\n\n"+ - "we've received a request to reset your password. However, this email address is not on our database of registered users.\n\n"+ - "Thanks,\nM4_LAB Team"; - var emailSubject = "Account Access Attempted"; */ - + let emailAddress = req.body.inputEmail async.waterfall([ function(done) { crypto.randomBytes(20, function(err, buf) { @@ -438,17 +378,10 @@ module.exports = function (app, config, passport, i18n) { methods.checkUserEmail(emailAddress, function(err, user){ if (user) { console.log("email: user found"); - //var emailSubject = "M4_LAB Password Reset"; var emailSubject = "Ihre Passwort-Anfrage an das Transferportal der HFT Stuttgart"; - /* var emailContent = "Hi User,\n\n"+ - "we've received a request to reset your password. If you didn't make the request, just ignore this email.\n\n"+ - "Otherwise, you can reset your password using this link: http://m4lab.hft-stuttgart.de/account/reset/" + token + "\n" + - "This password reset is only valid for 1 hour.\n\n"+ - "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"+ - // "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 + // "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/>' + @@ -474,35 +407,29 @@ module.exports = function (app, config, passport, i18n) { }); } else { - //done(err, null, null); done(err, 'no user found'); } }); } ], function(err) { if (err) { - //res.flash('error', 'An error occured. Please try again.'); res.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.'); } else { - //res.flash('success', 'If your email is registered, an e-mail has been sent to ' + emailAddress + ' with further instructions.'); res.flash('success', 'Wenn Ihre E-Mail-Adresse registriert ist, wurde eine E-Mail mit dem weiteren Vorgehen an ' + emailAddress + ' versendet.'); } - //res.redirect('/forgotPwd'); // deployment - res.redirect('/account/forgotPwd'); // localhost + res.redirect('/account/forgotPwd'); }); }); app.get('/reset/:token', function(req, res) { methods.getUserByToken(req.params.token, function(err, user){ if (!user) { - //res.flash('error', 'Password reset token is invalid or has expired.'); - res.flash('error', 'Der Schlüssel zum zurücksetzen des Passworts ist ungültig oder abgelaufen.'); - //res.redirect('/forgotPwd'); // deployment - res.redirect('/account/forgotPwd'); // deployment + 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'); + res.render(lang+'/account/reset') } }); }); @@ -521,12 +448,10 @@ module.exports = function (app, config, passport, i18n) { // update password methods.updateCredential(credentialData, function(err){ if (err) { - //res.flash('error', "Database error: Password cannot be modified.") res.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.") throw err } else { - //res.flash('success', "Your pasword has been updated.") res.flash('success', "Passwort aktualisiert!") // send notifiaction email mailer.options.to = user.email @@ -558,12 +483,8 @@ module.exports = function (app, config, passport, i18n) { if (!req.isAuthenticated() && !loggedInUser) { res.redirect('/login') } else { - let userData = { - fullName: loggedInUser.getFullName(), - m4lab_idp: loggedInUser.getIdpStatus() - } res.render(lang+'/account/newInformation', { - user: userData + user: loggedInUser }) } }) @@ -573,8 +494,7 @@ module.exports = function (app, config, passport, i18n) { } else { if (!req.body.name && !req.body.description) { res.flash('error', 'Please provide the required data') - //res.redirect('/account/newInformation') - res.redirect('/newInformation') + res.redirect('/account/newInformation') } else { let projectName = req.body.name.toLowerCase().replace(/\s/g, '-') let projectDesc = req.body.description @@ -582,8 +502,7 @@ module.exports = function (app, config, passport, i18n) { if (!req.files) { res.flash('error', 'Please choose a project logo') - //res.redirect('/account/newInformation') - res.redirect('/newInformation') + res.redirect('/account/newInformation') } else { let newLogoFile = req.files.logo async.waterfall([ @@ -602,8 +521,7 @@ module.exports = function (app, config, passport, i18n) { } else { res.flash("error", "Something went wrong. Please try again.") } - //res.redirect('/account/newInformation') - res.redirect('/newInformation') + res.redirect('/account/newInformation') } else { newInformation.setId(result.id) newInformation.setLogo(result.avatar_url) @@ -611,8 +529,7 @@ module.exports = function (app, config, passport, i18n) { newInformation.setKontaktUrl(tpGitlabURL+result.namespace.path+'/'+result.name+'/-/edit/master/public/kontakt.html') res.flash("success", "Your website has been created, but not published yet. Please continue to Step 2 and Step 3 to have your new website published.") - //res.redirect('/account/updateInformation?id='+newInformation.getId()) - res.redirect('/updateInformation?id='+newInformation.getId()) + res.redirect('/account/updateInformation?id='+newInformation.getId()) } callback(null) }) @@ -633,18 +550,12 @@ module.exports = function (app, config, passport, i18n) { if(!req.isAuthenticated() && !loggedInUser) { res.redirect('/login') } else { - let userData = { - fullName: loggedInUser.getFullName(), - m4lab_idp: loggedInUser.getIdpStatus()} - if(!req.query.id) { res.redirect('/account/services') } else { gitlab.getUserProjects(loggedInUser.getGitlabUserId(), function(data){ if (data.error) { - res.status(500).render(lang+'/500', { - error: data.data - }) + res.status(500).render(lang+'/500', { error: data.data }) } else { // quick way to decide whether a website is already published or not let informationStatus @@ -670,7 +581,7 @@ module.exports = function (app, config, passport, i18n) { } } res.render(lang+'/account/updateInformation', { - user: userData, + user: loggedInUser, information: curInformation }) } @@ -685,8 +596,7 @@ module.exports = function (app, config, passport, i18n) { } else { if (!req.body.name && !req.body.description) { res.flash('error', 'Please provide the required data') - //res.redirect('/account/updateInformation') - res.redirect('/updateInformation') + res.redirect('/account/updateInformation') } else { let projectName = req.body.name.toLowerCase().replace(/\s/g, '-') let projectDesc = req.body.description @@ -720,9 +630,8 @@ module.exports = function (app, config, passport, i18n) { updatedInformation.setKontaktUrl(tpGitlabURL+result.namespace.path+'/'+result.name+'/-/edit/master/public/kontakt.html') res.flash("success", "Your website has been updated") } - //res.redirect('/account/updateInformation?id='+updatedInformation.getId()) - res.redirect('/updateInformation?id='+updatedInformation.getId()) - + res.redirect('/account/updateInformation?id='+updatedInformation.getId()) + callback(null) }) } @@ -746,7 +655,6 @@ module.exports = function (app, config, passport, i18n) { } else { let emailAddress = loggedInUser.getEmail() let supportAddress = "support-transfer@hft-stuttgart.de" - //let supportAddress = "rosanny.sihombing@hft-stuttgart.de" let projectName = req.body.projectName let emailContent = "Guten Tag, \n\nhiermit beantrage Ich die Freischaltung einer Webseite auf dem Transferportal für folgendes Projekt: \n" +projectName+"\n\nVielen Dank,\n"+loggedInUser.getFullName() @@ -865,7 +773,6 @@ module.exports = function (app, config, passport, i18n) { }) // ============= USER VERIFICATION ================================ - // RS: update loggedInUser status after successfull verification? app.get("/verifyAccount", function(req, res){ console.log(req.query) methods.getUserIdByVerificationToken(req.query.token, function(userId, err){ @@ -890,9 +797,6 @@ module.exports = function (app, config, passport, i18n) { 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 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; @@ -908,6 +812,9 @@ module.exports = function (app, config, passport, i18n) { } }) + if(!loggedInUser) { + loggedInUser.setVerificationStatus(userData.verificationStatus) + } res.render(lang+'/account/verification', { status: true }); @@ -1012,8 +919,7 @@ module.exports = function (app, config, passport, i18n) { 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('/forgotPwd'); // deployment - res.redirect('/account/contact'); // localhost + res.redirect('/account/contact') }) }) -- GitLab