Commit 4450156e authored by Rosanny Sihombing's avatar Rosanny Sihombing
Browse files

cleaning codes

parent 689b3cfa
......@@ -11,13 +11,13 @@ import helmet from 'helmet'
import compression from 'compression'
import methodOverride from 'method-override'
const env = process.env.NODE_ENV || 'development'
const env = process.env.NODE_ENV ?? 'testing'
const config = require('./config/config')[env]
const lang = 'DE'
const app = express()
app.set('port', config.app.port)
app.set('views', path.join(__dirname + '/views'))
app.set('views', path.join(path.join(__dirname, '/views')))
app.set('view engine', 'pug')
// enable files upload
......
......@@ -66,4 +66,4 @@ class Project {
}
}
export = Project
export { Project }
import Project from './project'
import { Project } from './project'
class Repo extends Project {
constructor (ownerGitlabId: number, name: string, desc: string, id?: number, logo?: string, path?: string) {
......@@ -6,4 +6,4 @@ class Repo extends Project {
}
}
export = Repo
export { Repo }
......@@ -8,12 +8,12 @@ class User {
industry: string
organisation: string
speciality: string
is_m4lab_idp: number // 1 or 0
isM4labIdp: number // 1 or 0
verificationStatus: number // 1 or 0 - // should be boolean
gitlabUserId?: number
constructor (id: number, email: string, salutation: string, title: string, firstName: string, lastName: string, industry: string, organisation: string,
speciality: string, is_m4lab_idp: number, verificationStatus: number, gitlabUserId?: number) {
speciality: string, isM4labIdp: number, verificationStatus: number, gitlabUserId?: number) {
this.id = id
this.email = email
this.salutation = salutation
......@@ -23,7 +23,7 @@ class User {
this.industry = industry
this.organisation = organisation
this.speciality = speciality
this.is_m4lab_idp = is_m4lab_idp
this.isM4labIdp = isM4labIdp
this.verificationStatus = verificationStatus
this.gitlabUserId = gitlabUserId
}
......@@ -42,7 +42,7 @@ class User {
}
getIdpStatus () {
return this.is_m4lab_idp
return this.isM4labIdp
}
getVerificationStatus () {
......@@ -86,8 +86,8 @@ class User {
this.speciality = speciality
}
setM4lab_idp (m4lab_idp: number) {
this.is_m4lab_idp = m4lab_idp
setM4lab_idp (m4labIdp: number) {
this.isM4labIdp = m4labIdp
}
setVerificationStatus (verificationStatus: number) {
......@@ -110,4 +110,4 @@ class User {
}
}
export = User
export { User }
import Project from './project'
import { Project } from './project'
class Website extends Project {
constructor (ownerGitlabId: number, name: string, desc: string, id?: number, logo?: string, path?: string) {
......@@ -6,4 +6,4 @@ class Website extends Project {
}
}
export = Website
export { Website }
export = {
module.exports = {
development: {
app: {
name: 'User Account Management',
port: process.env.PORT || 9989,
port: process.env.PORT ?? 9989,
host: 'http://localhost:9989',
sessionSecret: 'thisisasecret'
},
passport: {
strategy: 'saml',
saml: {
path: process.env.SAML_PATH || '/saml/SSO',
path: process.env.SAML_PATH ?? '/saml/SSO',
entryPoint: process.env.SAML_ENTRY_POINT || 'saml entry point',
issuer: 'SAML issuer',
logoutUrl: 'SAML logout URL'
......@@ -41,15 +41,15 @@ export = {
testing: {
app: {
name: 'User Account Management',
port: process.env.PORT || 9989,
port: process.env.PORT ?? 9989,
host: 'https://m4lab.hft-stuttgart.de/account',
sessionSecret: 'thisisasecret'
},
passport: {
strategy: 'saml',
saml: {
path: process.env.SAML_PATH || '/saml/SSO',
entryPoint: process.env.SAML_ENTRY_POINT || 'saml entry point',
path: process.env.SAML_PATH ?? '/saml/SSO',
entryPoint: process.env.SAML_ENTRY_POINT ?? 'saml entry point',
issuer: 'SAML issuer', // testing metadata
logoutUrl: 'SAML logout URL'
}
......@@ -78,3 +78,5 @@ export = {
}
}
}
export {}
export = {
const miscConst = {
mailSignature: 'Mit den besten Grüßen,<br/>das Transferportal-Team der HFT Stuttgart<br/><br/>' +
'Transferportal der Hochschule für Technik Stuttgart<br/>' +
'Schellingstr. 24 70174 Stuttgart<br/>' +
'm4lab@hft-stuttgart.de<br/>' +
'<a href="https://transfer.hft-stuttgart.de">https://transfer.hft-stuttgart.de</a><br/>' +
'<a mailConsthref="https://transfer.hft-stuttgart.de">https://transfer.hft-stuttgart.de</a><br/>' +
'<a href="http://www.hft-stuttgart.de/Aktuell/"><img border="0" alt="HFT" src="https://m4lab.hft-stuttgart.de/img/signature/hft_logo.png" width="30" height="30"></a> &nbsp;' +
'<a href="http://www.facebook.com/hftstuttgart"><img border="0" alt="Facebook" src="https://m4lab.hft-stuttgart.de/img/signature/fb_bw.png" width="30" height="30"></a> &nbsp;' +
'<a href="https://www.instagram.com/hft_stuttgart/"><img border="0" alt="Instagram" src="https://m4lab.hft-stuttgart.de/img/signature/instagram_bw.png" width="30" height="30"></a> &nbsp;' +
......@@ -17,3 +17,5 @@ export = {
updatePasswordMailContent: '<div>Lieber Nutzer,<br/><br/>Ihr Passwort wurde erfolgreich geändert.<br/><br/></div>'
}
export { miscConst }
import mysql from 'mysql2'
const env = process.env.NODE_ENV || 'development'
const env = process.env.NODE_ENV ?? 'development'
const config = require('./config')[env]
// ==== USER ACOOUNT DB CONNECTION ====
......@@ -31,9 +31,9 @@ const projectConnection = mysql.createPool({
projectConnection.query('USE ' + config.database.dbProject)
const connection = {
const dbConnection = {
user: userConnection,
project: projectConnection
}
export = connection
export { dbConnection }
const nodemailer = require('nodemailer')
const nodemailerNTLMAuth = require('nodemailer-ntlm-auth')
const env = process.env.NODE_ENV || 'testing'
const env = process.env.NODE_ENV ?? 'testing'
const config = require('./config')[env]
const smtpTransporter = nodemailer.createTransport({
......@@ -37,4 +37,4 @@ const mailer: any = {
options: mailOptions
}
export = mailer
export { mailer }
import dbconn = require('../config/dbconn')
import { dbConnection } from '../config/dbconn'
const dbController = {
// ===================== user db =====================
registerNewUser: function (data: any, callback: any) {
dbconn.user.getConnection(function (err: any, thisconn) {
dbConnection.user.getConnection(function (err: any, thisconn) {
thisconn.beginTransaction(function (err: any) { // START TRANSACTION
if (err) { throw err }
// insert profile
......@@ -66,7 +66,7 @@ const dbController = {
},
getUserByEmail: async function (email: any) {
try {
const rows: any = await dbconn.user.promise().query('SELECT id, verificationStatus, salutation, title, firstname, lastname, industry, organisation, speciality, m4lab_idp FROM user WHERE email = "' + email + '"')
const rows: any = await dbConnection.user.promise().query('SELECT id, verificationStatus, salutation, title, firstname, lastname, industry, organisation, speciality, m4lab_idp FROM user WHERE email = "' + email + '"')
if (rows[0][0]) {
return rows[0][0]
} else { return null }
......@@ -77,7 +77,7 @@ const dbController = {
},
getUserEmailById: async function (userId: number) {
try {
const rows: any = await dbconn.user.promise().query('SELECT email FROM user WHERE id = ' + userId)
const rows: any = await dbConnection.user.promise().query('SELECT email FROM user WHERE id = ' + userId)
if (rows[0][0]) {
return rows[0][0].email
} else { return null }
......@@ -88,7 +88,7 @@ const dbController = {
},
checkUserEmail: async function (email: any) {
try {
const rows: any = await dbconn.user.promise().query('SELECT id, email FROM user WHERE email = "' + email + '"')
const rows: any = await dbConnection.user.promise().query('SELECT id, email FROM user WHERE email = "' + email + '"')
if (rows[0][0]) {
return rows[0][0]
} else { return null }
......@@ -99,7 +99,7 @@ const dbController = {
},
getUserByToken: async function (token: any) {
try {
const rows: any = await dbconn.user.promise().query('SELECT t1.user_id, t2.email FROM userdb.credential AS t1 INNER JOIN userdb.user AS t2 ON t1.user_id = t2.id AND t1.resetPasswordToken = "' +
const rows: any = await dbConnection.user.promise().query('SELECT t1.user_id, t2.email FROM userdb.credential AS t1 INNER JOIN userdb.user AS t2 ON t1.user_id = t2.id AND t1.resetPasswordToken = "' +
token + '" and resetPasswordExpires > ' + Date.now())
if (rows[0][0]) {
return rows[0][0]
......@@ -111,7 +111,7 @@ const dbController = {
},
updateUserById: async function (userId: number, userData: any) {
try {
const result: any = await dbconn.user.promise().query('UPDATE user SET ? WHERE id = ' + userId, userData)
const result: any = await dbConnection.user.promise().query('UPDATE user SET ? WHERE id = ' + userId, userData)
return result
} catch (err) {
console.error(err)
......@@ -120,7 +120,7 @@ const dbController = {
},
updateCredential: async function (data: any) {
try {
const result: any = await dbconn.user.promise().query('UPDATE credential SET ? WHERE user_id = ' + data.user_id, data)
const result: any = await dbConnection.user.promise().query('UPDATE credential SET ? WHERE user_id = ' + data.user_id, data)
return result
} catch (err) {
console.error(err)
......@@ -128,14 +128,14 @@ const dbController = {
return null
},
addUserProjectRole_OBSOLETE: function (data: any, callback: any) {
dbconn.user.query('INSERT INTO user_project_role SET ?', data, function (err: any) {
dbConnection.user.query('INSERT INTO user_project_role SET ?', data, function (err: any) {
if (err) throw err
callback(err)
})
},
getVerificationTokenByUserId: async function (userId: number) {
try {
const rows: any = await dbconn.user.promise().query('SELECT token FROM verification WHERE user_id = "' + userId + '"')
const rows: any = await dbConnection.user.promise().query('SELECT token FROM verification WHERE user_id = "' + userId + '"')
if (rows[0][0]) {
return rows[0][0].token
} else { return null }
......@@ -146,7 +146,7 @@ const dbController = {
},
getUserIdByVerificationToken: async function (token: any) {
try {
const rows: any = await dbconn.user.promise().query('SELECT user_id FROM verification WHERE token = "' + token + '"')
const rows: any = await dbConnection.user.promise().query('SELECT user_id FROM verification WHERE token = "' + token + '"')
if (rows[0][0]) {
return rows[0][0].user_id
} else {
......@@ -158,7 +158,7 @@ const dbController = {
return null
},
verifyUserAccount: function (userData: any, callback: any) {
dbconn.user.getConnection(function (err: any, thisconn) {
dbConnection.user.getConnection(function (err: any, thisconn) {
thisconn.beginTransaction(function (err: any) { // START TRANSACTION
if (err) { throw err }
// update user status
......@@ -186,7 +186,7 @@ const dbController = {
/* ===== GitLab ===== */
getGitlabId: async function (userId: number) {
try {
const rows: any = await dbconn.user.promise().query('SELECT gu.gitlab_userId FROM user_gitlab gu, user u WHERE u.id = "' + userId + '" and gu.user_id = u.id')
const rows: any = await dbConnection.user.promise().query('SELECT gu.gitlab_userId FROM user_gitlab gu, user u WHERE u.id = "' + userId + '" and gu.user_id = u.id')
if (rows[0][0]) {
return rows[0][0].gitlab_userId
} else {
......@@ -198,7 +198,7 @@ const dbController = {
}
},
addGitlabUser: function (data: any, callback: any) {
dbconn.user.query('INSERT INTO user_gitlab SET ?', data, function (err: any) {
dbConnection.user.query('INSERT INTO user_gitlab SET ?', data, function (err: any) {
if (err) throw err
callback(err)
})
......
......@@ -2,7 +2,7 @@ import axios from 'axios'
import fs from 'fs'
import formData from 'form-data'
const env = process.env.NODE_ENV || 'testing'
const env = process.env.NODE_ENV ?? 'testing'
const config = require('../config/config')[env]
const gitlabController = {
......@@ -124,4 +124,4 @@ const gitlabController = {
}
}
export {gitlabController}
export { gitlabController }
import async from 'async'
import mailer from '../config/mailer'
import bcrypt from 'bcryptjs'
import { mailer } from '../config/mailer'
import { miscConst } from '../config/const'
import { dbController } from './dbController'
const lang = 'DE'
const saltRounds: number = 10
const publicController = {
showRegistrationPage: function (res: any) {
showRegistrationPage: function (res: any, lang: String) {
res.render(lang + '/account/registration')
},
showContactPage: function (req: any, res: any) {
showContactPage: function (req: any, res: any, lang: String) {
res.render(lang + '/account/contact', {
user: req.user
})
},
showForgotPwdPage: function (req: any, res: any) {
showForgotPwdPage: function (req: any, res: any, lang: String) {
res.render(lang + '/account/forgotPwd', {
user: req.user
})
},
showResetToken: async function (req: any, res: any) {
showResetPassword: async function (req: any, res: any, lang: String) {
const user = await dbController.getUserByToken(req.params.token)
if (user) {
res.render(lang + '/account/reset')
......@@ -53,6 +55,221 @@ const publicController = {
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 = '<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=' + String(config.app.host) + '/verifyAccount?token=' + String(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/>' + String(miscConst.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] ' + 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 = '<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/>' + 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 + '<div>' + miscConst.mailSignature + '</div>'
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 = '<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: ' + String(config.app.host) + '/reset/' + String(token) + '<br/>' +
'Dieser Link ist aus Sicherheitsgründen nur für 1 Stunde gültig.<br/></p>' + String(miscConst.mailSignature) + '</div>'
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 {
......
const helpers = {
stringToArray: function (input: string) {
if (input != null) {
return input.split(',')