public.js 11.4 KB
Newer Older
Rosanny Sihombing's avatar
Rosanny Sihombing committed
1
2
3
4
5
6
7
8
9
10
11
12
const methods = require('../functions/methods')
const async = require('async')
const mailer = require('../config/mailer')
const constants = require('../config/const')
// pwd encryption
const crypto = require('crypto')
const bcrypt = require('bcryptjs')
const saltRounds = 10
const salt = 64

module.exports = function (app, config, lang) {

Rosanny Sihombing's avatar
Rosanny Sihombing committed
13
    // ================== NEW USERS REGISTRATION ======================
Rosanny Sihombing's avatar
Rosanny Sihombing committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

    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 = '<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 <a href='+config.app.host+'/verifyAccount?token='+token+'>diesen Link</a> ' +
                    '<br/><br/>' +
                    'Ohne Bestätigung Ihres Kontos müssen wir Ihr Konto leider nach 7 Tagen löschen.</p><br/>' + constants.mailSignature +
                    '</div>';
                  mailer.options.to = req.body.inputEmail;
                  mailer.options.subject = emailSubject;
                  mailer.options.html = emailContent;
                  mailer.transport.sendMail(mailer.options, function(err) {
                    if (err) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
83
                      console.error('cannot send email')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
                      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')
              })
            }
          ])
        }
    })

Rosanny Sihombing's avatar
Rosanny Sihombing committed
99
100
    // =================== USERS VERIFICATION =========================

Rosanny Sihombing's avatar
Rosanny Sihombing committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    app.get("/verifyAccount", async function(req, res){
      let userId = await methods.getUserIdByVerificationToken(req.query.token)
      if (!userId) {
        // no user found
        res.render(lang+'/account/verification', {
          status: null
        })
      } else {
        // a user found, verify the account
        let userData = {
          id: userId,
          verificationStatus: 1
        }
        methods.verifyUserAccount(userData, async function(err){
          if (err) {
            console.log("Error: "+err)
            res.render(lang+'/account/verification', {
              status: false
            });
          } else {
            // send welcome email after successful account verification
            let userEmail = await methods.getUserEmailById(userId)
            if (!userEmail) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
124
125
126
              res.render(lang+'/account/verification', {
                status: false
              })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
            } 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/>' + constants.mailSignature;
                mailer.options.to = userEmail
                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
                })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
146
            }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
147
148
149
          }
        })        
      }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
150
151
152
153
154
155
156
157
158
    })

    // ==================== FORGOT PASSWORD ===========================

    app.get('/forgotPwd', function (req, res) {
      res.render(lang+'/account/forgotPwd', {
        user: req.user
      })
    })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
159
    app.post('/forgotPwd', function(req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
160
161
162
163
164
165
166
167
      let emailAddress = req.body.inputEmail
      async.waterfall([
        function(done) {
          crypto.randomBytes(20, function(err, buf) {
            var token = buf.toString('hex')
            done(err, token)
          })
        },
Rosanny Sihombing's avatar
Rosanny Sihombing committed
168
169
170
171
172
173
174
175
176
177
        async function(token) {
          let user = await methods.checkUserEmail(emailAddress)
          if (!user) {
            console.log('no user found')
          } else {
            var emailSubject = "Ihre Passwort-Anfrage an das Transferportal der HFT Stuttgart";
            var 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/>' +
              '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>'
Rosanny Sihombing's avatar
Rosanny Sihombing committed
178
              
Rosanny Sihombing's avatar
Rosanny Sihombing committed
179
180
181
182
            var credentialData = {
              user_id: user.id,
              resetPasswordToken: token,
              resetPasswordExpires: Date.now() + 3600000 // 1 hour
Rosanny Sihombing's avatar
Rosanny Sihombing committed
183
            }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
184
185
186
187
188
189
190
191
192
193
194
195
            methods.updateCredential(credentialData, function(err) {
              if (err) { console.error(err) }
            })
  
            // send email
            mailer.options.to = emailAddress
            mailer.options.subject = emailSubject
            mailer.options.html = emailContent
            mailer.transport.sendMail(mailer.options, function(err) {
              if (err) { console.error(err) }
            })
          }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
196
197
198
199
200
201
202
203
204
        }
      ], 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')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
205
      })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
206
207
208
    })

    // reset
Rosanny Sihombing's avatar
Rosanny Sihombing committed
209
210
211
212
213
214
215
216
    app.get('/reset/:token', async function(req, res) {
      let user = await methods.getUserByToken(req.params.token)
      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')
      }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
217
    })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
218
    app.post('/reset/:token', async function(req, res) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
219
      var newPwd = req.body.inputNewPwd
Rosanny Sihombing's avatar
Rosanny Sihombing committed
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

      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, 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 = constants.updatePasswordMailSubject
                mailer.options.html = constants.updatePasswordMailContent+'<div>'+constants.mailSignature+'</div>'
                mailer.transport.sendMail(mailer.options, function(err) {
                  if (err) { console.log(err) }
                })
                
                res.redirect('/login')
Rosanny Sihombing's avatar
Rosanny Sihombing committed
250
              }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
251
            })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
252
          });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
253
254
255
        });
      }

Rosanny Sihombing's avatar
Rosanny Sihombing committed
256
257
258
    })

    // ======================= CONTACT FORM ===========================
Rosanny Sihombing's avatar
Rosanny Sihombing committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280

    app.get('/contact', function (req, res) {
      res.render(lang+'/account/contact', {
        user: req.user
      })
    })
    app.post('/contact', function(req, res, next) {
        //methods.currentDate();
        let emailAddress = req.body.inputEmail;
        let supportAddress = "support-transfer@hft-stuttgart.de";
        let inputName = req.body.name;
        let inputContent = req.body.message;
        let emailContent = "Es wurde eine Anfrage an das Transferportal gestellt: \n\n NAME: " + inputName + "\n NACHRICHT:\n "+ inputContent;
        let emailSubject = "Ihre Anfrage an das Transferportal";
        async.waterfall([
          function(done) {
              // send email
              mailer.options.to = supportAddress;
              mailer.options.cc = emailAddress;
              mailer.options.subject = emailSubject;
              mailer.options.text = emailContent;
              mailer.transport.sendMail(mailer.options, function(err) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
281
282
                done(err, 'done');
              });
Rosanny Sihombing's avatar
Rosanny Sihombing committed
283
284
285
            }
        ], function(err) {
          if (err) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
286
            console.error(err)
Rosanny Sihombing's avatar
Rosanny Sihombing committed
287
288
289
290
291
292
293
294
295
296
            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')
        })
    })

}