account.ts 21.4 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
95
96
97
98
99
100
101
102
103
104
105
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
import fs from 'fs'
import async from 'async'
import bcrypt from 'bcryptjs'
import * as passportSaml from 'passport-saml'
import dbconn from '../config/dbconn'
import methods from '../functions/methods'
import gitlab from '../functions/gitlab'
import constants from '../config/const'
import mailer from '../config/mailer'
import portalUser from '../classes/user'
import projectInformation from '../classes/website'
import projectRepo from '../classes/repo'

const SamlStrategy = passportSaml.Strategy
const saltRounds = 10;
const salt = 64; // salt length
const logoDir = 'public/upload/'
const defaultLogo:any = 'public/default/logo.png'

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

  // =========== PASSPORT =======
  passport.serializeUser(function (user:any, done:any) {
    done(null, user);
  });

  passport.deserializeUser(function (user:any, done:any) {
    done(null, user);
  });

  var samlStrategy = new SamlStrategy({
      // URL that goes from the Identity Provider -> Service Provider
      callbackUrl: config.passport.saml.path,
      // Base address to call logout requests
      logoutUrl: config.passport.saml.logoutUrl,
      
      entryPoint: config.passport.saml.entryPoint,
      issuer: config.passport.saml.issuer,
      identifierFormat: undefined,
      
      // Service Provider private key
      decryptionPvk: fs.readFileSync(__dirname + '/cert/key.pem', 'utf8'),
      // Service Provider Certificate
      privateCert: fs.readFileSync(__dirname + '/cert/key.pem', 'utf8'),
      // Identity Provider's public key
      cert: fs.readFileSync(__dirname + '/cert/cert_idp.pem', 'utf8'),
      
      validateInResponseTo: false,
      disableRequestedAuthnContext: true
  },
  function (profile:any, done:any) {
    return done(null, {
      id: profile.nameID,
      idFormat: profile.nameIDFormat,
      email: profile.email,
      firstName: profile.givenName,
      lastName: profile.sn
    });
  });
  
  passport.use(samlStrategy);

  // ============= SAML ==============
  app.post(config.passport.saml.path,
    passport.authenticate(config.passport.strategy,
      {
        failureRedirect: '/account/',
        failureFlash: true
      }),
    function (req:any, res:any) {
      res.redirect('/account/');
    }
  );

  // to generate Service Provider's XML metadata
  app.get('/saml/metadata',
    function(req:any, res:any) {
      res.type('application/xml');
      var spMetadata = samlStrategy.generateServiceProviderMetadata(fs.readFileSync(__dirname + '/cert/cert.pem', 'utf8'));
      res.status(200).send(spMetadata);
    }
  );

  // ======== APP ROUTES - ACCOUNT ====================

  async function getLoggedInUserData(email:string) {
    let user = await methods.getUserByEmail(email)
    if (!user) {
      console.log('no user found')
      return null
    } else {
      let 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
      )
      
      let userGitlabId = await methods.getGitlabId(loggedInUser.id)
      if (userGitlabId) {
        loggedInUser.setGitlabUserId(userGitlabId)
      }
      return loggedInUser
    }
  }

  app.get('/', async function (req:any, res:any) {
    if ( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)
      
      res.render(lang+'/account/home', {
        user: loggedInUser
      });
    }
  });

  app.get('/login',
    passport.authenticate(config.passport.strategy, {
      successRedirect: '/',
      failureRedirect: '/login'
    })
  )

  app.get('/logout', function (req:any, res:any) {
    if (req.user == null) {
      return res.redirect('/');
    }

    req.user.nameID = req.user.id;
    req.user.nameIDFormat = req.user.idFormat;
    return samlStrategy.logout(req, function(err:any, uri:any) {
      req.logout();

      if ( req.session ) {
        req.session.destroy((err:any) => {
          if(err) {
              return console.log(err);
          }
        });
      }

      return res.redirect(uri);
    });
  });

  app.get('/profile', async function (req:any, res:any) {
    if ( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)
      if (!loggedInUser) { // null user
        res.redirect('/account/')
      } else {
        if(loggedInUser.getVerificationStatus() != 1) {
          res.redirect('/account/')
        } else {
          res.render(lang+'/account/profile', {
            user: loggedInUser
          })
        }
      }
      
    }
  })

  app.get('/services', async function(req:any, res:any){
    if( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)
      if (!loggedInUser) { // null user
        res.redirect('/account/')
      } else {
        if(loggedInUser.getVerificationStatus() != 1) { // unverified users
          res.redirect('/account/')
        } else {
          let gitlabReposArr = []
          let gitlabPagesArr = []
  
          if(loggedInUser.getGitlabUserId()) { // for users who have activated their gitlab account
            let userProjects = await gitlab.getUserProjects(loggedInUser.getGitlabUserId()!)
            if (!userProjects) {
              console.error("something went wrong")
              res.status(500).render(lang+'/500', { error: "something went wrong" })
            }
            
            let project:any
            for (project in userProjects) {
              if (userProjects[project].tag_list.includes('website')) {
                let page = {
                  projectInformation: new projectInformation(loggedInUser.getGitlabUserId()!, userProjects[project].name, userProjects[project].description,
                    userProjects[project].id, userProjects[project].avatar_url, userProjects[project].path_with_namespace),
                  pipelineStatus: await gitlab.getProjectPipelineLatestStatus(userProjects[project].id)
                }
                gitlabPagesArr.push(page)
              } else {
                let repo = new projectRepo(loggedInUser.getGitlabUserId()!, userProjects[project].name, userProjects[project].description,
                  userProjects[project].id, userProjects[project].avatar_url, userProjects[project].path_with_namespace)
                gitlabReposArr.push(repo)
              }
            }
  
            res.render(lang+'/account/services', {
              user: loggedInUser,
              gitlabRepos: gitlabReposArr,
              gitlabPages: gitlabPagesArr
            })
          } else { // for users who have not activated their gitlab account yet
            let gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail())
            if (!gitlabUser) {
              res.render(lang+'/account/services', {
                user: loggedInUser,
                gitlabRepos: null,
                gitlabPages: null
              })
            } else {
              let gitlabActivationData = {
                user_id: loggedInUser.getId(),
                gitlab_userId: gitlabUser.id}

              methods.addGitlabUser(gitlabActivationData, function(err:any){
                if(err) {
                  res.status(500).render(lang+'/500', { error: err })
                } else {
                  res.redirect('/account/services')
                }
              })
            }
          }
        }
      }
    }
  })

  app.get('/security', async function (req:any, res:any) {
    if ( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)
      if (!loggedInUser) { // null user
        res.redirect('/account/')
      } else {
        if(loggedInUser.getVerificationStatus() == 1 && loggedInUser.getIdpStatus() == 1) {
          res.render(lang+'/account/security', {
            user: loggedInUser
          })
        } else {
          res.redirect('/account/')
        }
      }
    }
  })

  app.post('/updateProfile', async function (req:any, res:any) {
    if ( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)
      if (!loggedInUser) { // null user
        res.redirect('/account/')
      } else {
        let 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,
        }
        let result = await methods.updateUserById(loggedInUser.getId(), userData)
        if (!result) {
          res.flash('error', "Failed")
        } else {
          loggedInUser.updateProfile(userData.salutation, userData.title, userData.firstname, userData.lastname, userData.email,
            userData.organisation, userData.industry, userData.speciality)
          res.flash('success', 'Ihr Benutzerprofil wurde aktualisiert!')
        }
        res.redirect('/account/profile')
      }
      
    }
  });

  app.post('/account/changePwd', async function (req:any, res:any) {
    if( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)

      if (!loggedInUser) { // null user
        res.redirect('/account/')
      } else {
        let currPwd = req.body.inputCurrPwd
        let newPwd = req.body.inputNewPwd
        let retypePwd = req.body.inputConfirm

        dbconn.user.query('SELECT password FROM credential WHERE user_id='+loggedInUser.getId(), function (err, rows, fields) {
          if (err) {
            console.error(err)
            res.status(500).render(lang+'/500', { error: err })
          }
          var userPwd = rows[0].password

          // check if the password is correct
          bcrypt.compare(currPwd, userPwd, function(err, isMatch) {
            if (err) {
              console.error(err)
              res.status(500).render(lang+'/500', { error: err })
            } else if (!isMatch) {
              res.flash('error', "Das Passwort ist leider falsch. Bitte überprüfen Sie Ihre Eingabe.")
              res.redirect('/account/security')
            } else {
              if ( newPwd != retypePwd ) {
                res.flash('error', 'Passwörter stimmen nicht überein. Bitte stellen Sie sicher, dass Sie das Passwort beide Male genau gleich eingeben.')
                res.redirect('/account/security')
              } else {
                // update password
                bcrypt.genSalt(saltRounds, function(err, salt) {
                  bcrypt.hash(newPwd, salt, async function(err, hash) {
                    var credentialData = {
                      password: hash,
                      user_id: loggedInUser!.getId()
                    }
                
                    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 = loggedInUser!.getEmail()
                      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('/account/security')

                  });
                });
              }
            }
          })
        })
      }
    }
  });
  
  app.get('/resendVerificationEmail', async function(req:any, res:any){
    if (!req.isAuthenticated) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)
      if (!loggedInUser) {
        res.redirect('/login')
      } else {
        let token = await methods.getVerificationTokenByUserId(loggedInUser.id)
        if (!token) {
          res.send(false)
        } 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 diesen Link: ' + config.app.host + '/verifyAccount?token=' + token +
            '<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 = loggedInUser.email;
          mailer.options.subject = emailSubject;
          mailer.options.html = emailContent;
          mailer.transport.sendMail(mailer.options, function(err:any) {
            if (err) {
              console.log('cannot send email')
              throw err
            }
          })
          res.send(true)
        }
      }
    }
  })

  // ============= NEW GITLAB PAGES ===========================
  
  app.get('/newInformation', async function(req:any, res:any){
    if ( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)
      if (!loggedInUser) {
        res.redirect('/login')
      } else {
        let gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail())
        if (!gitlabUser) { // no user found
          res.redirect('/account/services')
        } else {
          res.render(lang+'/account/newInformation', {
            user: loggedInUser,
            gitlabUsername: gitlabUser.username
          })
        }
      }
    }
  })
  app.post('/newInformation', async function(req:any, res:any) {
    if( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)
      if (!loggedInUser) {
        res.redirect('/login')
      } else {
        if (!req.body.name && !req.body.description) {
          res.flash('error', 'Bitte geben Sie die benötigten Daten ein')
          res.redirect('/account/newInformation')
        } else {
          let projectName = req.body.name.toLowerCase().replace(/\s/g, '-')
          let projectDesc = req.body.description
          let projectTemplate = req.body.template
          let newInformation = new projectInformation(loggedInUser.getGitlabUserId()!, projectName, projectDesc)
          let newLogoFile = defaultLogo
            
          if (req.files) { newLogoFile = req.files.logo }
  
          async.waterfall([
            function(callback:any){ // upload logo
              if (!req.files) {
                callback(null, newLogoFile)
              } else {
                newLogoFile.mv(logoDir + newLogoFile.name, function(err:any) {
                  newLogoFile = logoDir+newLogoFile.name
                  callback(err, newLogoFile)
                })
              }
            },
            async function(newLogoFile:any){ // create a new GitLab Page
              let newPages = await gitlab.createNewPages(newInformation, newLogoFile, projectTemplate)
              if (newPages.status) {
                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.")
                } else {
                  res.flash("error", "Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut. ")
                }
                res.redirect('/account/newInformation')
              } else {
                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.")
                res.redirect('/account/updateInformation?id='+newPages.id)
              }
            }
          ], function (err) {
            if(err) console.log(err)
            // remove logo
            if (req.files) {
              fs.unlink(newLogoFile, (err) => {
                if(err) console.log(err)
              })
            }
          })
        }
      }
    }
  })

  app.get('/updateInformation', async function(req:any, res:any){
    if( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)

      if (!loggedInUser) {
        res.redirect('/login')
      } else {
        if(!req.query.id) {
          res.redirect('/account/services')
        } else {
          let project = await gitlab.getProjectById(req.query.id)
          if (!project) {
            console.log(" ========= Error or no project found")
            res.redirect('/account/services')
          } else if (!project.owner) {
            console.log(" ========= Project cannot be accessed, since it does not have an owner")
            res.redirect('/account/services')
          } else if (project.owner.id != loggedInUser.getGitlabUserId()) {
            console.log(" ========= Access denied: Not your project")
            res.redirect('/account/services')
          } else {
            let curInformation = new projectInformation(loggedInUser.getGitlabUserId()!, project.name, project.description,
              req.query.id, project.avatar_url, project.path_with_namespace)
            
            res.render(lang+'/account/updateInformation', {
              user: loggedInUser,
              information: curInformation
            })
          }
        }
      }
    }
  })
  // update a website
  app.post('/updateInformation', async function(req:any, res:any){
    if( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)

      if (!loggedInUser) {
        res.redirect('/login')
      } else {
        if (!req.body.name && !req.body.description) {
          res.flash('error', 'Bitte geben Sie die benötigten Daten ein')
          res.redirect('/account/updateInformation')
        } else {
          let projectName = req.body.name.toLowerCase().replace(/\s/g, '-')
          let projectDesc = req.body.description
          let updatedInformation = new projectInformation(loggedInUser.getGitlabUserId()!, projectName, projectDesc, req.query.id)
          let newLogoFile:any
  
          async.waterfall([
            function(callback:any){ // upload logo
              if(!req.files) {
                callback(null, newLogoFile)
              } else {
                newLogoFile = req.files.logo
                newLogoFile.mv(logoDir + newLogoFile.name, function(err:any) {
                  newLogoFile = logoDir + newLogoFile.name
                  callback(err, newLogoFile)
                })
              }
            },
            async function(newLogoFile:any){ // update gitlab page
              let updatedPages = await gitlab.updateProject(updatedInformation, newLogoFile)
              
              if (updatedPages.status) {
                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.")
                } else {
                  res.flash("error", "Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut. ")
                }
              } else {
                updatedInformation.setLogo(updatedPages.avatar_url)
                updatedInformation.setPath(updatedPages.path)
                res.flash("success", "Ihre Website wurde aktualisiert")
              }

              res.redirect('/account/updateInformation?id='+updatedInformation.getId())
            }
          ], function (err) {
            if(err) console.log(err)
            if(newLogoFile){ // remove logo
              fs.unlink(newLogoFile, (err) => {
                if(err) console.log(err)
              })
            }
          })
        }
      }
    }
  })

  app.delete('/deleteProject', async function(req:any, res:any){
    if( !req.isAuthenticated() ) {
      res.redirect('/login')
    } else {
      let loggedInUser = await getLoggedInUserData(req.user.email)
      if (!loggedInUser) {
        res.redirect('/login')
      } else {
        let projectId = req.body.id

        if (projectId) {
          // check if the owner is valid
          let project = await gitlab.getProjectById(projectId)
          if (!project) {
            console.log(" ========= Error or no project found")
          } else if (!project.owner) {
            console.log(" ========= Project cannot be accessed, since it does not have an owner")
          } else if (project.owner.id != loggedInUser.getGitlabUserId()) {
            console.log(" ========= Access denied: Not your project")
          } else {
            let isDeleted = await gitlab.deleteProjectById(projectId)
            if (!isDeleted) {
              res.flash("error", "Project cannot be deleted. Please try again.")
            }
          }
        }
        res.redirect('/account/services')
      }
    }
  })

}