Commit 28fe54f1 authored by Rosanny Sihombing's avatar Rosanny Sihombing
Browse files

clean codes

parent 9b0bffa7
// check password and password confirmation input fields
// used in Security and Reset Password
$('#inputNewPwd, #inputConfirm').on('keyup', function () {
var isBest, isMatch;
let isBest, isMatch
isBest = checkPasswordReq($('#inputNewPwd').val())
$('#recommendation').empty();
$('#recommendation').empty()
if (!isBest) {
//$('#recommendation').html('Must be at least 8 characters').css('color', 'red');
$('#recommendation').html('Das Passwort muss mindestens 8 Zeichen haben').css('color', 'red');
// $('#recommendation').html('Must be at least 8 characters').css('color', 'red');
$('#recommendation').html('Das Passwort muss mindestens 8 Zeichen haben').css('color', 'red')
}
// match or not?
if ($('#inputNewPwd').val() == $('#inputConfirm').val()) {
//$('#message').html('Matching').css('color', 'green');
$('#message').html('Übereinstimmend').css('color', 'green');
isMatch = true;
// $('#message').html('Matching').css('color', 'green');
$('#message').html('Übereinstimmend').css('color', 'green')
isMatch = true
} else {
//$('#message').html('Not Matching').css('color', 'red');
$('#message').html('Nicht übereinstimmend').css('color', 'red');
isMatch = false;
// $('#message').html('Not Matching').css('color', 'red');
$('#message').html('Nicht übereinstimmend').css('color', 'red')
isMatch = false
}
// enable/disable update button
if (isBest && isMatch) {
$('#updateBtn').prop('disabled', false);
$('#updateBtn').prop('disabled', false)
} else {
$('#updateBtn').prop('disabled', true);
$('#updateBtn').prop('disabled', true)
}
});
\ No newline at end of file
})
......@@ -12,23 +12,22 @@ import projectInformation from '../classes/website'
import projectRepo from '../classes/repo'
const SamlStrategy = passportSaml.Strategy
const saltRounds = 10;
const salt = 64; // salt length
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) {
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.serializeUser(function (user: any, done: any) {
done(null, user)
})
passport.deserializeUser(function (user:any, done:any) {
done(null, user);
});
passport.deserializeUser(function (user: any, done: any) {
done(null, user)
})
var samlStrategy = new SamlStrategy({
const samlStrategy = new SamlStrategy({
// URL that goes from the Identity Provider -> Service Provider
callbackUrl: config.passport.saml.path,
// Base address to call logout requests
......@@ -48,17 +47,17 @@ export = function (app:any, config:any, passport:any, lang:string) {
validateInResponseTo: false,
disableRequestedAuthnContext: true
},
function (profile:any, done:any) {
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);
passport.use(samlStrategy)
// ============= SAML ==============
app.post(config.passport.saml.path,
......@@ -67,33 +66,33 @@ export = function (app:any, config:any, passport:any, lang:string) {
failureRedirect: '/account/',
failureFlash: true
}),
function (req:any, res:any) {
res.redirect('/account/');
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);
function (req: any, res: any) {
res.type('application/xml')
const 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)
async function getLoggedInUserData (email: string) {
const user = await methods.getUserByEmail(email)
if (!user) {
console.log('no user found')
return null
} else {
let loggedInUser = new portalUser(
const 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)
const userGitlabId = await methods.getGitlabId(loggedInUser.id)
if (userGitlabId) {
loggedInUser.setGitlabUserId(userGitlabId)
}
......@@ -101,21 +100,21 @@ export = function (app:any, config:any, passport:any, lang:string) {
}
}
app.get('/', async function (req:any, res:any) {
if ( !req.isAuthenticated() ) {
app.get('/', async function (req: any, res: any) {
if (!req.isAuthenticated()) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) {
console.error("user data is not found")
res.status(500).render(lang+'/500', { error: "Your data is not found. Please try again." })
const loggedInUser = await getLoggedInUserData(req.user.email)
if (loggedInUser == null) {
console.error('user data is not found')
res.status(500).render(lang + '/500', { error: 'Your data is not found. Please try again.' })
} else {
res.render(lang+'/account/home', {
res.render(lang + '/account/home', {
user: loggedInUser
});
})
}
}
});
})
app.get('/login',
passport.authenticate(config.passport.strategy, {
......@@ -124,106 +123,106 @@ export = function (app:any, config:any, passport:any, lang:string) {
})
)
app.get('/logout', function (req:any, res:any) {
app.get('/logout', function (req: any, res: any) {
if (req.user == null) {
return res.redirect('/');
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();
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);
if (req.session) {
req.session.destroy((err: any) => {
if (err) {
return console.log(err)
}
});
})
}
return res.redirect(uri);
});
});
return res.redirect(uri)
})
})
app.get('/profile', async function (req:any, res:any) {
if ( !req.isAuthenticated() ) {
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
const loggedInUser = await getLoggedInUserData(req.user.email)
if (loggedInUser == null) { // null user
res.redirect('/account/')
} else {
if(loggedInUser.getVerificationStatus() != 1) {
if (loggedInUser.getVerificationStatus() != 1) {
res.redirect('/account/')
} else {
res.render(lang+'/account/profile', {
res.render(lang + '/account/profile', {
user: loggedInUser
})
}
}
}
})
app.get('/services', async function(req:any, res:any){
if( !req.isAuthenticated() ) {
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
const loggedInUser = await getLoggedInUserData(req.user.email)
if (loggedInUser == null) { // null user
res.redirect('/account/')
} else {
if(loggedInUser.getVerificationStatus() != 1) { // unverified users
if (loggedInUser.getVerificationStatus() != 1) { // unverified users
res.redirect('/account/')
} else {
let gitlabReposArr = []
let gitlabPagesArr = []
const gitlabReposArr = []
const gitlabPagesArr = []
if(loggedInUser.getGitlabUserId()) { // for users who have activated their gitlab account
let userProjects = await gitlab.getUserProjects(loggedInUser.getGitlabUserId()!)
if (loggedInUser.getGitlabUserId()) { // for users who have activated their gitlab account
const userProjects = await gitlab.getUserProjects(loggedInUser.getGitlabUserId()!)
if (!userProjects) {
console.error("something went wrong")
res.status(500).render(lang+'/500', { error: "something went wrong" })
console.error('something went wrong')
res.status(500).render(lang + '/500', { error: 'something went wrong' })
}
let project:any
let project: any
for (project in userProjects) {
if (userProjects[project].tag_list.includes('website')) {
let page = {
const 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,
const 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', {
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())
const gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail())
if (!gitlabUser) {
res.render(lang+'/account/services', {
res.render(lang + '/account/services', {
user: loggedInUser,
gitlabRepos: null,
gitlabPages: null
})
} else {
let gitlabActivationData = {
const gitlabActivationData = {
user_id: loggedInUser.getId(),
gitlab_userId: gitlabUser.id}
gitlab_userId: gitlabUser.id
}
methods.addGitlabUser(gitlabActivationData, function(err:any){
if(err) {
res.status(500).render(lang+'/500', { error: err })
methods.addGitlabUser(gitlabActivationData, function (err: any) {
if (err) {
res.status(500).render(lang + '/500', { error: err })
} else {
res.redirect('/account/services')
}
......@@ -235,16 +234,16 @@ export = function (app:any, config:any, passport:any, lang:string) {
}
})
app.get('/security', async function (req:any, res:any) {
if ( !req.isAuthenticated() ) {
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
const loggedInUser = await getLoggedInUserData(req.user.email)
if (loggedInUser == null) { // null user
res.redirect('/account/')
} else {
if(loggedInUser.getVerificationStatus() == 1 && loggedInUser.getIdpStatus() == 1) {
res.render(lang+'/account/security', {
if (loggedInUser.getVerificationStatus() == 1 && loggedInUser.getIdpStatus() == 1) {
res.render(lang + '/account/security', {
user: loggedInUser
})
} else {
......@@ -254,15 +253,15 @@ export = function (app:any, config:any, passport:any, lang:string) {
}
})
app.post('/updateProfile', async function (req:any, res:any) {
if ( !req.isAuthenticated() ) {
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
const loggedInUser = await getLoggedInUserData(req.user.email)
if (loggedInUser == null) { // null user
res.redirect('/account/')
} else {
let userData = {
const userData = {
salutation: req.body.inputSalutation,
title: req.body.inputTitle,
firstname: req.body.inputFirstname,
......@@ -270,11 +269,11 @@ export = function (app:any, config:any, passport:any, lang:string) {
email: req.body.inputEmail,
organisation: req.body.inputOrganisation,
industry: req.body.inputIndustry,
speciality: req.body.inputSpeciality,
speciality: req.body.inputSpeciality
}
let result = await methods.updateUserById(loggedInUser.getId(), userData)
const result = await methods.updateUserById(loggedInUser.getId(), userData)
if (!result) {
res.flash('error', "Failed")
res.flash('error', 'Failed')
} else {
loggedInUser.updateProfile(userData.salutation, userData.title, userData.firstname, userData.lastname, userData.email,
userData.organisation, userData.industry, userData.speciality)
......@@ -282,101 +281,99 @@ export = function (app:any, config:any, passport:any, lang:string) {
}
res.redirect('/account/profile')
}
}
});
})
app.post('/changePwd', async function (req:any, res:any) {
if( !req.isAuthenticated() ) {
app.post('/changePwd', async function (req: any, res: any) {
if (!req.isAuthenticated()) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) { // null user
if (loggedInUser == null) { // null user
res.redirect('/account/')
} else {
let currPwd = req.body.inputCurrPwd
let newPwd = req.body.inputNewPwd
let retypePwd = req.body.inputConfirm
const currPwd = req.body.inputCurrPwd
const newPwd = req.body.inputNewPwd
const retypePwd = req.body.inputConfirm
dbconn.user.query('SELECT password FROM credential WHERE user_id='+loggedInUser.getId(), function (err:any, rows:any) {
dbconn.user.query('SELECT password FROM credential WHERE user_id=' + loggedInUser.getId(), function (err: any, rows: any) {
if (err) {
console.error(err)
res.status(500).render(lang+'/500', { error: err })
res.status(500).render(lang + '/500', { error: err })
}
let userPwd = rows[0].password
const userPwd = rows[0].password
// check if the password is correct
bcrypt.compare(currPwd, userPwd, function(err, isMatch) {
bcrypt.compare(currPwd, userPwd, function (err, isMatch) {
if (err) {
console.error(err)
res.status(500).render(lang+'/500', { 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.flash('error', 'Das Passwort ist leider falsch. Bitte überprüfen Sie Ihre Eingabe.')
res.redirect('/account/security')
} else {
if ( newPwd != retypePwd ) {
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 = {
bcrypt.genSalt(saltRounds, function (err, salt) {
bcrypt.hash(newPwd, salt, async function (err, hash) {
const credentialData = {
password: hash,
user_id: loggedInUser!.getId()
user_id: loggedInUser.getId()
}
let result = await methods.updateCredential(credentialData)
const result = await methods.updateCredential(credentialData)
if (!result) {
console.log('Failed to reset password')
res.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.")
res.flash('error', 'Datenbankfehler: Passwort kann nicht geändert werden.')
} else {
res.flash('success', "Passwort aktualisiert!")
res.flash('success', 'Passwort aktualisiert!')
// send notifiaction email
mailer.options.to = loggedInUser!.getEmail()
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) {
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){
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) {
const loggedInUser = await getLoggedInUserData(req.user.email)
if (loggedInUser == null) {
res.redirect('/login')
} else {
let token = await methods.getVerificationTokenByUserId(loggedInUser.id)
const 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/>' +
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 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) {
'</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
......@@ -390,19 +387,19 @@ export = function (app:any, config:any, passport:any, lang:string) {
// ============= NEW GITLAB PAGES ===========================
app.get('/newInformation', async function(req:any, res:any){
if ( !req.isAuthenticated() ) {
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) {
const loggedInUser = await getLoggedInUserData(req.user.email)
if (loggedInUser == null) {
res.redirect('/login')
} else {
let gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail())
const gitlabUser = await gitlab.getUserByEmail(loggedInUser.getEmail())
if (!gitlabUser) { // no user found
res.redirect('/account/services')
} else {
res.render(lang+'/account/newInformation', {
res.render(lang + '/account/newInformation', {
user: loggedInUser,
gitlabUsername: gitlabUser.username
})
......@@ -410,58 +407,58 @@ export = function (app:any, config:any, passport:any, lang:string) {
}
}
})
app.post('/newInformation', async function(req:any, res:any) {
if( !req.isAuthenticated() ) {
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) {
const loggedInUser = await getLoggedInUserData(req.user.email)
if (loggedInUser == null) {
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)
const projectName = req.body.name.toLowerCase().replace(/\s/g, '-')
const projectDesc = req.body.description
const projectTemplate = req.body.template
const newInformation = new projectInformation(loggedInUser.getGitlabUserId()!, projectName, projectDesc)
let newLogoFile = defaultLogo
if (req.files) { newLogoFile = req.files.logo }
async.waterfall([
function(callback:any){ // upload logo
function (callback: any) { // upload logo
if (!req.files) {
callback(null, newLogoFile)
} else {
newLogoFile.mv(logoDir + newLogoFile.name, function(err:any) {
newLogoFile = logoDir+newLogoFile.name
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)
async function (newLogoFile: any) { // create a new GitLab Page
const 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.")
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.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)
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)
if (err != null) console.log(err)
// remove logo
if (req.files) {
fs.unlink(newLogoFile, (err) => {
if(err) console.log(err)
if (err != null) console.log(err)
})
}
})
......@@ -470,33 +467,33 @@ export = function (app:any, config:any, passport:any, lang:string) {
}
})
app.get('/updateInformation', async function(req:any, res:any){
if( !req.isAuthenticated() ) {
app.get('/updateInformation', async function (req: any, res: any) {
if (!req.isAuthenticated()) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) {
if (loggedInUser == null) {
res.redirect('/login')
} else {
if(!req.query.id) {
if (!req.query.id) {
res.redirect('/account/services')
} else {
let project = await gitlab.getProjectById(req.query.id)
const project = await gitlab.getProjectById(req.query.id)
if (!project) {
console.log(" ========= Error or no project found")
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")
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")
console.log(' ========= Access denied: Not your project')
res.redirect('/account/services')
} else {
let curInformation = new projectInformation(loggedInUser.getGitlabUserId()!, project.name, project.description,
const curInformation = new projectInformation(loggedInUser.getGitlabUserId()!, project.name, project.description,
req.query.id, project.avatar_url, project.path_with_namespace)
res.render(lang+'/account/updateInformation', {
res.render(lang + '/account/updateInformation', {
user: loggedInUser,
information: curInformation
})
......@@ -506,58 +503,58 @@ export = function (app:any, config:any, passport:any, lang:string) {
}
})
// update a website
app.post('/updateInformation', async function(req:any, res:any){
if( !req.isAuthenticated() ) {
app.post('/updateInformation', async function (req: any, res: any) {
if (!req.isAuthenticated()) {
res.redirect('/login')
} else {
let loggedInUser = await getLoggedInUserData(req.user.email)
const loggedInUser = await getLoggedInUserData(req.user.email)
if (!loggedInUser) {
if (loggedInUser == null) {
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
const projectName = req.body.name.toLowerCase().replace(/\s/g, '-')
const projectDesc = req.body.description
const updatedInformation = new projectInformation(loggedInUser.getGitlabUserId()!, projectName, projectDesc, req.query.id)
let newLogoFile: any
async.waterfall([
function(callback:any){ // upload logo
if(!req.files) {
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.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)
async function (newLogoFile: any) { // update gitlab page
const 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.")
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. ")
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.flash('success', 'Ihre Website wurde aktualisiert')
}
res.redirect('/account/updateInformation?id='+updatedInformation.getId())
res.redirect('/account/updateInformation?id=' + updatedInformation.getId())
}
], function (err) {
if(err) console.log(err)
if(newLogoFile){ // remove logo
if (err != null) console.log(err)
if (newLogoFile) { // remove logo
fs.unlink(newLogoFile, (err) => {
if(err) console.log(err)
if (err != null) console.log(err)
})
}
})
......@@ -566,29 +563,29 @@ export = function (app:any, config:any, passport:any, lang:string) {
}
})
app.delete('/deleteProject', async function(req:any, res:any){
if( !req.isAuthenticated() ) {
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) {
const loggedInUser = await getLoggedInUserData(req.user.email)
if (loggedInUser == null) {
res.redirect('/login')
} else {
let projectId = req.body.id
const projectId = req.body.id
if (projectId) {
// check if the owner is valid
let project = await gitlab.getProjectById(projectId)
const project = await gitlab.getProjectById(projectId)
if (!project) {
console.log(" ========= Error or no project found")
console.log(' ========= Error or no project found')
} else if (!project.owner) {
console.log(" ========= Project cannot be accessed, since it does not have an 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")
console.log(' ========= Access denied: Not your project')
} else {
let isDeleted = await gitlab.deleteProjectById(projectId)
const isDeleted = await gitlab.deleteProjectById(projectId)
if (!isDeleted) {
res.flash("error", "Project cannot be deleted. Please try again.")
res.flash('error', 'Project cannot be deleted. Please try again.')
}
}
}
......@@ -596,5 +593,4 @@ export = function (app:any, config:any, passport:any, lang:string) {
}
}
})
}
......@@ -4,19 +4,18 @@ 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) {
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.get('/registration', function (req: any, res: any) {
res.render(lang + '/account/registration')
})
app.post('/registration', function(req:any, res:any) {
app.post('/registration', function (req: any, res: any) {
// user data
let curDate:Date = new Date()
let userData:any = {
const curDate: Date = new Date()
const userData: any = {
salutation: req.body.inputSalutation,
title: req.body.inputTitle,
firstname: req.body.inputFirstname,
......@@ -25,65 +24,64 @@ export = function (app:any, config:any, lang:string) {
organisation: req.body.inputOrganisation,
industry: req.body.inputIndustry,
speciality: req.body.inputSpeciality,
createdDate: curDate.toISOString().slice(0,10)
createdDate: curDate.toISOString().slice(0, 10)
}
let userEmail:any = userData.email
let pos:number = userEmail.indexOf('@')
let emailLength:number = userEmail.length
let emailDomain:any = userEmail.slice(pos, emailLength);
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")
if (emailDomain.toLowerCase() == '@hft-stuttgart.de') {
res.flash('error', 'Fehlgeschlagen: HFT-Account')
res.redirect('/account/registration')
} else {
async.waterfall([
function(done:any) {
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));
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) {
let newAccount:any = {
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) {
methods.registerNewUser(newAccount, function(err:any){
function (newAccount: any, err: any) {
methods.registerNewUser(newAccount, function (err: any) {
if (err) {
res.flash('error', "Fehlgeschlagen")
}
else {
res.flash('error', 'Fehlgeschlagen')
} else {
// send email
let emailSubject = "Bitte bestätigen Sie Ihr M4_LAB Benutzerkonto"
let emailContent = '<div>Lieber Nutzer,<br/><br/>' +
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='+config.app.host+'/verifyAccount?token='+newAccount.verificationToken+'>diesen Link</a> ' +
'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) {
'</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)
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'+
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')
......@@ -93,62 +91,62 @@ export = function (app:any, config:any, lang:string) {
}
})
// 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)
app.get('/email/:email', async function (req: any, res: any) {
const user = await methods.checkUserEmail(req.params.email)
if (!user) {
console.log('No user found: '+req.params.email)
console.log('No user found: ' + req.params.email)
res.send(true)
} else {
console.log('User found: '+req.params.email)
console.log('User found: ' + req.params.email)
res.send(false)
}
})
// =================== USERS VERIFICATION =========================
app.get("/verifyAccount", async function(req:any, res:any){
let userId:number = await methods.getUserIdByVerificationToken(req.query.token)
app.get('/verifyAccount', async function (req: any, res: any) {
const userId: number = await methods.getUserIdByVerificationToken(req.query.token)
if (!userId) {
// no user found
res.render(lang+'/account/verification', {
res.render(lang + '/account/verification', {
status: null
})
} else {
// a user found, verify the account
let userData:any = {
const userData: any = {
id: userId,
verificationStatus: 1
}
methods.verifyUserAccount(userData, async function(err:any){
methods.verifyUserAccount(userData, async function (err: any) {
if (err) {
console.log("Error: "+err)
res.render(lang+'/account/verification', {
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)
const userEmail: string = await methods.getUserEmailById(userId)
if (!userEmail) {
res.render(lang+'/account/verification', {
res.render(lang + '/account/verification', {
status: false
})
} else {
// send email
let emailSubject = "Herzlich willkommen";
let emailContent = '<div>Lieber Nutzer,<br/><br/>' +
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/>' + constants.mailSignature;
mailer.options.to = userEmail;
mailer.options.subject = emailSubject;
mailer.options.html = emailContent;
mailer.transporter.sendMail(mailer.options, function(err:any) {
'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;
console.log('cannot send email')
throw err
}
})
res.render(lang+'/account/verification', {
res.render(lang + '/account/verification', {
status: true
})
}
......@@ -159,38 +157,38 @@ export = function (app:any, config:any, lang:string) {
// ==================== FORGOT PASSWORD ===========================
app.get('/forgotPwd', function (req:any, res:any) {
res.render(lang+'/account/forgotPwd', {
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
app.post('/forgotPwd', function (req: any, res: any) {
const emailAddress = req.body.inputEmail
async.waterfall([
async function(done:any) {
let user = await methods.checkUserEmail(emailAddress)
async function (done: any) {
const user = await methods.checkUserEmail(emailAddress)
if (!user) {
console.log('No user found: '+emailAddress)
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));
let token: string = ''
const randomChars: string = 'abcdefghijklmnopqrstuvwxyz0123456789'
for (let i = 0; i < 40; i++) {
token += randomChars.charAt(Math.floor(Math.random() * randomChars.length))
}
let emailSubject = "Ihre Passwort-Anfrage an das Transferportal der HFT Stuttgart";
let emailContent = '<div>Lieber Nutzer,<br/><br/>' +
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: '+config.app.host+'/reset/' + token + '<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>'
let credentialData = {
const credentialData = {
user_id: user.id,
resetPasswordToken: token,
resetPasswordExpires: Date.now() + 3600000 // 1 hour
}
let result = await methods.updateCredential(credentialData)
const result = await methods.updateCredential(credentialData)
if (!result) {
console.log('failed to update credential')
} else {
......@@ -198,18 +196,17 @@ export = function (app:any, config:any, lang:string) {
mailer.options.to = emailAddress
mailer.options.subject = emailSubject
mailer.options.html = emailContent
mailer.transporter.sendMail(mailer.options, function(err:any) {
mailer.transporter.sendMail(mailer.options, function (err: any) {
if (err) { console.error(err) }
})
}
}
done(null)
}
], function(err:any) {
], function (err: any) {
if (err) {
res.flash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.')
}
else {
} 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')
......@@ -217,89 +214,86 @@ export = function (app:any, config:any, lang:string) {
})
// reset
app.get('/reset/:token', async function(req:any, res:any) {
let user = await methods.getUserByToken(req.params.token)
app.get('/reset/:token', async function (req: any, res: any) {
const 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')
res.render(lang + '/account/reset')
}
})
app.post('/reset/:token', async function(req:any, res:any) {
let newPwd = req.body.inputNewPwd
app.post('/reset/:token', async function (req: any, res: any) {
const newPwd = req.body.inputNewPwd
let user = await methods.getUserByToken(req.params.token)
const user = await methods.getUserByToken(req.params.token)
if (!user) {
res.flash('error', "User not found.")
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) {
let credentialData = {
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
let result = await methods.updateCredential(credentialData)
const result = await methods.updateCredential(credentialData)
if (!result) {
console.log('Failed to reset password')
res.flash('error', "Datenbankfehler: Passwort kann nicht geändert werden.")
res.flash('error', 'Datenbankfehler: Passwort kann nicht geändert werden.')
} else {
res.flash('success', "Passwort aktualisiert!")
res.flash('success', 'Passwort aktualisiert!')
// send notification 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) {
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', {
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 emailSubject = "Ihre Anfrage an das Transferportal";
let emailContent = "<div>Es wurde eine Anfrage an das Transferportal gestellt: <br/><br/>NAME: " + inputName + "<br/>NACHRICHT: "+ inputContent+"</div>";
app.post('/contact', function (req: any, res: any, next: any) {
// methods.currentDate();
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 = '<div>Es wurde eine Anfrage an das Transferportal gestellt: <br/><br/>NAME: ' + inputName + '<br/>NACHRICHT: ' + inputContent + '</div>'
async.waterfall([
function(done:any) {
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');
});
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) {
], 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.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')
})
})
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment