import async from 'async' import bcrypt from 'bcryptjs' import { mailer } from '../config/mailer' import { miscConst } from '../config/const' import { dbController } from './dbController' const saltRounds: number = 10 const publicController = { showRegistrationPage: function (res: any, lang: String) { res.render(lang + '/account/registration') }, showContactPage: function (req: any, res: any, lang: String) { res.render(lang + '/account/contact', { user: req.user }) }, showForgotPwdPage: function (req: any, res: any, lang: String) { res.render(lang + '/account/forgotPwd', { user: req.user }) }, showResetPassword: async function (req: any, res: any, lang: String) { const user = await dbController.getUserByToken(req.params.token) if (user) { res.render(lang + '/account/reset') } else { res.flash('error', 'Der Schlüssel zum zurücksetzen des Passworts ist ungültig oder abgelaufen.') res.redirect('/account/forgotPwd') } }, sendContactMessage: function (req: any, res: any) { const emailAddress = req.body.inputEmail const supportAddress = 'support-transfer@hft-stuttgart.de' const inputName = req.body.name const inputContent = req.body.message const emailSubject = 'Ihre Anfrage an das Transferportal' const emailContent = '
Es wurde eine Anfrage an das Transferportal gestellt:

NAME: ' + inputName + '
NACHRICHT: ' + inputContent + '
' async.waterfall([ function (done: any) { // send email mailer.options.to = supportAddress mailer.options.cc = emailAddress mailer.options.subject = emailSubject mailer.options.html = emailContent mailer.transporter.sendMail(mailer.options, function (err: any) { done(err, 'done') }) } ], function (err: any) { if (!err) { res.flash('success', 'Vielen Dank für Ihre Anfrage. Wir melden uns baldmöglichst bei Ihnen. Eine Kopie Ihrer Anfrage wurde an ' + emailAddress + ' versandt.') } else { console.error(err) res.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.') } res.redirect('/account/contact') }) }, registerUser: function (req: any, res: any, config: any) { // user data const curDate: Date = new Date() const userData: any = { 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) } const userEmail: any = userData.email const pos: number = userEmail.indexOf('@') const emailLength: number = userEmail.length const emailDomain: any = userEmail.slice(pos, emailLength) if (emailDomain.toLowerCase() === '@hft-stuttgart.de') { res.flash('error', 'Fehlgeschlagen: HFT-Account') res.redirect('/account/registration') } else { async.waterfall([ function (done: any) { // generate token let token: string = '' const randomChars: string = 'abcdefghijklmnopqrstuvwxyz0123456789' for (let i = 0; i < 40; i++) { token += randomChars.charAt(Math.floor(Math.random() * randomChars.length)) } // encrypt password bcrypt.genSalt(saltRounds, function (err, salt) { bcrypt.hash(req.body.inputPassword, salt, function (err: any, hash: any) { const newAccount: any = { profile: userData, password: hash, verificationToken: token } done(err, newAccount) }) }) }, // save data function (newAccount: any, err: any) { dbController.registerNewUser(newAccount, function (err: any) { if (err) { res.flash('error', 'Fehlgeschlagen') } else { // send email const emailSubject = 'Bitte bestätigen Sie Ihr M4_LAB Benutzerkonto' const emailContent = '
Lieber Nutzer,

' + '

vielen Dank für Ihre Anmeldung am Transferportal der HFT Stuttgart.
' + 'Um Ihre Anmeldung zu bestätigen, klicken Sie bitte diesen Link ' + '

' + 'Ohne Bestätigung Ihres Kontos müssen wir Ihr Konto leider nach 7 Tagen löschen.


' + String(miscConst.mailSignature) + '
' mailer.options.to = req.body.inputEmail mailer.options.subject = emailSubject mailer.options.html = emailContent mailer.transporter.sendMail(mailer.options, function (err: any) { if (err) { console.error('Cannot send email. [Error] ' + String(err)) 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') }) } ]) } }, verifyAccount: async function (req: any, res: any, lang: String) { const userId: number = await dbController.getUserIdByVerificationToken(req.query.token) if (!userId) { // no user found res.render(lang + '/account/verification', { status: null }) } else { // a user found, verify the account const userData: any = { id: userId, verificationStatus: 1 } dbController.verifyUserAccount(userData, async function (err: any) { if (err) { console.error(err) res.render(lang + '/account/verification', { status: false }) } else { // send welcome email after successful account verification const userEmail: string = await dbController.getUserEmailById(userId) if (!userEmail) { res.render(lang + '/account/verification', { status: false }) } else { // send email const emailSubject = 'Herzlich willkommen' const emailContent = '
Lieber Nutzer,

' + '

herzlich willkommen beim Transferportal der HFT Stuttgart!
' + 'Sie können nun alle Dienste des Portals nutzen.


' + miscConst.mailSignature mailer.options.to = userEmail mailer.options.subject = emailSubject mailer.options.html = emailContent mailer.transporter.sendMail(mailer.options, function (err: any) { if (err) { console.log('cannot send email') throw err } }) res.render(lang + '/account/verification', { status: true }) } } }) } }, resetPassword: async function (req: any, res: any) { const newPwd = req.body.inputNewPwd const user = await dbController.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 dbController.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 = miscConst.updatePasswordMailSubject mailer.options.html = miscConst.updatePasswordMailContent + '

' + miscConst.mailSignature + '
' mailer.transporter.sendMail(mailer.options, function (err: any) { if (err) { console.log(err) } }) } res.redirect('/login') }) }) } }, generateNewToken: function (req: any, res: any, config: any) { const emailAddress = req.body.inputEmail async.waterfall([ async function (done: any) { const user = await dbController.checkUserEmail(emailAddress) if (!user) { console.log('No user found: ' + String(emailAddress)) } else { // generate token let token: string = '' const randomChars: string = 'abcdefghijklmnopqrstuvwxyz0123456789' for (let i = 0; i < 40; i++) { token += randomChars.charAt(Math.floor(Math.random() * randomChars.length)) } const emailSubject = 'Ihre Passwort-Anfrage an das Transferportal der HFT Stuttgart' const emailContent = '
Lieber Nutzer,

' + '

wir haben Ihre Anfrage zur Erneuerung Ihres Passwortes erhalten. Falls Sie diese Anfrage nicht gesendet haben, ignorieren Sie bitte diese E-Mail.

' + 'Sie können Ihr Passwort mit dem Klick auf diesen Link ändern: ' + String(config.app.host) + '/reset/' + String(token) + '
' + 'Dieser Link ist aus Sicherheitsgründen nur für 1 Stunde gültig.

' + String(miscConst.mailSignature) + '
' const credentialData = { user_id: user.id, resetPasswordToken: token, resetPasswordExpires: Date.now() + 3600000 // 1 hour } const result = await dbController.updateCredential(credentialData) if (!result) { console.log('failed to update credential') } else { // send email mailer.options.to = emailAddress mailer.options.subject = emailSubject mailer.options.html = emailContent mailer.transporter.sendMail(mailer.options, function (err: any) { if (err) { console.error(err) } }) } } done(null) } ], function (err: any) { 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 ' + String(emailAddress) + ' versendet.') } res.redirect('/account/forgotPwd') }) }, checkUserEmail: async function (req: any, res: any) { const user = await dbController.checkUserEmail(req.params.email) if (user) { res.send(false) } else { res.send(true) } } } export { publicController }