public.ts 11.6 KB
Newer Older
Rosanny Sihombing's avatar
Rosanny Sihombing committed
1
2
3
4
5
6
7
8
9
10
11
12
13
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
83
84
85
86
87
88
89
90
91
92
93
94
import async from 'async'
import bcrypt from 'bcryptjs'
import methods from '../functions/methods'
import mailer from '../config/mailer'
import constants from '../config/const'

const saltRounds:number = 10
const salt:number = 64

export = function (app:any, config:any, lang:string) {

  // ================== NEW USERS REGISTRATION ======================
  app.get('/registration', function(req:any, res:any) {
    res.render(lang+'/account/registration')
  })
  app.post('/registration', function(req:any, res:any) {
    // user data
    var curDate:Date = new Date()
    var 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)
    }
    
    var userEmail:any = userData.email
    var pos:number = userEmail.indexOf('@')
    var emailLength:number = userEmail.length
    var 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 = '';
          let 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) {
              var newAccount:any = {
                profile: userData,
                password: hash,
                verificationToken: token
              }
              done(err, newAccount)
            });
          });
        },
        // save data
        function(newAccount:any, err:any) {
          methods.registerNewUser(newAccount, function(err:any){
            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='+newAccount.verificationToken+'>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.transporter.sendMail(mailer.options, function(err:any) {
                if (err) {
                  console.error('Cannot send email. [Error] '+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')
            })
        }
      ])
    }
  })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
95
96
97
98
99
100
101
102
103
104
105
  // to check whether or not an account is already exist
  app.get('/email/:email', async function(req:any, res:any) {
    let user = await methods.checkUserEmail(req.params.email)
      if (!user) {
        console.log('No user found: '+req.params.email)
        res.send(true)
      } else {
        console.log('User found: '+req.params.email)
        res.send(false)
      }
  })
Rosanny Sihombing's avatar
Rosanny Sihombing committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303

  // =================== USERS VERIFICATION =========================

  app.get("/verifyAccount", async function(req:any, res:any){
    let userId:number = 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:any = {
        id: userId,
        verificationStatus: 1
      }
      methods.verifyUserAccount(userData, async function(err:any){
        if (err) {
          console.log("Error: "+err)
          res.render(lang+'/account/verification', {
            status: false
          });
        } else {
          // send welcome email after successful account verification
          let userEmail:string = await methods.getUserEmailById(userId)
          if (!userEmail) {
            res.render(lang+'/account/verification', {
              status: false
            })
          } 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.transporter.sendMail(mailer.options, function(err:any) {
                if (err) {
                  console.log('cannot send email')
                  throw err
                }
              })
  
              res.render(lang+'/account/verification', {
                status: true
              })
          }
        }
      })        
    }
  })

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

  app.get('/forgotPwd', function (req:any, res:any) {
    res.render(lang+'/account/forgotPwd', {
      user: req.user
    })
  })
  app.post('/forgotPwd', function(req:any, res:any) {
    let emailAddress = req.body.inputEmail
    async.waterfall([
      async function(done:any) {
        let user = await methods.checkUserEmail(emailAddress)
        if (!user) {
          console.log('No user found: '+emailAddress)
        } else {
          // generate token
          let token:string = '';
          let randomChars:string = 'abcdefghijklmnopqrstuvwxyz0123456789';
          for ( let i = 0; i<40; i++ ) {
            token += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
          }

          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>'
            
          var credentialData = {
            user_id: user.id,
            resetPasswordToken: token,
            resetPasswordExpires: Date.now() + 3600000 // 1 hour
          }
          let result = await methods.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 ' + emailAddress + ' versendet.')
      }
      res.redirect('/account/forgotPwd')
    })
  })

  // reset
  app.get('/reset/:token', async function(req:any, res:any) {
      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')
      }
  })
  app.post('/reset/:token', async function(req:any, res:any) {
      var newPwd = req.body.inputNewPwd

      var 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) {
            var credentialData = {
              password: hash,
              user_id: user.user_id
            }
            // 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 notifiaction 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 ===========================
  app.get('/contact', function (req:any, res:any) {
      res.render(lang+'/account/contact', {
        user: req.user
      })
  })
  app.post('/contact', function(req:any, res:any, next:any) {
        //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:any) {
            // send email
            mailer.options.to = supportAddress;
            mailer.options.cc = emailAddress;
            mailer.options.subject = emailSubject;
            mailer.options.text = emailContent;
            mailer.transporter.sendMail(mailer.options, function(err:any) {
              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')
        })
  })
 
}