Commit 28fe54f1 authored by Rosanny Sihombing's avatar Rosanny Sihombing
Browse files

clean codes

parent 9b0bffa7
// check password and password confirmation input fields // check password and password confirmation input fields
// used in Security and Reset Password // used in Security and Reset Password
$('#inputNewPwd, #inputConfirm').on('keyup', function () { $('#inputNewPwd, #inputConfirm').on('keyup', function () {
var isBest, isMatch; let isBest, isMatch
isBest = checkPasswordReq($('#inputNewPwd').val()) isBest = checkPasswordReq($('#inputNewPwd').val())
$('#recommendation').empty(); $('#recommendation').empty()
if (!isBest) { if (!isBest) {
//$('#recommendation').html('Must be at least 8 characters').css('color', 'red'); // $('#recommendation').html('Must be at least 8 characters').css('color', 'red');
$('#recommendation').html('Das Passwort muss mindestens 8 Zeichen haben').css('color', 'red'); $('#recommendation').html('Das Passwort muss mindestens 8 Zeichen haben').css('color', 'red')
} }
// match or not? // match or not?
if ($('#inputNewPwd').val() == $('#inputConfirm').val()) { if ($('#inputNewPwd').val() == $('#inputConfirm').val()) {
//$('#message').html('Matching').css('color', 'green'); // $('#message').html('Matching').css('color', 'green');
$('#message').html('Übereinstimmend').css('color', 'green'); $('#message').html('Übereinstimmend').css('color', 'green')
isMatch = true; isMatch = true
} else { } else {
//$('#message').html('Not Matching').css('color', 'red'); // $('#message').html('Not Matching').css('color', 'red');
$('#message').html('Nicht übereinstimmend').css('color', 'red'); $('#message').html('Nicht übereinstimmend').css('color', 'red')
isMatch = false; isMatch = false
} }
// enable/disable update button // enable/disable update button
if (isBest && isMatch) { if (isBest && isMatch) {
$('#updateBtn').prop('disabled', false); $('#updateBtn').prop('disabled', false)
} else { } else {
$('#updateBtn').prop('disabled', true); $('#updateBtn').prop('disabled', true)
} }
}); })
\ No newline at end of file
...@@ -12,53 +12,52 @@ import projectInformation from '../classes/website' ...@@ -12,53 +12,52 @@ import projectInformation from '../classes/website'
import projectRepo from '../classes/repo' import projectRepo from '../classes/repo'
const SamlStrategy = passportSaml.Strategy const SamlStrategy = passportSaml.Strategy
const saltRounds = 10; const saltRounds = 10
const salt = 64; // salt length const salt = 64 // salt length
const logoDir = 'public/upload/' const logoDir = 'public/upload/'
const defaultLogo:any = 'public/default/logo.png' const defaultLogo: any = 'public/default/logo.png'
export = function (app:any, config:any, passport:any, lang:string) {
export = function (app: any, config: any, passport: any, lang: string) {
// =========== PASSPORT ======= // =========== PASSPORT =======
passport.serializeUser(function (user:any, done:any) { passport.serializeUser(function (user: any, done: any) {
done(null, user); done(null, user)
}); })
passport.deserializeUser(function (user:any, done:any) { passport.deserializeUser(function (user: any, done: any) {
done(null, user); done(null, user)
}); })
var samlStrategy = new SamlStrategy({ const samlStrategy = new SamlStrategy({
// URL that goes from the Identity Provider -> Service Provider // URL that goes from the Identity Provider -> Service Provider
callbackUrl: config.passport.saml.path, callbackUrl: config.passport.saml.path,
// Base address to call logout requests // Base address to call logout requests
logoutUrl: config.passport.saml.logoutUrl, logoutUrl: config.passport.saml.logoutUrl,
entryPoint: config.passport.saml.entryPoint, entryPoint: config.passport.saml.entryPoint,
issuer: config.passport.saml.issuer, issuer: config.passport.saml.issuer,
identifierFormat: undefined, identifierFormat: undefined,
// Service Provider private key // Service Provider private key
decryptionPvk: fs.readFileSync(__dirname + '/cert/key.pem', 'utf8'), decryptionPvk: fs.readFileSync(__dirname + '/cert/key.pem', 'utf8'),
// Service Provider Certificate // Service Provider Certificate
privateKey: fs.readFileSync(__dirname + '/cert/key.pem', 'utf8'), privateKey: fs.readFileSync(__dirname + '/cert/key.pem', 'utf8'),
// Identity Provider's public key // Identity Provider's public key
cert: fs.readFileSync(__dirname + '/cert/cert_idp.pem', 'utf8'), cert: fs.readFileSync(__dirname + '/cert/cert_idp.pem', 'utf8'),
validateInResponseTo: false, validateInResponseTo: false,
disableRequestedAuthnContext: true disableRequestedAuthnContext: true
}, },
function (profile:any, done:any) { function (profile: any, done: any) {
return done(null, { return done(null, {
id: profile.nameID, id: profile.nameID,
idFormat: profile.nameIDFormat, idFormat: profile.nameIDFormat,
email: profile.email, email: profile.email,
firstName: profile.givenName, firstName: profile.givenName,
lastName: profile.sn lastName: profile.sn
}); })
}); })
passport.use(samlStrategy); passport.use(samlStrategy)
// ============= SAML ============== // ============= SAML ==============
app.post(config.passport.saml.path, app.post(config.passport.saml.path,
...@@ -67,33 +66,33 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -67,33 +66,33 @@ export = function (app:any, config:any, passport:any, lang:string) {
failureRedirect: '/account/', failureRedirect: '/account/',
failureFlash: true failureFlash: true
}), }),
function (req:any, res:any) { function (req: any, res: any) {
res.redirect('/account/'); res.redirect('/account/')
} }
); )
// to generate Service Provider's XML metadata // to generate Service Provider's XML metadata
app.get('/saml/metadata', app.get('/saml/metadata',
function(req:any, res:any) { function (req: any, res: any) {
res.type('application/xml'); res.type('application/xml')
var spMetadata = samlStrategy.generateServiceProviderMetadata(fs.readFileSync(__dirname + '/cert/cert.pem', 'utf8')); const spMetadata = samlStrategy.generateServiceProviderMetadata(fs.readFileSync(__dirname + '/cert/cert.pem', 'utf8'))
res.status(200).send(spMetadata); res.status(200).send(spMetadata)
} }
); )
// ======== APP ROUTES - ACCOUNT ==================== // ======== APP ROUTES - ACCOUNT ====================
async function getLoggedInUserData(email:string) { async function getLoggedInUserData (email: string) {
let user = await methods.getUserByEmail(email) const user = await methods.getUserByEmail(email)
if (!user) { if (!user) {
console.log('no user found') console.log('no user found')
return null return null
} else { } else {
let loggedInUser = new portalUser( const loggedInUser = new portalUser(
user.id, email, user.salutation, user.title, user.firstname, user.lastname, user.industry, user.organisation, user.speciality, user.m4lab_idp, user.verificationStatus user.id, email, user.salutation, user.title, user.firstname, user.lastname, user.industry, user.organisation, user.speciality, user.m4lab_idp, user.verificationStatus
) )
let userGitlabId = await methods.getGitlabId(loggedInUser.id) const userGitlabId = await methods.getGitlabId(loggedInUser.id)
if (userGitlabId) { if (userGitlabId) {
loggedInUser.setGitlabUserId(userGitlabId) loggedInUser.setGitlabUserId(userGitlabId)
} }
...@@ -101,21 +100,21 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -101,21 +100,21 @@ export = function (app:any, config:any, passport:any, lang:string) {
} }
} }
app.get('/', async function (req:any, res:any) { app.get('/', async function (req: any, res: any) {
if ( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { if (loggedInUser == null) {
console.error("user data is not found") console.error('user data is not found')
res.status(500).render(lang+'/500', { error: "Your data is not found. Please try again." }) res.status(500).render(lang + '/500', { error: 'Your data is not found. Please try again.' })
} else { } else {
res.render(lang+'/account/home', { res.render(lang + '/account/home', {
user: loggedInUser user: loggedInUser
}); })
} }
} }
}); })
app.get('/login', app.get('/login',
passport.authenticate(config.passport.strategy, { passport.authenticate(config.passport.strategy, {
...@@ -124,106 +123,106 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -124,106 +123,106 @@ export = function (app:any, config:any, passport:any, lang:string) {
}) })
) )
app.get('/logout', function (req:any, res:any) { app.get('/logout', function (req: any, res: any) {
if (req.user == null) { if (req.user == null) {
return res.redirect('/'); return res.redirect('/')
} }
req.user.nameID = req.user.id; req.user.nameID = req.user.id
req.user.nameIDFormat = req.user.idFormat; req.user.nameIDFormat = req.user.idFormat
return samlStrategy.logout(req, function(err:any, uri:any) { return samlStrategy.logout(req, function (err: any, uri: any) {
req.logout(); req.logout()
if ( req.session ) { if (req.session) {
req.session.destroy((err:any) => { req.session.destroy((err: any) => {
if(err) { if (err) {
return console.log(err); return console.log(err)
} }
}); })
} }
return res.redirect(uri); return res.redirect(uri)
}); })
}); })
app.get('/profile', async function (req:any, res:any) { app.get('/profile', async function (req: any, res: any) {
if ( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { // null user if (loggedInUser == null) { // null user
res.redirect('/account/') res.redirect('/account/')
} else { } else {
if(loggedInUser.getVerificationStatus() != 1) { if (loggedInUser.getVerificationStatus() != 1) {
res.redirect('/account/') res.redirect('/account/')
} else { } else {
res.render(lang+'/account/profile', { res.render(lang + '/account/profile', {
user: loggedInUser user: loggedInUser
}) })
} }
} }
} }
}) })
app.get('/services', async function(req:any, res:any){ app.get('/services', async function (req: any, res: any) {
if( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { // null user if (loggedInUser == null) { // null user
res.redirect('/account/') res.redirect('/account/')
} else { } else {
if(loggedInUser.getVerificationStatus() != 1) { // unverified users if (loggedInUser.getVerificationStatus() != 1) { // unverified users
res.redirect('/account/') res.redirect('/account/')
} else { } else {
let gitlabReposArr = [] const gitlabReposArr = []
let gitlabPagesArr = [] const gitlabPagesArr = []
if(loggedInUser.getGitlabUserId()) { // for users who have activated their gitlab account if (loggedInUser.getGitlabUserId()) { // for users who have activated their gitlab account
let userProjects = await gitlab.getUserProjects(loggedInUser.getGitlabUserId()!) const userProjects = await gitlab.getUserProjects(loggedInUser.getGitlabUserId()!)
if (!userProjects) { if (!userProjects) {
console.error("something went wrong") console.error('something went wrong')
res.status(500).render(lang+'/500', { error: "something went wrong" }) res.status(500).render(lang + '/500', { error: 'something went wrong' })
} }
let project:any let project: any
for (project in userProjects) { for (project in userProjects) {
if (userProjects[project].tag_list.includes('website')) { if (userProjects[project].tag_list.includes('website')) {
let page = { const page = {
projectInformation: new projectInformation(loggedInUser.getGitlabUserId()!, userProjects[project].name, userProjects[project].description, projectInformation: new projectInformation(loggedInUser.getGitlabUserId()!, userProjects[project].name, userProjects[project].description,
userProjects[project].id, userProjects[project].avatar_url, userProjects[project].path_with_namespace), userProjects[project].id, userProjects[project].avatar_url, userProjects[project].path_with_namespace),
pipelineStatus: await gitlab.getProjectPipelineLatestStatus(userProjects[project].id) pipelineStatus: await gitlab.getProjectPipelineLatestStatus(userProjects[project].id)
} }
gitlabPagesArr.push(page) gitlabPagesArr.push(page)
} else { } else {
let repo = new projectRepo(loggedInUser.getGitlabUserId()!, userProjects[project].name, userProjects[project].description, const repo = new projectRepo(loggedInUser.getGitlabUserId()!, userProjects[project].name, userProjects[project].description,
userProjects[project].id, userProjects[project].avatar_url, userProjects[project].path_with_namespace) userProjects[project].id, userProjects[project].avatar_url, userProjects[project].path_with_namespace)
gitlabReposArr.push(repo) gitlabReposArr.push(repo)
} }
} }
res.render(lang+'/account/services', { res.render(lang + '/account/services', {
user: loggedInUser, user: loggedInUser,
gitlabRepos: gitlabReposArr, gitlabRepos: gitlabReposArr,
gitlabPages: gitlabPagesArr gitlabPages: gitlabPagesArr
}) })
} else { // for users who have not activated their gitlab account yet } else { // for users who have not activated their gitlab account yet
let gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail()) const gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail())
if (!gitlabUser) { if (!gitlabUser) {
res.render(lang+'/account/services', { res.render(lang + '/account/services', {
user: loggedInUser, user: loggedInUser,
gitlabRepos: null, gitlabRepos: null,
gitlabPages: null gitlabPages: null
}) })
} else { } else {
let gitlabActivationData = { const gitlabActivationData = {
user_id: loggedInUser.getId(), user_id: loggedInUser.getId(),
gitlab_userId: gitlabUser.id} gitlab_userId: gitlabUser.id
}
methods.addGitlabUser(gitlabActivationData, function(err:any){ methods.addGitlabUser(gitlabActivationData, function (err: any) {
if(err) { if (err) {
res.status(500).render(lang+'/500', { error: err }) res.status(500).render(lang + '/500', { error: err })
} else { } else {
res.redirect('/account/services') res.redirect('/account/services')
} }
...@@ -235,16 +234,16 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -235,16 +234,16 @@ export = function (app:any, config:any, passport:any, lang:string) {
} }
}) })
app.get('/security', async function (req:any, res:any) { app.get('/security', async function (req: any, res: any) {
if ( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { // null user if (loggedInUser == null) { // null user
res.redirect('/account/') res.redirect('/account/')
} else { } else {
if(loggedInUser.getVerificationStatus() == 1 && loggedInUser.getIdpStatus() == 1) { if (loggedInUser.getVerificationStatus() == 1 && loggedInUser.getIdpStatus() == 1) {
res.render(lang+'/account/security', { res.render(lang + '/account/security', {
user: loggedInUser user: loggedInUser
}) })
} else { } else {
...@@ -254,15 +253,15 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -254,15 +253,15 @@ export = function (app:any, config:any, passport:any, lang:string) {
} }
}) })
app.post('/updateProfile', async function (req:any, res:any) { app.post('/updateProfile', async function (req: any, res: any) {
if ( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { // null user if (loggedInUser == null) { // null user
res.redirect('/account/') res.redirect('/account/')
} else { } else {
let userData = { const userData = {
salutation: req.body.inputSalutation, salutation: req.body.inputSalutation,
title: req.body.inputTitle, title: req.body.inputTitle,
firstname: req.body.inputFirstname, firstname: req.body.inputFirstname,
...@@ -270,11 +269,11 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -270,11 +269,11 @@ export = function (app:any, config:any, passport:any, lang:string) {
email: req.body.inputEmail, email: req.body.inputEmail,
organisation: req.body.inputOrganisation, organisation: req.body.inputOrganisation,
industry: req.body.inputIndustry, industry: req.body.inputIndustry,
speciality: req.body.inputSpeciality, speciality: req.body.inputSpeciality
} }
let result = await methods.updateUserById(loggedInUser.getId(), userData) const result = await methods.updateUserById(loggedInUser.getId(), userData)
if (!result) { if (!result) {
res.flash('error', "Failed") res.flash('error', 'Failed')
} else { } else {
loggedInUser.updateProfile(userData.salutation, userData.title, userData.firstname, userData.lastname, userData.email, loggedInUser.updateProfile(userData.salutation, userData.title, userData.firstname, userData.lastname, userData.email,
userData.organisation, userData.industry, userData.speciality) userData.organisation, userData.industry, userData.speciality)
...@@ -282,101 +281,99 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -282,101 +281,99 @@ export = function (app:any, config:any, passport:any, lang:string) {
} }
res.redirect('/account/profile') res.redirect('/account/profile')
} }
} }
}); })
app.post('/changePwd', async function (req:any, res:any) { app.post('/changePwd', async function (req: any, res: any) {
if( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { // null user if (loggedInUser == null) { // null user
res.redirect('/account/') res.redirect('/account/')
} else { } else {
let currPwd = req.body.inputCurrPwd const currPwd = req.body.inputCurrPwd
let newPwd = req.body.inputNewPwd const newPwd = req.body.inputNewPwd
let retypePwd = req.body.inputConfirm const retypePwd = req.body.inputConfirm
dbconn.user.query('SELECT password FROM credential WHERE user_id='+loggedInUser.getId(), function (err:any, rows:any) { dbconn.user.query('SELECT password FROM credential WHERE user_id=' + loggedInUser.getId(), function (err: any, rows: any) {
if (err) { if (err) {
console.error(err) console.error(err)
res.status(500).render(lang+'/500', { error: err }) res.status(500).render(lang + '/500', { error: err })
} }
let userPwd = rows[0].password const userPwd = rows[0].password
// check if the password is correct // check if the password is correct
bcrypt.compare(currPwd, userPwd, function(err, isMatch) { bcrypt.compare(currPwd, userPwd, function (err, isMatch) {
if (err) { if (err) {
console.error(err) console.error(err)
res.status(500).render(lang+'/500', { error: err }) res.status(500).render(lang + '/500', { error: err })
} else if (!isMatch) { } else if (!isMatch) {
res.flash('error', "Das Passwort ist leider falsch. Bitte überprüfen Sie Ihre Eingabe.") res.flash('error', 'Das Passwort ist leider falsch. Bitte überprüfen Sie Ihre Eingabe.')
res.redirect('/account/security') res.redirect('/account/security')
} else { } else {
if ( newPwd != retypePwd ) { 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.flash('error', 'Passwörter stimmen nicht überein. Bitte stellen Sie sicher, dass Sie das Passwort beide Male genau gleich eingeben.')
res.redirect('/account/security') res.redirect('/account/security')
} else { } else {
// update password // update password
bcrypt.genSalt(saltRounds, function(err, salt) { bcrypt.genSalt(saltRounds, function (err, salt) {
bcrypt.hash(newPwd, salt, async function(err, hash) { bcrypt.hash(newPwd, salt, async function (err, hash) {
var credentialData = { const credentialData = {
password: hash, password: hash,
user_id: loggedInUser!.getId() user_id: loggedInUser.getId()
} }
let result = await methods.updateCredential(credentialData) const result = await methods.updateCredential(credentialData)
if (!result) { if (!result) {
console.log('Failed to reset password') console.log('Failed to reset password')
res.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.") res.flash('error', 'Datenbankfehler: Passwort kann nicht geändert werden.')
} else { } else {
res.flash('success', "Passwort aktualisiert!") res.flash('success', 'Passwort aktualisiert!')
// send notifiaction email // send notifiaction email
mailer.options.to = loggedInUser!.getEmail() mailer.options.to = loggedInUser.getEmail()
mailer.options.subject = constants.updatePasswordMailSubject mailer.options.subject = constants.updatePasswordMailSubject
mailer.options.html = constants.updatePasswordMailContent+'<div>'+constants.mailSignature+'</div>' mailer.options.html = constants.updatePasswordMailContent + '<div>' + constants.mailSignature + '</div>'
mailer.transporter.sendMail(mailer.options, function(err:any) { mailer.transporter.sendMail(mailer.options, function (err: any) {
if (err) { console.log(err) } if (err) { console.log(err) }
}) })
} }
res.redirect('/account/security') res.redirect('/account/security')
})
}); })
});
} }
} }
}) })
}) })
} }
} }
}); })
app.get('/resendVerificationEmail', async function(req:any, res:any){ app.get('/resendVerificationEmail', async function (req: any, res: any) {
if (!req.isAuthenticated) { if (!req.isAuthenticated) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { if (loggedInUser == null) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let token = await methods.getVerificationTokenByUserId(loggedInUser.id) const token = await methods.getVerificationTokenByUserId(loggedInUser.id)
if (!token) { if (!token) {
res.send(false) res.send(false)
} else { } else {
// send email // send email
var emailSubject = "Bitte bestätigen Sie Ihr M4_LAB Benutzerkonto" const emailSubject = 'Bitte bestätigen Sie Ihr M4_LAB Benutzerkonto'
var emailContent = '<div>Lieber Nutzer,<br/><br/>' + const emailContent = '<div>Lieber Nutzer,<br/><br/>' +
'<p>vielen Dank für Ihre Anmeldung am Transferportal der HFT Stuttgart. <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 + 'Um Ihre Anmeldung zu bestätigen, klicken Sie bitte diesen Link: ' + config.app.host + '/verifyAccount?token=' + token +
'<br/><br/>' + '<br/><br/>' +
'Ohne Bestätigung Ihres Kontos müssen wir Ihr Konto leider nach 7 Tagen löschen.</p><br/>' + constants.mailSignature + 'Ohne Bestätigung Ihres Kontos müssen wir Ihr Konto leider nach 7 Tagen löschen.</p><br/>' + constants.mailSignature +
'</div>'; '</div>'
mailer.options.to = loggedInUser.email; mailer.options.to = loggedInUser.email
mailer.options.subject = emailSubject; mailer.options.subject = emailSubject
mailer.options.html = emailContent; mailer.options.html = emailContent
mailer.transport.sendMail(mailer.options, function(err:any) { mailer.transport.sendMail(mailer.options, function (err: any) {
if (err) { if (err) {
console.log('cannot send email') console.log('cannot send email')
throw err throw err
...@@ -389,20 +386,20 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -389,20 +386,20 @@ export = function (app:any, config:any, passport:any, lang:string) {
}) })
// ============= NEW GITLAB PAGES =========================== // ============= NEW GITLAB PAGES ===========================
app.get('/newInformation', async function(req:any, res:any){ app.get('/newInformation', async function (req: any, res: any) {
if ( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { if (loggedInUser == null) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail()) const gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail())
if (!gitlabUser) { // no user found if (!gitlabUser) { // no user found
res.redirect('/account/services') res.redirect('/account/services')
} else { } else {
res.render(lang+'/account/newInformation', { res.render(lang + '/account/newInformation', {
user: loggedInUser, user: loggedInUser,
gitlabUsername: gitlabUser.username gitlabUsername: gitlabUser.username
}) })
...@@ -410,58 +407,58 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -410,58 +407,58 @@ export = function (app:any, config:any, passport:any, lang:string) {
} }
} }
}) })
app.post('/newInformation', async function(req:any, res:any) { app.post('/newInformation', async function (req: any, res: any) {
if( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { if (loggedInUser == null) {
res.redirect('/login') res.redirect('/login')
} else { } else {
if (!req.body.name && !req.body.description) { if (!req.body.name && !req.body.description) {
res.flash('error', 'Bitte geben Sie die benötigten Daten ein') res.flash('error', 'Bitte geben Sie die benötigten Daten ein')
res.redirect('/account/newInformation') res.redirect('/account/newInformation')
} else { } else {
let projectName = req.body.name.toLowerCase().replace(/\s/g, '-') const projectName = req.body.name.toLowerCase().replace(/\s/g, '-')
let projectDesc = req.body.description const projectDesc = req.body.description
let projectTemplate = req.body.template const projectTemplate = req.body.template
let newInformation = new projectInformation(loggedInUser.getGitlabUserId()!, projectName, projectDesc) const newInformation = new projectInformation(loggedInUser.getGitlabUserId()!, projectName, projectDesc)
let newLogoFile = defaultLogo let newLogoFile = defaultLogo
if (req.files) { newLogoFile = req.files.logo } if (req.files) { newLogoFile = req.files.logo }
async.waterfall([ async.waterfall([
function(callback:any){ // upload logo function (callback: any) { // upload logo
if (!req.files) { if (!req.files) {
callback(null, newLogoFile) callback(null, newLogoFile)
} else { } else {
newLogoFile.mv(logoDir + newLogoFile.name, function(err:any) { newLogoFile.mv(logoDir + newLogoFile.name, function (err: any) {
newLogoFile = logoDir+newLogoFile.name newLogoFile = logoDir + newLogoFile.name
callback(err, newLogoFile) callback(err, newLogoFile)
}) })
} }
}, },
async function(newLogoFile:any){ // create a new GitLab Page async function (newLogoFile: any) { // create a new GitLab Page
let newPages = await gitlab.createNewPages(newInformation, newLogoFile, projectTemplate) const newPages = await gitlab.createNewPages(newInformation, newLogoFile, projectTemplate)
if (newPages.status) { if (newPages.status) {
if(newPages.data.message.name == "has already been taken") { 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.") res.flash('error', "Der Projektname '" + newInformation.getName() + "' ist bereits vergeben, bitte wählen Sie einen anderen Namen.")
} else { } else {
res.flash("error", "Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut. ") res.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut. ')
} }
res.redirect('/account/newInformation') res.redirect('/account/newInformation')
} else { } else {
res.flash("success", "Ihre Webseite wurde erstellt, aber noch nicht veröffentlicht. Um Ihre Webseite endgültig zu veröffentlichen, "+ 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.") 'schließen Sie die Einrichtung gemäß unten stehender Anleitung ab.')
res.redirect('/account/updateInformation?id='+newPages.id) res.redirect('/account/updateInformation?id=' + newPages.id)
} }
} }
], function (err) { ], function (err) {
if(err) console.log(err) if (err != null) console.log(err)
// remove logo // remove logo
if (req.files) { if (req.files) {
fs.unlink(newLogoFile, (err) => { fs.unlink(newLogoFile, (err) => {
if(err) console.log(err) if (err != null) console.log(err)
}) })
} }
}) })
...@@ -470,33 +467,33 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -470,33 +467,33 @@ export = function (app:any, config:any, passport:any, lang:string) {
} }
}) })
app.get('/updateInformation', async function(req:any, res:any){ app.get('/updateInformation', async function (req: any, res: any) {
if( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { if (loggedInUser == null) {
res.redirect('/login') res.redirect('/login')
} else { } else {
if(!req.query.id) { if (!req.query.id) {
res.redirect('/account/services') res.redirect('/account/services')
} else { } else {
let project = await gitlab.getProjectById(req.query.id) const project = await gitlab.getProjectById(req.query.id)
if (!project) { if (!project) {
console.log(" ========= Error or no project found") console.log(' ========= Error or no project found')
res.redirect('/account/services') res.redirect('/account/services')
} else if (!project.owner) { } else if (!project.owner) {
console.log(" ========= Project cannot be accessed, since it does not have an owner") console.log(' ========= Project cannot be accessed, since it does not have an owner')
res.redirect('/account/services') res.redirect('/account/services')
} else if (project.owner.id != loggedInUser.getGitlabUserId()) { } else if (project.owner.id != loggedInUser.getGitlabUserId()) {
console.log(" ========= Access denied: Not your project") console.log(' ========= Access denied: Not your project')
res.redirect('/account/services') res.redirect('/account/services')
} else { } else {
let curInformation = new projectInformation(loggedInUser.getGitlabUserId()!, project.name, project.description, const curInformation = new projectInformation(loggedInUser.getGitlabUserId()!, project.name, project.description,
req.query.id, project.avatar_url, project.path_with_namespace) req.query.id, project.avatar_url, project.path_with_namespace)
res.render(lang+'/account/updateInformation', { res.render(lang + '/account/updateInformation', {
user: loggedInUser, user: loggedInUser,
information: curInformation information: curInformation
}) })
...@@ -506,58 +503,58 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -506,58 +503,58 @@ export = function (app:any, config:any, passport:any, lang:string) {
} }
}) })
// update a website // update a website
app.post('/updateInformation', async function(req:any, res:any){ app.post('/updateInformation', async function (req: any, res: any) {
if( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { if (loggedInUser == null) {
res.redirect('/login') res.redirect('/login')
} else { } else {
if (!req.body.name && !req.body.description) { if (!req.body.name && !req.body.description) {
res.flash('error', 'Bitte geben Sie die benötigten Daten ein') res.flash('error', 'Bitte geben Sie die benötigten Daten ein')
res.redirect('/account/updateInformation') res.redirect('/account/updateInformation')
} else { } else {
let projectName = req.body.name.toLowerCase().replace(/\s/g, '-') const projectName = req.body.name.toLowerCase().replace(/\s/g, '-')
let projectDesc = req.body.description const projectDesc = req.body.description
let updatedInformation = new projectInformation(loggedInUser.getGitlabUserId()!, projectName, projectDesc, req.query.id) const updatedInformation = new projectInformation(loggedInUser.getGitlabUserId()!, projectName, projectDesc, req.query.id)
let newLogoFile:any let newLogoFile: any
async.waterfall([ async.waterfall([
function(callback:any){ // upload logo function (callback: any) { // upload logo
if(!req.files) { if (!req.files) {
callback(null, newLogoFile) callback(null, newLogoFile)
} else { } else {
newLogoFile = req.files.logo newLogoFile = req.files.logo
newLogoFile.mv(logoDir + newLogoFile.name, function(err:any) { newLogoFile.mv(logoDir + newLogoFile.name, function (err: any) {
newLogoFile = logoDir + newLogoFile.name newLogoFile = logoDir + newLogoFile.name
callback(err, newLogoFile) callback(err, newLogoFile)
}) })
} }
}, },
async function(newLogoFile:any){ // update gitlab page async function (newLogoFile: any) { // update gitlab page
let updatedPages = await gitlab.updateProject(updatedInformation, newLogoFile) const updatedPages = await gitlab.updateProject(updatedInformation, newLogoFile)
if (updatedPages.status) { if (updatedPages.status) {
if(updatedPages.data.message.name == "has already been taken") { if (updatedPages.data.message.name == 'has already been taken') {
res.flash("error", "Der Projektname '"+projectName+"' ist bereits vergeben, bitte wählen Sie einen anderen Namen.") res.flash('error', "Der Projektname '" + projectName + "' ist bereits vergeben, bitte wählen Sie einen anderen Namen.")
} else { } else {
res.flash("error", "Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut. ") res.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut. ')
} }
} else { } else {
updatedInformation.setLogo(updatedPages.avatar_url) updatedInformation.setLogo(updatedPages.avatar_url)
updatedInformation.setPath(updatedPages.path) updatedInformation.setPath(updatedPages.path)
res.flash("success", "Ihre Website wurde aktualisiert") res.flash('success', 'Ihre Website wurde aktualisiert')
} }
res.redirect('/account/updateInformation?id='+updatedInformation.getId()) res.redirect('/account/updateInformation?id=' + updatedInformation.getId())
} }
], function (err) { ], function (err) {
if(err) console.log(err) if (err != null) console.log(err)
if(newLogoFile){ // remove logo if (newLogoFile) { // remove logo
fs.unlink(newLogoFile, (err) => { fs.unlink(newLogoFile, (err) => {
if(err) console.log(err) if (err != null) console.log(err)
}) })
} }
}) })
...@@ -566,29 +563,29 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -566,29 +563,29 @@ export = function (app:any, config:any, passport:any, lang:string) {
} }
}) })
app.delete('/deleteProject', async function(req:any, res:any){ app.delete('/deleteProject', async function (req: any, res: any) {
if( !req.isAuthenticated() ) { if (!req.isAuthenticated()) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let loggedInUser = await getLoggedInUserData(req.user.email) const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { if (loggedInUser == null) {
res.redirect('/login') res.redirect('/login')
} else { } else {
let projectId = req.body.id const projectId = req.body.id
if (projectId) { if (projectId) {
// check if the owner is valid // check if the owner is valid
let project = await gitlab.getProjectById(projectId) const project = await gitlab.getProjectById(projectId)
if (!project) { if (!project) {
console.log(" ========= Error or no project found") console.log(' ========= Error or no project found')
} else if (!project.owner) { } else if (!project.owner) {
console.log(" ========= Project cannot be accessed, since it does not have an owner") console.log(' ========= Project cannot be accessed, since it does not have an owner')
} else if (project.owner.id != loggedInUser.getGitlabUserId()) { } else if (project.owner.id != loggedInUser.getGitlabUserId()) {
console.log(" ========= Access denied: Not your project") console.log(' ========= Access denied: Not your project')
} else { } else {
let isDeleted = await gitlab.deleteProjectById(projectId) const isDeleted = await gitlab.deleteProjectById(projectId)
if (!isDeleted) { if (!isDeleted) {
res.flash("error", "Project cannot be deleted. Please try again.") res.flash('error', 'Project cannot be deleted. Please try again.')
} }
} }
} }
...@@ -596,5 +593,4 @@ export = function (app:any, config:any, passport:any, lang:string) { ...@@ -596,5 +593,4 @@ export = function (app:any, config:any, passport:any, lang:string) {
} }
} }
}) })
}
}
\ No newline at end of file
...@@ -4,19 +4,18 @@ import methods from '../functions/methods' ...@@ -4,19 +4,18 @@ import methods from '../functions/methods'
import mailer from '../config/mailer' import mailer from '../config/mailer'
import constants from '../config/const' import constants from '../config/const'
const saltRounds:number = 10 const saltRounds: number = 10
const salt:number = 64 const salt: number = 64
export = function (app:any, config:any, lang:string) {
export = function (app: any, config: any, lang: string) {
// ================== NEW USERS REGISTRATION ====================== // ================== NEW USERS REGISTRATION ======================
app.get('/registration', function(req:any, res:any) { app.get('/registration', function (req: any, res: any) {
res.render(lang+'/account/registration') res.render(lang + '/account/registration')
}) })
app.post('/registration', function(req:any, res:any) { app.post('/registration', function (req: any, res: any) {
// user data // user data
let curDate:Date = new Date() const curDate: Date = new Date()
let userData:any = { const userData: any = {
salutation: req.body.inputSalutation, salutation: req.body.inputSalutation,
title: req.body.inputTitle, title: req.body.inputTitle,
firstname: req.body.inputFirstname, firstname: req.body.inputFirstname,
...@@ -25,172 +24,171 @@ export = function (app:any, config:any, lang:string) { ...@@ -25,172 +24,171 @@ export = function (app:any, config:any, lang:string) {
organisation: req.body.inputOrganisation, organisation: req.body.inputOrganisation,
industry: req.body.inputIndustry, industry: req.body.inputIndustry,
speciality: req.body.inputSpeciality, speciality: req.body.inputSpeciality,
createdDate: curDate.toISOString().slice(0,10) createdDate: curDate.toISOString().slice(0, 10)
} }
let userEmail:any = userData.email const userEmail: any = userData.email
let pos:number = userEmail.indexOf('@') const pos: number = userEmail.indexOf('@')
let emailLength:number = userEmail.length const emailLength: number = userEmail.length
let emailDomain:any = userEmail.slice(pos, emailLength); const emailDomain: any = userEmail.slice(pos, emailLength)
if ( emailDomain.toLowerCase() == "@hft-stuttgart.de") { if (emailDomain.toLowerCase() == '@hft-stuttgart.de') {
res.flash('error', "Fehlgeschlagen: HFT-Account") res.flash('error', 'Fehlgeschlagen: HFT-Account')
res.redirect('/account/registration') res.redirect('/account/registration')
} else { } else {
async.waterfall([ async.waterfall([
function(done:any) { function (done: any) {
// generate token // generate token
let token:string = ''; let token: string = ''
let randomChars:string = 'abcdefghijklmnopqrstuvwxyz0123456789'; const randomChars: string = 'abcdefghijklmnopqrstuvwxyz0123456789'
for ( let i = 0; i<40; i++ ) { for (let i = 0; i < 40; i++) {
token += randomChars.charAt(Math.floor(Math.random() * randomChars.length)); token += randomChars.charAt(Math.floor(Math.random() * randomChars.length))
} }
// encrypt password // encrypt password
bcrypt.genSalt(saltRounds, function(err, salt) { bcrypt.genSalt(saltRounds, function (err, salt) {
bcrypt.hash(req.body.inputPassword, salt, function(err:any, hash:any) { bcrypt.hash(req.body.inputPassword, salt, function (err: any, hash: any) {
let newAccount:any = { const newAccount: any = {
profile: userData, profile: userData,
password: hash, password: hash,
verificationToken: token verificationToken: token
} }
done(err, newAccount) done(err, newAccount)
}); })
}); })
}, },
// save data // save data
function(newAccount:any, err:any) { function (newAccount: any, err: any) {
methods.registerNewUser(newAccount, function(err:any){ methods.registerNewUser(newAccount, function (err: any) {
if (err) { if (err) {
res.flash('error', "Fehlgeschlagen") res.flash('error', 'Fehlgeschlagen')
} } else {
else {
// send email // send email
let emailSubject = "Bitte bestätigen Sie Ihr M4_LAB Benutzerkonto" const emailSubject = 'Bitte bestätigen Sie Ihr M4_LAB Benutzerkonto'
let emailContent = '<div>Lieber Nutzer,<br/><br/>' + const emailContent = '<div>Lieber Nutzer,<br/><br/>' +
'<p>vielen Dank für Ihre Anmeldung am Transferportal der HFT Stuttgart. <br/>' + '<p>vielen Dank für Ihre Anmeldung am Transferportal der HFT Stuttgart. <br/>' +
'Um Ihre Anmeldung zu bestätigen, klicken Sie bitte <a href='+config.app.host+'/verifyAccount?token='+newAccount.verificationToken+'>diesen Link</a> ' + 'Um Ihre Anmeldung zu bestätigen, klicken Sie bitte <a href=' + config.app.host + '/verifyAccount?token=' + newAccount.verificationToken + '>diesen Link</a> ' +
'<br/><br/>' + '<br/><br/>' +
'Ohne Bestätigung Ihres Kontos müssen wir Ihr Konto leider nach 7 Tagen löschen.</p><br/>' + constants.mailSignature + 'Ohne Bestätigung Ihres Kontos müssen wir Ihr Konto leider nach 7 Tagen löschen.</p><br/>' + constants.mailSignature +
'</div>'; '</div>'
mailer.options.to = req.body.inputEmail; mailer.options.to = req.body.inputEmail
mailer.options.subject = emailSubject; mailer.options.subject = emailSubject
mailer.options.html = emailContent; mailer.options.html = emailContent
mailer.transporter.sendMail(mailer.options, function(err:any) { mailer.transporter.sendMail(mailer.options, function (err: any) {
if (err) { if (err) {
console.error('Cannot send email. [Error] '+err) console.error('Cannot send email. [Error] ' + err)
throw err throw err
} }
}) })
// user feedback // user feedback
res.flash('success', 'Vielen Dank für Ihre Registrierung!'+'\r\n\r\n'+ 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'+ '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.') 'Wenn Sie die Mail nicht in ihrem Postfach vorfinden, prüfen Sie bitte auch Ihren Spam-Ordner.')
} }
res.redirect('/account/registration') res.redirect('/account/registration')
}) })
} }
]) ])
} }
}) })
// to check whether or not an account is already exist // to check whether or not an account is already exist
app.get('/email/:email', async function(req:any, res:any) { app.get('/email/:email', async function (req: any, res: any) {
let user = await methods.checkUserEmail(req.params.email) const user = await methods.checkUserEmail(req.params.email)
if (!user) { if (!user) {
console.log('No user found: '+req.params.email) console.log('No user found: ' + req.params.email)
res.send(true) res.send(true)
} else { } else {
console.log('User found: '+req.params.email) console.log('User found: ' + req.params.email)
res.send(false) res.send(false)
} }
}) })
// =================== USERS VERIFICATION ========================= // =================== USERS VERIFICATION =========================
app.get("/verifyAccount", async function(req:any, res:any){ app.get('/verifyAccount', async function (req: any, res: any) {
let userId:number = await methods.getUserIdByVerificationToken(req.query.token) const userId: number = await methods.getUserIdByVerificationToken(req.query.token)
if (!userId) { if (!userId) {
// no user found // no user found
res.render(lang+'/account/verification', { res.render(lang + '/account/verification', {
status: null status: null
}) })
} else { } else {
// a user found, verify the account // a user found, verify the account
let userData:any = { const userData: any = {
id: userId, id: userId,
verificationStatus: 1 verificationStatus: 1
} }
methods.verifyUserAccount(userData, async function(err:any){ methods.verifyUserAccount(userData, async function (err: any) {
if (err) { if (err) {
console.log("Error: "+err) console.log('Error: ' + err)
res.render(lang+'/account/verification', { res.render(lang + '/account/verification', {
status: false status: false
}); })
} else { } else {
// send welcome email after successful account verification // send welcome email after successful account verification
let userEmail:string = await methods.getUserEmailById(userId) const userEmail: string = await methods.getUserEmailById(userId)
if (!userEmail) { if (!userEmail) {
res.render(lang+'/account/verification', { res.render(lang + '/account/verification', {
status: false status: false
}) })
} else { } else {
// send email // send email
let emailSubject = "Herzlich willkommen"; const emailSubject = 'Herzlich willkommen'
let emailContent = '<div>Lieber Nutzer,<br/><br/>' + const emailContent = '<div>Lieber Nutzer,<br/><br/>' +
'<p>herzlich willkommen beim Transferportal der HFT Stuttgart!<br/>' + '<p>herzlich willkommen beim Transferportal der HFT Stuttgart!<br/>' +
'Sie können nun alle Dienste des Portals nutzen.<p/><br/>' + constants.mailSignature; 'Sie können nun alle Dienste des Portals nutzen.<p/><br/>' + constants.mailSignature
mailer.options.to = userEmail; mailer.options.to = userEmail
mailer.options.subject = emailSubject; mailer.options.subject = emailSubject
mailer.options.html = emailContent; mailer.options.html = emailContent
mailer.transporter.sendMail(mailer.options, function(err:any) { mailer.transporter.sendMail(mailer.options, function (err: any) {
if (err) { if (err) {
console.log('cannot send email'); console.log('cannot send email')
throw err; throw err
} }
}) })
res.render(lang+'/account/verification', { res.render(lang + '/account/verification', {
status: true status: true
}) })
} }
} }
}) })
} }
}) })
// ==================== FORGOT PASSWORD =========================== // ==================== FORGOT PASSWORD ===========================
app.get('/forgotPwd', function (req:any, res:any) { app.get('/forgotPwd', function (req: any, res: any) {
res.render(lang+'/account/forgotPwd', { res.render(lang + '/account/forgotPwd', {
user: req.user user: req.user
}) })
}) })
app.post('/forgotPwd', function(req:any, res:any) { app.post('/forgotPwd', function (req: any, res: any) {
let emailAddress = req.body.inputEmail const emailAddress = req.body.inputEmail
async.waterfall([ async.waterfall([
async function(done:any) { async function (done: any) {
let user = await methods.checkUserEmail(emailAddress) const user = await methods.checkUserEmail(emailAddress)
if (!user) { if (!user) {
console.log('No user found: '+emailAddress) console.log('No user found: ' + emailAddress)
} else { } else {
// generate token // generate token
let token:string = ''; let token: string = ''
let randomChars:string = 'abcdefghijklmnopqrstuvwxyz0123456789'; const randomChars: string = 'abcdefghijklmnopqrstuvwxyz0123456789'
for ( let i = 0; i<40; i++ ) { for (let i = 0; i < 40; i++) {
token += randomChars.charAt(Math.floor(Math.random() * randomChars.length)); token += randomChars.charAt(Math.floor(Math.random() * randomChars.length))
} }
let emailSubject = "Ihre Passwort-Anfrage an das Transferportal der HFT Stuttgart"; const emailSubject = 'Ihre Passwort-Anfrage an das Transferportal der HFT Stuttgart'
let emailContent = '<div>Lieber Nutzer,<br/><br/>' + const emailContent = '<div>Lieber Nutzer,<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/>' + '<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: '+config.app.host+'/reset/' + token + '<br/>' + 'Sie können Ihr Passwort mit dem Klick auf diesen Link ändern: ' + config.app.host + '/reset/' + token + '<br/>' +
'Dieser Link ist aus Sicherheitsgründen nur für 1 Stunde gültig.<br/></p>' + constants.mailSignature + '</div>' 'Dieser Link ist aus Sicherheitsgründen nur für 1 Stunde gültig.<br/></p>' + constants.mailSignature + '</div>'
let credentialData = { const credentialData = {
user_id: user.id, user_id: user.id,
resetPasswordToken: token, resetPasswordToken: token,
resetPasswordExpires: Date.now() + 3600000 // 1 hour resetPasswordExpires: Date.now() + 3600000 // 1 hour
} }
let result = await methods.updateCredential(credentialData) const result = await methods.updateCredential(credentialData)
if (!result) { if (!result) {
console.log('failed to update credential') console.log('failed to update credential')
} else { } else {
...@@ -198,18 +196,17 @@ export = function (app:any, config:any, lang:string) { ...@@ -198,18 +196,17 @@ export = function (app:any, config:any, lang:string) {
mailer.options.to = emailAddress mailer.options.to = emailAddress
mailer.options.subject = emailSubject mailer.options.subject = emailSubject
mailer.options.html = emailContent mailer.options.html = emailContent
mailer.transporter.sendMail(mailer.options, function(err:any) { mailer.transporter.sendMail(mailer.options, function (err: any) {
if (err) { console.error(err) } if (err) { console.error(err) }
}) })
} }
} }
done(null) done(null)
} }
], function(err:any) { ], function (err: any) {
if (err) { if (err) {
res.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.') res.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.')
} } else {
else {
res.flash('success', 'Wenn Ihre E-Mail-Adresse registriert ist, wurde eine E-Mail mit dem weiteren Vorgehen an ' + emailAddress + ' versendet.') 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') res.redirect('/account/forgotPwd')
...@@ -217,89 +214,86 @@ export = function (app:any, config:any, lang:string) { ...@@ -217,89 +214,86 @@ export = function (app:any, config:any, lang:string) {
}) })
// reset // reset
app.get('/reset/:token', async function(req:any, res:any) { app.get('/reset/:token', async function (req: any, res: any) {
let user = await methods.getUserByToken(req.params.token) const user = await methods.getUserByToken(req.params.token)
if (!user) { if (!user) {
res.flash('error', 'Der Schlüssel zum zurücksetzen des Passworts ist ungültig oder abgelaufen.') res.flash('error', 'Der Schlüssel zum zurücksetzen des Passworts ist ungültig oder abgelaufen.')
res.redirect('/account/forgotPwd') res.redirect('/account/forgotPwd')
} else { } else {
res.render(lang+'/account/reset') res.render(lang + '/account/reset')
} }
}) })
app.post('/reset/:token', async function(req:any, res:any) { app.post('/reset/:token', async function (req: any, res: any) {
let newPwd = req.body.inputNewPwd const newPwd = req.body.inputNewPwd
let user = await methods.getUserByToken(req.params.token)
if (!user) {
res.flash('error', "User not found.")
res.redirect('/login')
} else {
// encrypt password
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(newPwd, salt, async function(err:any, hash) {
let credentialData = {
password: hash,
user_id: user.user_id,
resetPasswordToken: null,
resetPasswordExpires: null
}
// update password
let result = await methods.updateCredential(credentialData)
if (!result) {
console.log('Failed to reset password')
res.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.")
} else {
res.flash('success', "Passwort aktualisiert!")
// send notification email
mailer.options.to = user.email
mailer.options.subject = constants.updatePasswordMailSubject
mailer.options.html = constants.updatePasswordMailContent+'<div>'+constants.mailSignature+'</div>'
mailer.transporter.sendMail(mailer.options, function(err:any) {
if (err) { console.log(err) }
})
}
res.redirect('/login')
});
});
}
const user = await methods.getUserByToken(req.params.token)
if (!user) {
res.flash('error', 'User not found.')
res.redirect('/login')
} else {
// encrypt password
bcrypt.genSalt(saltRounds, function (err, salt) {
bcrypt.hash(newPwd, salt, async function (err: any, hash) {
const credentialData = {
password: hash,
user_id: user.user_id,
resetPasswordToken: null,
resetPasswordExpires: null
}
// update password
const result = await methods.updateCredential(credentialData)
if (!result) {
console.log('Failed to reset password')
res.flash('error', 'Datenbankfehler: Passwort kann nicht geändert werden.')
} else {
res.flash('success', 'Passwort aktualisiert!')
// send notification email
mailer.options.to = user.email
mailer.options.subject = constants.updatePasswordMailSubject
mailer.options.html = constants.updatePasswordMailContent + '<div>' + constants.mailSignature + '</div>'
mailer.transporter.sendMail(mailer.options, function (err: any) {
if (err) { console.log(err) }
})
}
res.redirect('/login')
})
})
}
}) })
// ======================= CONTACT FORM =========================== // ======================= CONTACT FORM ===========================
app.get('/contact', function (req:any, res:any) { app.get('/contact', function (req: any, res: any) {
res.render(lang+'/account/contact', { res.render(lang + '/account/contact', {
user: req.user user: req.user
}) })
}) })
app.post('/contact', function(req:any, res:any, next:any) { app.post('/contact', function (req: any, res: any, next: any) {
//methods.currentDate(); // methods.currentDate();
let emailAddress = req.body.inputEmail; const emailAddress = req.body.inputEmail
let supportAddress = "support-transfer@hft-stuttgart.de"; const supportAddress = 'support-transfer@hft-stuttgart.de'
let inputName = req.body.name; const inputName = req.body.name
let inputContent = req.body.message; const inputContent = req.body.message
let emailSubject = "Ihre Anfrage an das Transferportal"; const emailSubject = 'Ihre Anfrage an das Transferportal'
let emailContent = "<div>Es wurde eine Anfrage an das Transferportal gestellt: <br/><br/>NAME: " + inputName + "<br/>NACHRICHT: "+ inputContent+"</div>"; const emailContent = '<div>Es wurde eine Anfrage an das Transferportal gestellt: <br/><br/>NAME: ' + inputName + '<br/>NACHRICHT: ' + inputContent + '</div>'
async.waterfall([ async.waterfall([
function(done:any) { function (done: any) {
// send email // send email
mailer.options.to = supportAddress; mailer.options.to = supportAddress
mailer.options.cc = emailAddress; mailer.options.cc = emailAddress
mailer.options.subject = emailSubject; mailer.options.subject = emailSubject
mailer.options.html = emailContent; mailer.options.html = emailContent
mailer.transporter.sendMail(mailer.options, function(err:any) { mailer.transporter.sendMail(mailer.options, function (err: any) {
done(err, 'done'); done(err, 'done')
});
}
], function(err:any) {
if (err) {
console.error(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')
}) })
}
], function (err: any) {
if (err) {
console.error(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')
})
}) })
}
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment