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

clean codes

parent 9b0bffa7
import gitlab from '../functions/gitlab' import gitlab from '../functions/gitlab'
//const axios = require('axios') // const axios = require('axios')
//jest.mock('axios') // jest.mock('axios')
describe('GitLab API', () => { describe('GitLab API', () => {
test('returns an existing gitlab user by an email address', async () => { test('returns an existing gitlab user by an email address', async () => {
let user = await gitlab.getUserByEmail('litehon958@whipjoy.com') const user = await gitlab.getUserByEmail('litehon958@whipjoy.com')
expect(user).not.toBeNull() expect(user).not.toBeNull()
}) })
test('returns an undefined user', async () => { test('returns an undefined user', async () => {
let user = await gitlab.getUserByEmail('johndoe@nowhere.com') const user = await gitlab.getUserByEmail('johndoe@nowhere.com')
expect(user).toBeUndefined() expect(user).toBeUndefined()
}) })
test('returns users project', async () => { test('returns users project', async () => {
let userProjects = await gitlab.getUserProjects(136) const userProjects = await gitlab.getUserProjects(136)
expect(userProjects).toBeDefined() expect(userProjects).toBeDefined()
}) })
test('returns undefined projects, due to non-existing gitlab user ID', async () => { test('returns undefined projects, due to non-existing gitlab user ID', async () => {
let userProjects = await gitlab.getUserProjects(0) const userProjects = await gitlab.getUserProjects(0)
expect(userProjects).toBeUndefined() expect(userProjects).toBeUndefined()
}) })
test('returns a project by ID', async () => { test('returns a project by ID', async () => {
let project = await gitlab.getProjectById(13) // m4lab_landing_page const project = await gitlab.getProjectById(13) // m4lab_landing_page
expect(project).toBeDefined() expect(project).toBeDefined()
}) })
test('returns undefined, due to invalid project ID', async () => { test('returns undefined, due to invalid project ID', async () => {
let project = await gitlab.getProjectById(0) const project = await gitlab.getProjectById(0)
expect(project).toBeUndefined() expect(project).toBeUndefined()
}) })
}) })
\ No newline at end of file
import methods from '../functions/methods' import methods from '../functions/methods'
describe("DB methohds test", () => { describe('DB methohds test', () => {
it('returns a user from DB by email', async () => {
it("returns a user from DB by email", async() => { const user = await methods.getUserByEmail('litehon958@whipjoy.com')
const user = await methods.getUserByEmail('litehon958@whipjoy.com') expect(user).not.toBeNull()
expect(user).not.toBeNull() })
}) it('returns a null user', async () => {
it("returns a null user", async() => { const user = await methods.getUserByEmail('jondoe@nowhere.com') // a non-exist user
const user = await methods.getUserByEmail('jondoe@nowhere.com') // a non-exist user expect(user).toBeNull()
expect(user).toBeNull() })
})
it("returns a user's email", async () => {
it("returns a user's email", async() => { const email = await methods.getUserEmailById(1)
const email = await methods.getUserEmailById(1) expect(email).not.toBeNull()
expect(email).not.toBeNull() })
}) it("returns null instead of a user's email", async () => {
it("returns null instead of a user's email", async() => { const email = await methods.getUserEmailById(1005) // no user has this ID
const email = await methods.getUserEmailById(1005) // no user has this ID expect(email).toBeNull()
expect(email).toBeNull() })
})
it('returns null from DB by token', async () => {
it("returns null from DB by token", async() => { const user = await methods.getUserByToken('12345678') // unvalid token
const user = await methods.getUserByToken('12345678') // unvalid token expect(user).toBeNull() // for valid token = expect(user).not.toBeNull()
expect(user).toBeNull() // for valid token = expect(user).not.toBeNull() })
})
it("returns a user's verification token, if any", async () => {
it("returns a user's verification token, if any", async() => { const token = await methods.getVerificationTokenByUserId(1)
const token = await methods.getVerificationTokenByUserId(1) expect(token).toBeNull()
expect(token).toBeNull() })
})
it("returns a user's ID, if any", async () => {
it("returns a user's ID, if any", async() => { const token = await methods.getUserIdByVerificationToken('12345678') // unvalid token
const token = await methods.getUserIdByVerificationToken('12345678') // unvalid token expect(token).toBeNull() // for valid token = expect(user).not.toBeNull()
expect(token).toBeNull() // for valid token = expect(user).not.toBeNull() })
})
it("returns a user's GitLab_ID, if any", async () => {
it("returns a user's GitLab_ID, if any", async() => { const id = await methods.getGitlabId(1)
const id = await methods.getGitlabId(1) expect(id).not.toBeNull()
expect(id).not.toBeNull() })
})
it('checks user email', async () => {
it("checks user email", async() => { const user = await methods.checkUserEmail('litehon958@whipjoy.com')
const user = await methods.checkUserEmail('litehon958@whipjoy.com') expect(user).not.toBeNull()
expect(user).not.toBeNull() })
}) it('checks user email and return null', async () => {
it("checks user email and return null", async() => { const user = await methods.checkUserEmail('jondoe@nowhere.com') // a non-exist user
const user = await methods.checkUserEmail('jondoe@nowhere.com') // a non-exist user expect(user).toBeNull()
expect(user).toBeNull() })
}) })
})
\ No newline at end of file
import express from 'express'; import express from 'express'
import path from 'path'; import path from 'path'
import passport from 'passport'; import passport from 'passport'
import morgan from 'morgan'; import morgan from 'morgan'
import cookieParser from 'cookie-parser'; import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'; import bodyParser from 'body-parser'
import session from 'express-session'; import session from 'express-session'
import flash from 'express-flash-2'; import flash from 'express-flash-2'
import fileUpload from 'express-fileupload'; import fileUpload from 'express-fileupload'
import helmet from 'helmet'; import helmet from 'helmet'
import compression from 'compression'; import compression from 'compression'
import methodOverride from 'method-override'; import methodOverride from 'method-override'
import dotenv from 'dotenv'
dotenv.config(); const env = process.env.NODE_ENV || 'development'
const config = require('./config/config')[env]
const lang = 'DE'
var env = process.env.NODE_ENV || 'testing'; const app = express()
const config = require('./config/config')[env]; app.set('port', config.app.port)
const lang = 'DE'; app.set('views', path.join(__dirname + '/views'))
app.set('view engine', 'pug')
var app = express();
app.set('port', config.app.port);
app.set('views', path.join( __dirname + '/views'));
app.set('view engine', 'pug');
// enable files upload // enable files upload
app.use(fileUpload({ app.use(fileUpload({
createParentPath: true, createParentPath: true,
limits: { limits: {
fileSize: 1000000 // 1 MB max. file size fileSize: 1000000 // 1 MB max. file size
} }
})); }))
app.use(methodOverride('_method')); app.use(methodOverride('_method'))
app.use( app.use(
helmet.contentSecurityPolicy({ helmet.contentSecurityPolicy({
useDefaults: true, useDefaults: true,
directives: { directives: {
"font-src": ["'self'", "https://use.fontawesome.com"], 'font-src': ["'self'", 'https://use.fontawesome.com'],
"img-src": ["'self'", "https://transfer.hft-stuttgart.de"], 'img-src': ["'self'", 'https://transfer.hft-stuttgart.de'],
"script-src": ["'self'", "https://code.jquery.com/jquery-3.3.1.min.js", "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js", 'script-src': ["'self'", 'https://code.jquery.com/jquery-3.3.1.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js',
"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js", "https://unpkg.com/bootstrap-show-password@1.2.1/dist/bootstrap-show-password.min.js"], 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js', 'https://unpkg.com/bootstrap-show-password@1.2.1/dist/bootstrap-show-password.min.js'],
"style-src": ["'self'", "https://use.fontawesome.com/releases/v5.8.2/css/all.css"], 'style-src': ["'self'", 'https://use.fontawesome.com/releases/v5.8.2/css/all.css'],
"frame-src": ["'self'"] 'frame-src': ["'self'"]
}, },
reportOnly: true, reportOnly: true
}) })
); )
app.use(compression()); app.use(compression())
app.use(morgan('combined')); app.use(morgan('combined'))
app.use(cookieParser(config.app.sessionSecret)); app.use(cookieParser(config.app.sessionSecret))
app.use(bodyParser.json()); app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public')))
app.use((req, res, next) => { app.use((req, res, next) => {
next(); next()
}); })
app.use(session({ app.use(session({
resave: true, resave: true,
saveUninitialized: true, saveUninitialized: true,
secret: config.app.sessionSecret secret: config.app.sessionSecret
})); }))
app.use(flash()); app.use(flash())
app.use(passport.initialize()); app.use(passport.initialize())
app.use(passport.session()); app.use(passport.session())
// caching disabled for every route // caching disabled for every route
// NOTE: Works in Firefox and Opera. Does not work in Edge // NOTE: Works in Firefox and Opera. Does not work in Edge
app.use(function(req, res, next) { app.use(function (req, res, next) {
res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'); res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0')
next(); next()
}); })
require('./routes/public')(app, config, lang); require('./routes/public')(app, config, lang)
require('./routes/account')(app, config, passport, lang); require('./routes/account')(app, config, passport, lang)
// Handle 404 // Handle 404
app.use(function (req:any, res:any) { app.use(function (req: any, res: any) {
res.status(404).render(lang+'/404') res.status(404).render(lang + '/404')
}) })
// Handle 500 - any server error // Handle 500 - any server error
app.use(function (err:any, req:any, res:any, next:any) { app.use(function (err: any, req: any, res: any, next: any) {
console.error(err.stack) console.error(err.stack)
res.status(500).render(lang+'/500', { res.status(500).render(lang + '/500', {
error: err error: err
}) })
}) })
app.listen(app.get('port'), function () { app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port')); console.log('Express server listening on port ' + app.get('port'))
}); })
\ No newline at end of file
class Project { class Project {
ownerGitlabId:number ownerGitlabId: number
name:string name: string
desc:string desc: string
id?:number id?: number
logo?:string logo?: string
path?:string path?: string
constructor(ownerGitlabId:number, name:string, desc:string, id?:number, logo?:string, path?:string) { constructor (ownerGitlabId: number, name: string, desc: string, id?: number, logo?: string, path?: string) {
this.ownerGitlabId = ownerGitlabId this.ownerGitlabId = ownerGitlabId
this.name = name this.name = name
this.desc = desc this.desc = desc
this.id = id this.id = id
this.logo = logo this.logo = logo
this.path = path this.path = path
} }
// getter // getter
getOwnerGitlabId() { getOwnerGitlabId () {
return this.ownerGitlabId return this.ownerGitlabId
} }
getId() {
return this.id getId () {
} return this.id
getName() { }
return this.name
} getName () {
getDesc() { return this.name
return this.desc }
}
getLogo() { getDesc () {
return this.logo return this.desc
} }
getPath() {
return this.path getLogo () {
} return this.logo
// setter }
setOwnerGitlabId(newOwnerGitlabId:number){
this.ownerGitlabId = newOwnerGitlabId getPath () {
} return this.path
setId(newId:number) { }
this.id = newId
} // setter
setName(newName:string) { setOwnerGitlabId (newOwnerGitlabId: number) {
this.name = newName this.ownerGitlabId = newOwnerGitlabId
} }
setDesc(newDesc:string) {
this.desc = newDesc setId (newId: number) {
} this.id = newId
setLogo(newLogoUrl:string) { }
this.logo = newLogoUrl
} setName (newName: string) {
setPath(newPath:string) { this.name = newName
this.path = newPath }
}
setDesc (newDesc: string) {
this.desc = newDesc
}
setLogo (newLogoUrl: string) {
this.logo = newLogoUrl
}
setPath (newPath: string) {
this.path = newPath
}
} }
export = Project export = Project
\ No newline at end of file
import Project from "./project" import Project from './project'
class Repo extends Project { class Repo extends Project {
constructor(ownerGitlabId:number, name:string, desc:string, id?:number, logo?:string, path?:string) { constructor (ownerGitlabId: number, name: string, desc: string, id?: number, logo?: string, path?: string) {
super(ownerGitlabId, name, desc, id, logo, path) super(ownerGitlabId, name, desc, id, logo, path)
} }
} }
export = Repo export = Repo
\ No newline at end of file
class User { class User {
id:number id: number
email:string email: string
salutation:string // should be enum salutation: string // should be enum
title:string // should be enum title: string // should be enum
firstName:string firstName: string
lastName:string lastName: string
industry:string industry: string
organisation:string organisation: string
speciality:string speciality: string
is_m4lab_idp:number // 1 or 0 is_m4lab_idp: number // 1 or 0
verificationStatus:number // 1 or 0 - // should be boolean verificationStatus: number // 1 or 0 - // should be boolean
gitlabUserId?:number gitlabUserId?: number
constructor(id:number, email:string, salutation:string, title:string, firstName:string, lastName:string, industry:string, organisation:string, 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, is_m4lab_idp: number, verificationStatus: number, gitlabUserId?: number) {
this.id = id this.id = id
this.email = email this.email = email
this.salutation = salutation this.salutation = salutation
this.title = title this.title = title
this.firstName = firstName this.firstName = firstName
this.lastName = lastName this.lastName = lastName
this.industry = industry this.industry = industry
this.organisation = organisation this.organisation = organisation
this.speciality = speciality this.speciality = speciality
this.is_m4lab_idp = is_m4lab_idp this.is_m4lab_idp = is_m4lab_idp
this.verificationStatus = verificationStatus this.verificationStatus = verificationStatus
this.gitlabUserId = gitlabUserId this.gitlabUserId = gitlabUserId
} }
// getter // getter
getId() { getId () {
return this.id return this.id
} }
getEmail() {
return this.email getEmail () {
} return this.email
getFullName() { }
return this.firstName+' '+this.lastName
} getFullName () {
getIdpStatus() { return this.firstName + ' ' + this.lastName
return this.is_m4lab_idp }
}
getVerificationStatus() { getIdpStatus () {
return this.verificationStatus return this.is_m4lab_idp
} }
getGitlabUserId() {
return this.gitlabUserId getVerificationStatus () {
} return this.verificationStatus
// setter }
setEmail(email:string) {
this.email = email getGitlabUserId () {
} return this.gitlabUserId
setSalutation(salutation:string) { }
this.salutation = salutation
} // setter
setTitle(title:string) { setEmail (email: string) {
this.title = title this.email = email
} }
setFirstName(firstName:string) {
this.firstName = firstName setSalutation (salutation: string) {
} this.salutation = salutation
setLastName(lastName:string) { }
this.lastName = lastName
} setTitle (title: string) {
setIndustry(industry:string) { this.title = title
this.industry = industry }
}
setOrganisation(organisation:string) { setFirstName (firstName: string) {
this.organisation = organisation this.firstName = firstName
} }
setSpeciality(speciality:string) {
this.speciality = speciality setLastName (lastName: string) {
} this.lastName = lastName
setM4lab_idp(m4lab_idp:number) { }
this.is_m4lab_idp = m4lab_idp
} setIndustry (industry: string) {
setVerificationStatus(verificationStatus:number) { this.industry = industry
this.verificationStatus = verificationStatus }
}
setGitlabUserId(newGitlabUserId:number) { setOrganisation (organisation: string) {
this.gitlabUserId = newGitlabUserId this.organisation = organisation
} }
updateProfile(newSalutation:string, newTitle:string, newFirstname:string, newLastname:string, newEmail:string, newOrganisation:string, newIndustry:string, newSpeciality:string) { setSpeciality (speciality: string) {
this.salutation = newSalutation this.speciality = speciality
this.title = newTitle }
this.firstName = newFirstname
this.lastName = newLastname setM4lab_idp (m4lab_idp: number) {
this.email = newEmail this.is_m4lab_idp = m4lab_idp
this.organisation = newOrganisation }
this.industry = newIndustry
this.speciality = newSpeciality setVerificationStatus (verificationStatus: number) {
} this.verificationStatus = verificationStatus
}
setGitlabUserId (newGitlabUserId: number) {
this.gitlabUserId = newGitlabUserId
}
updateProfile (newSalutation: string, newTitle: string, newFirstname: string, newLastname: string, newEmail: string, newOrganisation: string, newIndustry: string, newSpeciality: string) {
this.salutation = newSalutation
this.title = newTitle
this.firstName = newFirstname
this.lastName = newLastname
this.email = newEmail
this.organisation = newOrganisation
this.industry = newIndustry
this.speciality = newSpeciality
}
} }
export = User export = User
\ No newline at end of file
import Project from "./project" import Project from './project'
class Website extends Project { class Website extends Project {
constructor(ownerGitlabId:number, name:string, desc:string, id?:number, logo?:string, path?:string) { constructor (ownerGitlabId: number, name: string, desc: string, id?: number, logo?: string, path?: string) {
super(ownerGitlabId, name, desc, id, logo, path) super(ownerGitlabId, name, desc, id, logo, path)
} }
} }
export = Website export = Website
\ No newline at end of file
...@@ -10,32 +10,32 @@ export = { ...@@ -10,32 +10,32 @@ export = {
strategy: 'saml', strategy: 'saml',
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', entryPoint: 'https://transfer.hft-stuttgart.de/idp2/saml2/idp/SSOService.php',
issuer: 'SAML issuer', //local metadata issuer: 'sp-account.m4lab.hft-stuttgart.de',
logoutUrl: 'SAML logout URL' logoutUrl: 'https://transfer.hft-stuttgart.de/idp/saml2/idp2/SingleLogoutService.php'
} }
}, },
database: { database: {
host: 'localhost', // DB host host: 'localhost', // DB host
user: 'usernamedb', // DB username user: 'DBManager', // DB username
password: 'passworddb', // DB password password: 'Stuttgart2019', // DB password
port: 3306, // MySQL port port: 3306, // MySQL port
dbUser: 'userdb', // User DB dbUser: 'userdb', // User DB
host_project: 'localhost', // DB host project db host_project: 'localhost', // DB host project db
dbProject: 'projectdb' // Project DB dbProject: 'projectdb' // Project DB
}, },
mailer: { mailer: {
host: 'mailhost', // hostname host: 'mailhost', // hostname
secureConnection: false, // TLS requires secureConnection to be false secureConnection: false, // TLS requires secureConnection to be false
port: 587, // port for secure SMTP port: 587, // port for secure SMTP
TLS: true, TLS: true,
authUser: 'mailuser', authUser: 'mailuser',
authPass: 'mailpass', authPass: 'mailpass',
tlsCiphers: 'SSLv3', tlsCiphers: 'SSLv3',
from: 'mailfrom', from: 'mailfrom'
}, },
gitlab: { gitlab: {
token_readWriteProjects: 'token-goes-here' token_readWriteProjects: 'PfP27Tj4dNo9zgQ_c6XP'
} }
}, },
testing: { testing: {
...@@ -50,31 +50,31 @@ export = { ...@@ -50,31 +50,31 @@ export = {
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', entryPoint: process.env.SAML_ENTRY_POINT || 'saml entry point',
issuer: 'SAML issuer', //testing metadata issuer: 'SAML issuer', // testing metadata
logoutUrl: 'SAML logout URL' logoutUrl: 'SAML logout URL'
} }
}, },
database: { database: {
host: 'dbhost', // DB host host: 'dbhost', // DB host
user: 'dbuser', // DB username user: 'dbuser', // DB username
password: 'dbpass', // DB password password: 'dbpass', // DB password
port: 3306, // MySQL port port: 3306, // MySQL port
dbUser: 'userdb', // User DB dbUser: 'userdb', // User DB
host_project: 'dbhost', // DB host project db host_project: 'dbhost', // DB host project db
dbProject: 'projectdb' // Project DB dbProject: 'projectdb' // Project DB
}, },
mailer: { mailer: {
host: 'mailhost', // hostname host: 'mailhost', // hostname
secureConnection: false, // TLS requires secureConnection to be false secureConnection: false, // TLS requires secureConnection to be false
port: 587, // port for secure SMTP port: 587, // port for secure SMTP
TLS: true, TLS: true,
authUser: 'mailuser', authUser: 'mailuser',
authPass: 'mailpass', authPass: 'mailpass',
tlsCiphers: 'SSLv3', tlsCiphers: 'SSLv3',
from: 'mailfrom', from: 'mailfrom'
}, },
gitlab: { gitlab: {
token_readWriteProjects: 'token-goes-here' token_readWriteProjects: 'token-goes-here'
} }
} }
} }
\ No newline at end of file
export = { export = {
mailSignature: 'Mit den besten Grüßen,<br/>das Transferportal-Team der HFT Stuttgart<br/><br/>' + mailSignature: 'Mit den besten Grüßen,<br/>das Transferportal-Team der HFT Stuttgart<br/><br/>' +
'Transferportal der Hochschule für Technik Stuttgart<br/>' + 'Transferportal der Hochschule für Technik Stuttgart<br/>' +
'Schellingstr. 24 70174 Stuttgart<br/>' + 'Schellingstr. 24 70174 Stuttgart<br/>' +
'm4lab@hft-stuttgart.de<br/>' + 'm4lab@hft-stuttgart.de<br/>' +
...@@ -13,7 +13,7 @@ export = { ...@@ -13,7 +13,7 @@ export = {
'<a href="http://www.hft-stuttgart.de/Aktuell/Presse-Marketing/SocialMedia/Snapcode HFT_Stuttgart.jpg/photo_view">' + '<a href="http://www.hft-stuttgart.de/Aktuell/Presse-Marketing/SocialMedia/Snapcode HFT_Stuttgart.jpg/photo_view">' +
'<img border="0" alt="Snapchat" src="https://m4lab.hft-stuttgart.de/img/signature/snapchat_bw.png" width="30" height="30"></a>' + '<img border="0" alt="Snapchat" src="https://m4lab.hft-stuttgart.de/img/signature/snapchat_bw.png" width="30" height="30"></a>' +
'<br/><img border="0" src="https://m4lab.hft-stuttgart.de/img/signature/inno_bw.png" width="150" height="100">', '<br/><img border="0" src="https://m4lab.hft-stuttgart.de/img/signature/inno_bw.png" width="150" height="100">',
updatePasswordMailSubject: "Ihr Passwort für das Transferportal wurde gespeichert.", updatePasswordMailSubject: 'Ihr Passwort für das Transferportal wurde gespeichert.',
updatePasswordMailContent: '<div>Lieber Nutzer,<br/><br/>Ihr Passwort wurde erfolgreich geändert.<br/><br/></div>' updatePasswordMailContent: '<div>Lieber Nutzer,<br/><br/>Ihr Passwort wurde erfolgreich geändert.<br/><br/></div>'
} }
\ No newline at end of file
import mysql from 'mysql2' import mysql from 'mysql2'
var env = process.env.NODE_ENV || 'testing' const env = process.env.NODE_ENV || 'development'
const config = require('./config')[env] const config = require('./config')[env]
// ==== USER ACOOUNT DB CONNECTION ==== // ==== USER ACOOUNT DB CONNECTION ====
const userConnection = mysql.createPool({ const userConnection = mysql.createPool({
host: config.database.host, host: config.database.host,
user: config.database.user, user: config.database.user,
password: config.database.password, password: config.database.password,
port: config.database.port, port: config.database.port,
database: config.database.dbUser, database: config.database.dbUser,
waitForConnections: true, waitForConnections: true,
connectionLimit: 10, connectionLimit: 10,
queueLimit: 0 queueLimit: 0
}); })
userConnection.query('USE '+config.database.dbUser) userConnection.query('USE ' + config.database.dbUser)
// ==== PROJECT DB CONNECTION ==== // ==== PROJECT DB CONNECTION ====
const projectConnection = mysql.createPool({ const projectConnection = mysql.createPool({
host: config.database.host_project, host: config.database.host_project,
user: config.database.user, user: config.database.user,
password: config.database.password, password: config.database.password,
port: config.database.port, port: config.database.port,
database: config.database.dbProject, database: config.database.dbProject,
waitForConnections: true, waitForConnections: true,
connectionLimit: 10, connectionLimit: 10,
queueLimit: 0 queueLimit: 0
}); })
projectConnection.query('USE '+config.database.dbProject) projectConnection.query('USE ' + config.database.dbProject)
const connection = { const connection = {
user: userConnection, user: userConnection,
project: projectConnection project: projectConnection
} }
export = connection export = connection
\ No newline at end of file
const nodemailer = require('nodemailer') const nodemailer = require('nodemailer')
const nodemailerNTLMAuth = require('nodemailer-ntlm-auth') const nodemailerNTLMAuth = require('nodemailer-ntlm-auth')
var env = process.env.NODE_ENV || 'testing' const env = process.env.NODE_ENV || 'testing'
const config = require('./config')[env] const config = require('./config')[env]
var smtpTransporter = nodemailer.createTransport({ const smtpTransporter = nodemailer.createTransport({
host: config.mailer.host, host: config.mailer.host,
secure: config.mailer.secureConnection, secure: config.mailer.secureConnection,
port: config.mailer.port, port: config.mailer.port,
...@@ -18,23 +18,23 @@ var smtpTransporter = nodemailer.createTransport({ ...@@ -18,23 +18,23 @@ var smtpTransporter = nodemailer.createTransport({
domain: 'ad' domain: 'ad'
} }
}, },
customAuth:{ customAuth: {
NTLM: nodemailerNTLMAuth NTLM: nodemailerNTLMAuth
} }
}); })
var mailOptions:any = { const mailOptions: any = {
to: "", to: '',
cc: "", cc: '',
from: config.mailer.from, from: config.mailer.from,
subject: "", subject: '',
text: "", text: '',
html: "" html: ''
} }
var mailer:any = { const mailer: any = {
transporter: smtpTransporter, transporter: smtpTransporter,
options: mailOptions options: mailOptions
} }
export = mailer export = mailer
\ No newline at end of file
...@@ -2,127 +2,126 @@ import axios from 'axios' ...@@ -2,127 +2,126 @@ import axios from 'axios'
import fs from 'fs' import fs from 'fs'
import formData from 'form-data' import formData from 'form-data'
var env = process.env.NODE_ENV || 'testing' const env = process.env.NODE_ENV || 'testing'
const config = require('../config/config')[env] const config = require('../config/config')[env]
var gitlab = { const gitlab = {
getUserByEmail: async function(email:string) { getUserByEmail: async function (email: string) {
return axios({ return await axios({
method: 'get', method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/users?search='+email, url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/users?search=' + email,
headers: { headers: { Authorization: 'Bearer ' + config.gitlab.token_readWriteProjects }
'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects} })
}) .then(res => res.data[0])
.then(res => res.data[0]) .catch(function (err) {
.catch(function(err){ console.error(err)
console.error(err) return null
return null })
}) },
}, createNewPages: async function (newPagesData: any, newLogoFile: string, template: any) {
createNewPages: async function(newPagesData:any, newLogoFile:string, template:any) { const data = new formData()
let data = new formData() data.append('avatar', fs.createReadStream(newLogoFile))
data.append('avatar', fs.createReadStream(newLogoFile))
return axios({ return await axios({
method: 'post', method: 'post',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/user/'+newPagesData.getOwnerGitlabId()+ url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/user/' + newPagesData.getOwnerGitlabId() +
'?name='+newPagesData.getName()+'&description='+newPagesData.getDesc()+'&tag_list=website'+ '?name=' + newPagesData.getName() + '&description=' + newPagesData.getDesc() + '&tag_list=website' +
'&use_custom_template=true&template_name='+template, '&use_custom_template=true&template_name=' + template,
headers: { headers: {
'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects, Authorization: 'Bearer ' + config.gitlab.token_readWriteProjects,
...data.getHeaders() ...data.getHeaders()
}, },
data: data data: data
}) })
.then(res => res.data) .then(res => res.data)
.catch(function(err) { .catch(function (err) {
console.error("ERR Status: "+err.response.status) console.error('ERR Status: ' + err.response.status)
console.error("ERR Name: "+err.response.data.message.name) console.error('ERR Name: ' + err.response.data.message.name)
console.error("ERR Path: "+err.response.data.message.path) console.error('ERR Path: ' + err.response.data.message.path)
return err.response return err.response
}) })
}, },
updateProject: async function(updatedProjectData:any, newLogoFile:string){ updateProject: async function (updatedProjectData: any, newLogoFile: string) {
let data = new formData() const data = new formData()
if (newLogoFile) { if (newLogoFile) {
data.append('avatar', fs.createReadStream(newLogoFile)) data.append('avatar', fs.createReadStream(newLogoFile))
}
return axios({
method: 'put',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/'+updatedProjectData.getId()+
'?name='+updatedProjectData.getName()+'&description='+updatedProjectData.getDesc(),
headers: {
'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects,
...data.getHeaders()
},
data : data
})
//.then(res => res.data[0])
.then(res => res.data)
.catch(function(err){
console.error("ERR Status: "+err.response.status)
console.error("ERR Name: "+err.response.data.message.name)
console.error("ERR Path: "+err.response.data.message.path)
return err.response
})
},
deleteProjectById: function(projectId:number){
// https://docs.gitlab.com/ee/api/projects.html#delete-project
return axios({
method: 'delete',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/'+projectId,
headers: {
'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects
}
})
.then(res => true)
.catch(function(err) {
console.error("ERR Status: "+err.response.status)
console.error("ERR Name: "+err.response.data.message.name)
console.error("ERR Path: "+err.response.data.message.path)
return false
})
},
getUserProjects: async function(gitlabUserId:number) {
return axios({
method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/users/'+gitlabUserId+'/projects?owned=true&visibility=public',
headers: {
'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects
}
})
.then(res => res.data)
.catch(function(err) {
console.error(err)
return null
})
},
getProjectById: async function(projectId:number) {
return axios({
method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/'+projectId,
headers: {
'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects
}
})
.then(res => res.data)
.catch(function(err) {
console.error(err)
return null
})
},
getProjectPipelineLatestStatus: async function(projectId:number) {
return axios({
method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/'+projectId+'/pipelines'
})
.then(res => res.data[0].status)
.catch(function(err) {
console.error(err)
return null
})
} }
return await axios({
method: 'put',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/' + updatedProjectData.getId() +
'?name=' + updatedProjectData.getName() + '&description=' + updatedProjectData.getDesc(),
headers: {
Authorization: 'Bearer ' + config.gitlab.token_readWriteProjects,
...data.getHeaders()
},
data: data
})
// .then(res => res.data[0])
.then(res => res.data)
.catch(function (err) {
console.error('ERR Status: ' + err.response.status)
console.error('ERR Name: ' + err.response.data.message.name)
console.error('ERR Path: ' + err.response.data.message.path)
return err.response
})
},
deleteProjectById: async function (projectId: number) {
// https://docs.gitlab.com/ee/api/projects.html#delete-project
return await axios({
method: 'delete',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/' + projectId,
headers: {
Authorization: 'Bearer ' + config.gitlab.token_readWriteProjects
}
})
.then(res => true)
.catch(function (err) {
console.error('ERR Status: ' + err.response.status)
console.error('ERR Name: ' + err.response.data.message.name)
console.error('ERR Path: ' + err.response.data.message.path)
return false
})
},
getUserProjects: async function (gitlabUserId: number) {
return await axios({
method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/users/' + gitlabUserId + '/projects?owned=true&visibility=public',
headers: {
Authorization: 'Bearer ' + config.gitlab.token_readWriteProjects
}
})
.then(res => res.data)
.catch(function (err) {
console.error(err)
return null
})
},
getProjectById: async function (projectId: number) {
return await axios({
method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/' + projectId,
headers: {
Authorization: 'Bearer ' + config.gitlab.token_readWriteProjects
}
})
.then(res => res.data)
.catch(function (err) {
console.error(err)
return null
})
},
getProjectPipelineLatestStatus: async function (projectId: number) {
return await axios({
method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/' + projectId + '/pipelines'
})
.then(res => res.data[0].status)
.catch(function (err) {
console.error(err)
return null
})
}
} }
export = gitlab export = gitlab
\ No newline at end of file
var helpers = { const helpers = {
stringToArray: function (input:string){ stringToArray: function (input: string) {
if(input != null){ if (input != null) {
return input.split(','); return input.split(',')
}else{ } else {
return null; return null
}
} }
}; }
}
export = helpers; export = helpers
\ No newline at end of file
import dbconn = require('../config/dbconn') import dbconn = require('../config/dbconn')
var methods = { const methods = {
// ===================== user db ===================== // ===================== user db =====================
registerNewUser: function(data:any, callback:any) { registerNewUser: function (data: any, callback: any) {
dbconn.user.getConnection(function(err:any, thisconn){ dbconn.user.getConnection(function (err: any, thisconn) {
thisconn.beginTransaction(function(err:any) { // START TRANSACTION thisconn.beginTransaction(function (err: any) { // START TRANSACTION
if (err) { throw err } if (err) { throw err }
// insert profile // insert profile
thisconn.query('INSERT INTO user SET ?', data.profile, function (err:any, results:any, fields:any) { thisconn.query('INSERT INTO user SET ?', data.profile, function (err: any, results: any, fields: any) {
if (err) { if (err) {
return thisconn.rollback(function() { return thisconn.rollback(function () {
throw err throw err
}); })
} }
let newUserId:number = results.insertId const newUserId: number = results.insertId
// set password // set password
var credentialData:any = { const credentialData: any = {
user_id: newUserId, user_id: newUserId,
password: data.password password: data.password
} }
thisconn.query('INSERT INTO credential SET ?', credentialData, function (err:any, results:any, fields:any) { thisconn.query('INSERT INTO credential SET ?', credentialData, function (err: any, results: any, fields: any) {
if (err) { if (err) {
return thisconn.rollback(function() { return thisconn.rollback(function () {
throw err throw err
}); })
}
// set default user-project-role
var projectRoleData:any = {
project_id: 1, //M4_LAB
role_id: 2, // USER
user_id: newUserId
}
thisconn.query('INSERT INTO user_project_role SET ?', projectRoleData, function (err:any, results:any, fields:any) {
if (err) {
return thisconn.rollback(function() {
throw err
});
}
// MLAB-129: INSERT verification token
let verificationData:any = {
user_id: newUserId,
token: data.verificationToken
}
thisconn.query('INSERT INTO verification SET ?', verificationData, function (err:any, results:any, fields:any) {
if (err) {
return thisconn.rollback(function() {
throw err
});
}
// COMMIT
thisconn.commit(function(err:any) {
if (err) {
return thisconn.rollback(function() {
throw err
})
}
})
})
})
});
});
});
callback(err)
})
},
getUserByEmail: async function(email:any) {
try {
let rows:any = await dbconn.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 }
} catch (err) {
console.error(err)
}
return null
},
getUserEmailById: async function(userId:number) {
try {
let rows:any = await dbconn.user.promise().query('SELECT email FROM user WHERE id = ' +userId)
if (rows[0][0]) {
return rows[0][0].email
}
else { return null }
} catch (err) {
console.error(err)
}
return null
},
checkUserEmail: async function(email:any) {
try {
let rows:any = await dbconn.user.promise().query('SELECT id, email FROM user WHERE email = "' +email+'"')
if (rows[0][0]) {
return rows[0][0]
}
else { return null }
} catch (err) {
console.error(err)
}
return null
},
getUserByToken: async function(token:any) {
try {
let 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 = "'
+token+'" and resetPasswordExpires > '+Date.now())
if (rows[0][0]) {
return rows[0][0]
}
else { return null }
} catch (err) {
console.error(err)
}
return null
},
updateUserById: async function(userId:number, userData:any) {
try {
let result:any = await dbconn.user.promise().query('UPDATE user SET ? WHERE id = ' +userId, userData)
return result
} catch (err) {
console.error(err)
}
return null
},
updateCredential: async function(data:any) {
try {
let result:any = await dbconn.user.promise().query('UPDATE credential SET ? WHERE user_id = ' +data.user_id, data)
return result
} catch (err) {
console.error(err)
}
return null
},
addUserProjectRole_OBSOLETE: function(data:any, callback:any) {
dbconn.user.query('INSERT INTO user_project_role SET ?', data, function (err:any){
if (err) throw err
callback(err)
})
},
getVerificationTokenByUserId: async function(userId:number) {
try {
let rows:any = await dbconn.user.promise().query('SELECT token FROM verification WHERE user_id = "' +userId+'"')
if (rows[0][0]) {
return rows[0][0].token
}
else { return null }
} catch (err) {
console.error(err)
}
return null
},
getUserIdByVerificationToken: async function(token:any) {
try {
let rows:any = await dbconn.user.promise().query('SELECT user_id FROM verification WHERE token = "' +token+'"')
if (rows[0][0]) {
return rows[0][0].user_id
} }
else { // set default user-project-role
return null const projectRoleData: any = {
project_id: 1, // M4_LAB
role_id: 2, // USER
user_id: newUserId
} }
} catch (err) { thisconn.query('INSERT INTO user_project_role SET ?', projectRoleData, function (err: any, results: any, fields: any) {
console.error(err) if (err) {
} return thisconn.rollback(function () {
return null throw err
}, })
verifyUserAccount: function(userData:any, callback:any) { }
dbconn.user.getConnection(function(err:any, thisconn){ // MLAB-129: INSERT verification token
thisconn.beginTransaction(function(err:any) { // START TRANSACTION const verificationData: any = {
if (err) { throw err } user_id: newUserId,
// update user status token: data.verificationToken
thisconn.query('UPDATE user SET ? WHERE id =' +userData.id, userData, function (err:any, rows:any, fields:any) { }
if (err) { thisconn.query('INSERT INTO verification SET ?', verificationData, function (err: any, results: any, fields: any) {
return thisconn.rollback(function() { throw err }) if (err) {
} return thisconn.rollback(function () {
// delete verification token throw err
thisconn.query('DELETE FROM verification WHERE user_id = '+userData.id, function (err:any, rows:any, fields:any) { })
if (err) { }
return thisconn.rollback(function() { throw err }) // COMMIT
} thisconn.commit(function (err: any) {
// COMMIT if (err) {
thisconn.commit(function(err:any) { return thisconn.rollback(function () {
if (err) { throw err
return thisconn.rollback(function() { throw err })
}
})
}) })
}
}) })
})
}) })
callback(err) })
}) })
}, })
/* ===== GitLab ===== */ callback(err)
getGitlabId: async function(userId:number) { })
try { },
let 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') getUserByEmail: async function (email: any) {
if (rows[0][0]) { try {
return rows[0][0].gitlab_userId 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 + '"')
} else { if (rows[0][0]) {
return null return rows[0][0]
} else { return null }
} catch (err) {
console.error(err)
}
return null
},
getUserEmailById: async function (userId: number) {
try {
const rows: any = await dbconn.user.promise().query('SELECT email FROM user WHERE id = ' + userId)
if (rows[0][0]) {
return rows[0][0].email
} else { return null }
} catch (err) {
console.error(err)
}
return null
},
checkUserEmail: async function (email: any) {
try {
const rows: any = await dbconn.user.promise().query('SELECT id, email FROM user WHERE email = "' + email + '"')
if (rows[0][0]) {
return rows[0][0]
} else { return null }
} catch (err) {
console.error(err)
}
return null
},
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 = "' +
token + '" and resetPasswordExpires > ' + Date.now())
if (rows[0][0]) {
return rows[0][0]
} else { return null }
} catch (err) {
console.error(err)
}
return null
},
updateUserById: async function (userId: number, userData: any) {
try {
const result: any = await dbconn.user.promise().query('UPDATE user SET ? WHERE id = ' + userId, userData)
return result
} catch (err) {
console.error(err)
}
return null
},
updateCredential: async function (data: any) {
try {
const result: any = await dbconn.user.promise().query('UPDATE credential SET ? WHERE user_id = ' + data.user_id, data)
return result
} catch (err) {
console.error(err)
}
return null
},
addUserProjectRole_OBSOLETE: function (data: any, callback: any) {
dbconn.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 + '"')
if (rows[0][0]) {
return rows[0][0].token
} else { return null }
} catch (err) {
console.error(err)
}
return null
},
getUserIdByVerificationToken: async function (token: any) {
try {
const rows: any = await dbconn.user.promise().query('SELECT user_id FROM verification WHERE token = "' + token + '"')
if (rows[0][0]) {
return rows[0][0].user_id
} else {
return null
}
} catch (err) {
console.error(err)
}
return null
},
verifyUserAccount: function (userData: any, callback: any) {
dbconn.user.getConnection(function (err: any, thisconn) {
thisconn.beginTransaction(function (err: any) { // START TRANSACTION
if (err) { throw err }
// update user status
thisconn.query('UPDATE user SET ? WHERE id =' + userData.id, userData, function (err: any, rows: any, fields: any) {
if (err) {
return thisconn.rollback(function () { throw err })
}
// delete verification token
thisconn.query('DELETE FROM verification WHERE user_id = ' + userData.id, function (err: any, rows: any, fields: any) {
if (err) {
return thisconn.rollback(function () { throw err })
} }
} // COMMIT
catch(err) { thisconn.commit(function (err: any) {
console.error(err) if (err) {
return err return thisconn.rollback(function () { throw err })
} }
}, })
addGitlabUser: function(data:any, callback:any){ })
dbconn.user.query('INSERT INTO user_gitlab SET ?', data, function (err:any) {
if (err) throw err
callback(err)
}) })
})
callback(err)
})
},
/* ===== 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')
if (rows[0][0]) {
return rows[0][0].gitlab_userId
} else {
return null
}
} catch (err) {
console.error(err)
return err
} }
}; },
addGitlabUser: function (data: any, callback: any) {
dbconn.user.query('INSERT INTO user_gitlab SET ?', data, function (err: any) {
if (err) throw err
callback(err)
})
}
}
export = methods export = methods
This diff is collapsed.
...@@ -19,7 +19,8 @@ ...@@ -19,7 +19,8 @@
"start": "nodemon app.ts", "start": "nodemon app.ts",
"build": "tsc -build", "build": "tsc -build",
"clean": "tsc -build --clean", "clean": "tsc -build --clean",
"test": "jest" "test": "jest",
"clean-code": "ts-standard --fix"
}, },
"dependencies": { "dependencies": {
"async": "^3.1.0", "async": "^3.1.0",
...@@ -28,7 +29,6 @@ ...@@ -28,7 +29,6 @@
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
"compression": "^1.7.4", "compression": "^1.7.4",
"cookie-parser": "1.4.3", "cookie-parser": "1.4.3",
"dotenv": "^9.0.2",
"express": "^4.17.1", "express": "^4.17.1",
"express-fileupload": "^1.1.6", "express-fileupload": "^1.1.6",
"express-flash-2": "^1.0.1", "express-flash-2": "^1.0.1",
...@@ -36,7 +36,6 @@ ...@@ -36,7 +36,6 @@
"form-data": "^3.0.0", "form-data": "^3.0.0",
"fs": "0.0.1-security", "fs": "0.0.1-security",
"helmet": "^4.6.0", "helmet": "^4.6.0",
"jest": "^26.5.0",
"method-override": "^3.0.0", "method-override": "^3.0.0",
"morgan": "^1.9.1", "morgan": "^1.9.1",
"mysql2": "^2.2.5", "mysql2": "^2.2.5",
...@@ -55,7 +54,7 @@ ...@@ -55,7 +54,7 @@
"@types/express-fileupload": "^1.1.6", "@types/express-fileupload": "^1.1.6",
"@types/express-flash-2": "^1.0.6", "@types/express-flash-2": "^1.0.6",
"@types/express-session": "^1.17.0", "@types/express-session": "^1.17.0",
"@types/jest": "^26.0.23", "@types/jest": "^28.1.3",
"@types/method-override": "^0.0.31", "@types/method-override": "^0.0.31",
"@types/morgan": "^1.9.2", "@types/morgan": "^1.9.2",
"@types/mysql": "^2.15.18", "@types/mysql": "^2.15.18",
...@@ -64,8 +63,11 @@ ...@@ -64,8 +63,11 @@
"@types/passport": "^1.0.6", "@types/passport": "^1.0.6",
"@types/passport-strategy": "^0.2.35", "@types/passport-strategy": "^0.2.35",
"@types/xml2js": "^0.4.8", "@types/xml2js": "^0.4.8",
"jest": "^28.1.1",
"nodemon": "^2.0.1", "nodemon": "^2.0.1",
"ts-jest": "^28.0.5",
"ts-node": "^9.1.1", "ts-node": "^9.1.1",
"ts-standard": "^11.0.0",
"typescript": "^4.2.4" "typescript": "^4.2.4"
}, },
"engines": { "engines": {
......
// password requirement // password requirement
function checkPasswordReq(pwd) { function checkPasswordReq (pwd) {
if (pwd.length < 8) { if (pwd.length < 8) {
isBest = false; isBest = false
} else { } else {
isBest = true; isBest = true
} }
return isBest return isBest
} }
\ No newline at end of file
var menu = [{'name':'Informationen', 'combos':[{'name':'Projekte', 'link':'/project'}, {'name':'Über das M4_LAB', 'link':'/projectoverview?projectID=1'},{'name':'Kontakt', 'link':'/account/contact'}], 'type':'dropdown', 'link':'#'},{'name':'Zusammenarbeit', 'combos':[{'name':'Mailinglisten', 'link':'/mailinglists'},{'name':'Videokonferenzen', 'link':'/videoconference.html'},/* {'name':'...', 'link':'#'}*/], 'type':'dropdown', 'link':'#'},{'name':'Events', 'combos':[{'name':'Veranstaltungen der HfT', 'link':'http://www.hft-stuttgart.de/Aktuell/Veranstaltungen/'},{'name':'Veranstaltungen der HfT Forschung', 'link':'https://www.hft-stuttgart.de/forschung/veranstaltungen'}], 'type':'dropdown', 'link':'#'},{'name':'Benutzerkonto', 'combos': [], 'type':'', 'link':'/account/'}]; const menu = [{ name: 'Informationen', combos: [{ name: 'Projekte', link: '/project' }, { name: 'Über das M4_LAB', link: '/projectoverview?projectID=1' }, { name: 'Kontakt', link: '/account/contact' }], type: 'dropdown', link: '#' }, { name: 'Zusammenarbeit', combos: [{ name: 'Mailinglisten', link: '/mailinglists' }, { name: 'Videokonferenzen', link: '/videoconference.html' }/* {'name':'...', 'link':'#'} */], type: 'dropdown', link: '#' }, { name: 'Events', combos: [{ name: 'Veranstaltungen der HfT', link: 'http://www.hft-stuttgart.de/Aktuell/Veranstaltungen/' }, { name: 'Veranstaltungen der HfT Forschung', link: 'https://www.hft-stuttgart.de/forschung/veranstaltungen' }], type: 'dropdown', link: '#' }, { name: 'Benutzerkonto', combos: [], type: '', link: '/account/' }]
const hft_links = [{ url: '/account/contact', name: 'Kontakt' }, { url: 'https://www.hft-stuttgart.de/impressum', name: 'Impressum' }, { url: 'https://www.hft-stuttgart.de/datenschutz', name: 'Datenschutz' }]
var hft_links = [{'url':'/account/contact', 'name':'Kontakt'},{'url':'https://www.hft-stuttgart.de/impressum', 'name':'Impressum'},{'url':'https://www.hft-stuttgart.de/datenschutz', 'name':'Datenschutz'}] const socialmedias = [{ url: 'https://twitter.com/InnolabM4', name: 'fa-twitter' }, { url: 'https://www.facebook.com/HfTStuttgart/', name: 'fa-facebook-square' }, { url: 'https://www.instagram.com/m4_lab/', name: 'fa-instagram' }, { url: 'https://de.linkedin.com/school/hochschule-f%C3%BCr-technik-stuttgart-%E2%80%93-university-of-applied-sciences/', name: 'fa-linkedin' }, { url: 'https://www.youtube.com/channel/UCi0_JfF2qMZbOhOnNH5PyHA', name: 'fa-youtube' }]
var socialmedias = [{'url':'https://twitter.com/InnolabM4', 'name': 'fa-twitter'}, {'url':'https://www.facebook.com/HfTStuttgart/', 'name': 'fa-facebook-square'}, {'url':'https://www.instagram.com/m4_lab/', 'name': 'fa-instagram'}, {'url':'https://de.linkedin.com/school/hochschule-f%C3%BCr-technik-stuttgart-%E2%80%93-university-of-applied-sciences/', 'name': 'fa-linkedin'}, {'url':'https://www.youtube.com/channel/UCi0_JfF2qMZbOhOnNH5PyHA', 'name': 'fa-youtube'}]; const footer_images = [{ src: '/images/demo/Innovative_Hochschule_Initiative_BMBF_GWK_RGB.jpg', alt: 'Innovative Hochschule' }]
var footer_images = [/*{'src':'/images/demo/bbf_logo.png', 'alt':'BMBF'},*/ {'src':'/images/demo/Innovative_Hochschule_Initiative_BMBF_GWK_RGB.jpg', 'alt':'Innovative Hochschule'}] function prependChild (parent, child) {
parent.insertBefore(child, parent.childNodes[0])
function prependChild(parent,child){
parent.insertBefore(child, parent.childNodes[0]);
} }
function readCookie (cname) {
function readCookie(cname) { const name = cname + '='
var name = cname + "="; const decodedCookie = decodeURIComponent(document.cookie)
var decodedCookie = decodeURIComponent(document.cookie); const ca = decodedCookie.split(';')
var ca = decodedCookie.split(';'); for (let i = 0; i < ca.length; i++) {
for(var i = 0; i <ca.length; i++) { let c = ca[i]
var c = ca[i];
while (c.charAt(0) == ' ') { while (c.charAt(0) == ' ') {
c = c.substring(1); c = c.substring(1)
} }
if (c.indexOf(name) == 0) { if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length); return c.substring(name.length, c.length)
} }
} }
return ""; return ''
} }
function sendRequest(URL){ function sendRequest (URL) {
console.log(document.cookie); console.log(document.cookie)
let xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest()
xhr.open("POST", URL, true); xhr.open('POST', URL, true)
let token = readCookie("XSRF-TOKEN"); const token = readCookie('XSRF-TOKEN')
//Send the proper header information along with the request // Send the proper header information along with the request
xhr.setRequestHeader('X-CSRF-TOKEN', token); xhr.setRequestHeader('X-CSRF-TOKEN', token)
xhr.send(); xhr.send()
} }
/* function head() /* function head()
* creates header and prepends it to the documents body * creates header and prepends it to the documents body
*/ */
function head() { function head () {
let navheader = document.createElement("header"); const navheader = document.createElement('header')
navheader.id = "header"; navheader.id = 'header'
navheader.classList.add("clear"); navheader.classList.add('clear')
// disclaimer // disclaimer
let alertdiv = document.createElement("div"); const alertdiv = document.createElement('div')
alertdiv.classList.add("alert", "alert-danger", "alert-dismissible", "fade", "show"); alertdiv.classList.add('alert', 'alert-danger', 'alert-dismissible', 'fade', 'show')
alertdiv.style = "text-align:center;"; alertdiv.style = 'text-align:center;'
alertdiv.innerHTML="<strong>Disclaimer</strong> This website is under construction and in prototype-phase. It is not for public use." alertdiv.innerHTML = '<strong>Disclaimer</strong> This website is under construction and in prototype-phase. It is not for public use.'
let alertbutton = document.createElement("button"); const alertbutton = document.createElement('button')
alertbutton.type = "button"; alertbutton.type = 'button'
alertbutton.classList.add("close"); alertbutton.classList.add('close')
alertbutton.setAttribute("data-dismiss", "alert"); alertbutton.setAttribute('data-dismiss', 'alert')
alertbutton.innerHTML = "&times;"; alertbutton.innerHTML = '&times;'
prependChild(alertdiv, alertbutton); prependChild(alertdiv, alertbutton)
// navigation header // navigation header
let navbar = document.createElement("nav"); const navbar = document.createElement('nav')
navbar.classList.add("navbar", "navbar-expand-md", "navbar-light"); navbar.classList.add('navbar', 'navbar-expand-md', 'navbar-light')
navbar.style = "background-color: #ffffff;"; navbar.style = 'background-color: #ffffff;'
let navbarcontainer = document.createElement("div"); const navbarcontainer = document.createElement('div')
navbarcontainer.classList.add("container"); navbarcontainer.classList.add('container')
let navbarheader = document.createElement("div"); const navbarheader = document.createElement('div')
navbarheader.classList.add("navbar-header"); navbarheader.classList.add('navbar-header')
// navigation header - logo // navigation header - logo
let link_m4lab = document.createElement('a'); const link_m4lab = document.createElement('a')
link_m4lab.href = "/"; link_m4lab.href = '/'
link_m4lab.classList.add("navbar-brand"); link_m4lab.classList.add('navbar-brand')
link_m4lab.innerHTML = "<img src='/img/header/Logozeile_Header.png' alt='Logo Innovationslabor M4_LAB'>"; link_m4lab.innerHTML = "<img src='/img/header/Logozeile_Header.png' alt='Logo Innovationslabor M4_LAB'>"
navbarheader.appendChild(link_m4lab); navbarheader.appendChild(link_m4lab)
// navigation header - toggle button menu for mobile devices // navigation header - toggle button menu for mobile devices
let togglebutton = document.createElement('button'); const togglebutton = document.createElement('button')
togglebutton.classList.add("navbar-toggler") togglebutton.classList.add('navbar-toggler')
togglebutton.type = "button"; togglebutton.type = 'button'
togglebutton.setAttribute("data-toggle", "collapse"); togglebutton.setAttribute('data-toggle', 'collapse')
togglebutton.setAttribute("data-target", "#navbarCollapse"); togglebutton.setAttribute('data-target', '#navbarCollapse')
togglebutton.setAttribute("aria-controls", "navbarCollapse"); togglebutton.setAttribute('aria-controls', 'navbarCollapse')
togglebutton.setAttribute("aria-expanded", "false"); togglebutton.setAttribute('aria-expanded', 'false')
togglebutton.setAttribute("aria-label", "Toggle navigation"); togglebutton.setAttribute('aria-label', 'Toggle navigation')
togglebutton.innerHTML = "<span class='navbar-toggler-icon'></span>"; togglebutton.innerHTML = "<span class='navbar-toggler-icon'></span>"
// nav menu // nav menu
let navelements = document.createElement('ul'); const navelements = document.createElement('ul')
navelements.id="navbarCollapse"; navelements.id = 'navbarCollapse'
navelements.classList.add("collapse", "nav", "navbar-collapse", "navbar-nav", "justify-content-end"); navelements.classList.add('collapse', 'nav', 'navbar-collapse', 'navbar-nav', 'justify-content-end')
for(let j = 0; j<menu.length; j++){ for (let j = 0; j < menu.length; j++) {
let headitem = document.createElement('li'); const headitem = document.createElement('li')
let itemtype = menu[j].type; const itemtype = menu[j].type
headitem.classList.add("nav-item") headitem.classList.add('nav-item')
let headlink = document.createElement('a'); const headlink = document.createElement('a')
headlink.href=menu[j].link; headlink.href = menu[j].link
headlink.id="navbarDropdown" + j; headlink.id = 'navbarDropdown' + j
headlink.classList.add('nav-link'); headlink.classList.add('nav-link')
headlink.setAttribute("role", "button"); headlink.setAttribute('role', 'button')
if(itemtype=='dropdown'){ if (itemtype == 'dropdown') {
headitem.classList.add("dropdown"); headitem.classList.add('dropdown')
headlink.classList.add('dropdown-toggle'); headlink.classList.add('dropdown-toggle')
headlink.setAttribute("data-toggle", "dropdown"); headlink.setAttribute('data-toggle', 'dropdown')
headlink.setAttribute("aria-haspopup", "true"); headlink.setAttribute('aria-haspopup', 'true')
headlink.setAttribute("aria-expanded", "false"); headlink.setAttribute('aria-expanded', 'false')
}
headlink.innerHTML=menu[j].name;
if(itemtype=='dropdown'){
let combodiv = document.createElement('div');
combodiv.id=headlink.id+"_par";
combodiv.setAttribute("aria-labelledby",headlink.id);
combodiv.classList.add("dropdown-menu");
for(let k = 0; k< menu[j].combos.length; k++){
let combolink = document.createElement('a');
combolink.classList.add("dropdown-item");
combolink.href = menu[j].combos[k].link;
combolink.innerHTML = menu[j].combos[k].name;
combodiv.appendChild(combolink);
}
headitem.appendChild(combodiv);
}
prependChild(headitem, headlink)
navelements.appendChild(headitem);
} }
headlink.innerHTML = menu[j].name
if (itemtype == 'dropdown') {
const combodiv = document.createElement('div')
combodiv.id = headlink.id + '_par'
combodiv.setAttribute('aria-labelledby', headlink.id)
combodiv.classList.add('dropdown-menu')
for (let k = 0; k < menu[j].combos.length; k++) {
const combolink = document.createElement('a')
combolink.classList.add('dropdown-item')
combolink.href = menu[j].combos[k].link
combolink.innerHTML = menu[j].combos[k].name
combodiv.appendChild(combolink)
}
headitem.appendChild(combodiv)
}
prependChild(headitem, headlink)
navelements.appendChild(headitem)
}
navbarcontainer.appendChild(navbarheader); navbarcontainer.appendChild(navbarheader)
navbarcontainer.appendChild(togglebutton); navbarcontainer.appendChild(togglebutton)
navbarcontainer.appendChild(navelements); navbarcontainer.appendChild(navelements)
navbar.appendChild(navbarcontainer) navbar.appendChild(navbarcontainer)
navheader.appendChild(alertdiv); navheader.appendChild(alertdiv)
navheader.appendChild(navbar); navheader.appendChild(navbar)
prependChild(document.body, navheader); prependChild(document.body, navheader)
} }
/* function foot() /* function foot()
* creates footer and appends it to the documents body * creates footer and appends it to the documents body
*/ */
function foot() { function foot () {
// add styles to <head> to manage sticky footer // add styles to <head> to manage sticky footer
var styles = ` const styles = `
@media only screen and (min-width: 768px) { @media only screen and (min-width: 768px) {
html { html {
position: relative; position: relative;
...@@ -158,70 +155,70 @@ function foot() { ...@@ -158,70 +155,70 @@ function foot() {
} }
} }
` `
var styleSheet = document.createElement("style") const styleSheet = document.createElement('style')
styleSheet.type = "text/css" styleSheet.type = 'text/css'
styleSheet.innerText = styles styleSheet.innerText = styles
document.head.appendChild(styleSheet) document.head.appendChild(styleSheet)
let footerdiv = document.createElement('div'); const footerdiv = document.createElement('div')
footerdiv.id="homepage"; footerdiv.id = 'homepage'
//footerdiv.classList.add("last", "clear"); // footerdiv.classList.add("last", "clear");
footerdiv.innerHTML = "<hr>"; footerdiv.innerHTML = '<hr>'
let containerdiv = document.createElement('div'); const containerdiv = document.createElement('div')
containerdiv.classList.add('container'); containerdiv.classList.add('container')
let containerdivrow = document.createElement('div'); const containerdivrow = document.createElement('div')
containerdivrow.classList.add('row'); containerdivrow.classList.add('row')
//bmbf // bmbf
let bmbf = document.createElement('div'); const bmbf = document.createElement('div')
bmbf.classList.add("col-md-auto"); bmbf.classList.add('col-md-auto')
bmbf.innerHTML = "<img src='/img/footer/Innovative_Hochschule_Initiative_BMBF_GWK_RGB.png' alt='Innovative Hochschule' style='height:90px'/>" bmbf.innerHTML = "<img src='/img/footer/Innovative_Hochschule_Initiative_BMBF_GWK_RGB.png' alt='Innovative Hochschule' style='height:90px'/>"
//m4labgrau // m4labgrau
let m4labgrau = document.createElement('div'); const m4labgrau = document.createElement('div')
m4labgrau.classList.add("col-md-auto"); m4labgrau.classList.add('col-md-auto')
m4labgrau.innerHTML = "<img src='/img/footer/M4_LAB_LOGO_Graustufen.png' alt='M4_LAB' style='height:80px'/>" m4labgrau.innerHTML = "<img src='/img/footer/M4_LAB_LOGO_Graustufen.png' alt='M4_LAB' style='height:80px'/>"
// socmed // socmed
let socialdiv = document.createElement('div'); const socialdiv = document.createElement('div')
socialdiv.classList.add("col-md-auto"); socialdiv.classList.add('col-md-auto')
let socialrow = document.createElement('div'); const socialrow = document.createElement('div')
socialrow.id="socialmediabuttons"; socialrow.id = 'socialmediabuttons'
for(let j = 0; j< socialmedias.length; j++){ for (let j = 0; j < socialmedias.length; j++) {
let sociallink = document.createElement('a'); const sociallink = document.createElement('a')
sociallink.href = socialmedias[j].url; sociallink.href = socialmedias[j].url
let socialcontent = document.createElement('i'); const socialcontent = document.createElement('i')
socialcontent.classList.add("fab", socialmedias[j].name); socialcontent.classList.add('fab', socialmedias[j].name)
sociallink.appendChild(socialcontent); sociallink.appendChild(socialcontent)
socialrow.appendChild(sociallink); socialrow.appendChild(sociallink)
socialrow.innerHTML+="&nbsp;"; socialrow.innerHTML += '&nbsp;'
} }
socialdiv.appendChild(socialrow); socialdiv.appendChild(socialrow)
// contact // contact
let contactdiv = document.createElement('div'); const contactdiv = document.createElement('div')
contactdiv.classList.add("col-md-auto", "footer-unten") contactdiv.classList.add('col-md-auto', 'footer-unten')
contactdiv.innerHTML="Hochschule für Technik Stuttgart"; contactdiv.innerHTML = 'Hochschule für Technik Stuttgart'
let rowdiv = document.createElement('div'); const rowdiv = document.createElement('div')
rowdiv.classList.add("row"); rowdiv.classList.add('row')
for(let i = 0; i<hft_links.length; i++){ for (let i = 0; i < hft_links.length; i++) {
let coldiv = document.createElement('div'); const coldiv = document.createElement('div')
coldiv.classList.add("contactrow", "footer-unten"); coldiv.classList.add('contactrow', 'footer-unten')
let collink = document.createElement('a'); const collink = document.createElement('a')
collink.innerHTML = hft_links[i].name; collink.innerHTML = hft_links[i].name
collink.classList.add("contact-lower") collink.classList.add('contact-lower')
collink.href = hft_links[i].url; collink.href = hft_links[i].url
coldiv.appendChild(collink) coldiv.appendChild(collink)
rowdiv.appendChild(coldiv); rowdiv.appendChild(coldiv)
} }
contactdiv.appendChild(rowdiv); contactdiv.appendChild(rowdiv)
containerdivrow.appendChild(bmbf); containerdivrow.appendChild(bmbf)
containerdivrow.appendChild(m4labgrau); containerdivrow.appendChild(m4labgrau)
containerdivrow.appendChild(socialdiv); containerdivrow.appendChild(socialdiv)
containerdivrow.appendChild(contactdiv); containerdivrow.appendChild(contactdiv)
containerdiv.appendChild(containerdivrow); containerdiv.appendChild(containerdivrow)
footerdiv.appendChild(containerdiv); footerdiv.appendChild(containerdiv)
document.body.appendChild(footerdiv); document.body.appendChild(footerdiv)
} }
head(); head()
foot(); foot()
var menu = [{'name':'Informationen', 'combos':[{'name':'Projekte', 'link':'/project'}, {'name':'Über das M4_LAB', 'link':'/projectoverview?projectID=1'}], 'type':'dropdown', 'link':'#'},{'name':'Zusammenarbeit', 'combos':[{'name':'Mailinglisten', 'link':'/mailinglists'},{'name':'Videokonferenzen', 'link':'/videoconference.html'},/* {'name':'...', 'link':'#'}*/], 'type':'dropdown', 'link':'#'},{'name':'Events', 'combos':[{'name':'Veranstaltungen der HfT', 'link':'http://www.hft-stuttgart.de/Aktuell/Veranstaltungen/'}/*,{'name':'...', 'link':'#'}*/], 'type':'dropdown', 'link':'#'},/*{'name':'Bürgerbeteiligung', 'combos':[{'name':'...', 'link':'#'}, {'name':'...', 'link':'#'}], 'type':'dropdown', 'link':'#'},*/{'name':'Logout', 'combos':[], 'type':'logoutbutton', 'link':'/logout'}]; const menu = [{ name: 'Informationen', combos: [{ name: 'Projekte', link: '/project' }, { name: 'Über das M4_LAB', link: '/projectoverview?projectID=1' }], type: 'dropdown', link: '#' }, { name: 'Zusammenarbeit', combos: [{ name: 'Mailinglisten', link: '/mailinglists' }, { name: 'Videokonferenzen', link: '/videoconference.html' }/* {'name':'...', 'link':'#'} */], type: 'dropdown', link: '#' }, { name: 'Events', combos: [{ name: 'Veranstaltungen der HfT', link: 'http://www.hft-stuttgart.de/Aktuell/Veranstaltungen/' }/*, {'name':'...', 'link':'#'} */], type: 'dropdown', link: '#' }, /* {'name':'Bürgerbeteiligung', 'combos':[{'name':'...', 'link':'#'}, {'name':'...', 'link':'#'}], 'type':'dropdown', 'link':'#'}, */{ name: 'Logout', combos: [], type: 'logoutbutton', link: '/logout' }]
const hft_links = [{ url: 'http://www.hft-stuttgart.de/Forschung/M4-Lab/Team/index.html/de', name: 'Kontakt' }, { url: 'http://www.hft-stuttgart.de/Hochschule/Impressum.html/de', name: 'Impressum' }, { url: 'http://www.hft-stuttgart.de/Einrichtungen/Datenschutz/Datenschutz-Homepage', name: 'Datenschutz' }]
var hft_links = [{'url':'http://www.hft-stuttgart.de/Forschung/M4-Lab/Team/index.html/de', 'name':'Kontakt'},{'url':'http://www.hft-stuttgart.de/Hochschule/Impressum.html/de', 'name':'Impressum'},{'url':'http://www.hft-stuttgart.de/Einrichtungen/Datenschutz/Datenschutz-Homepage', 'name':'Datenschutz'}] const socialmedias = [{ url: 'https://twitter.com/InnolabM4', name: 'fa-twitter' }, { url: 'https://www.facebook.com/HfTStuttgart/', name: 'fa-facebook-square' }, { url: 'https://www.instagram.com/m4_lab/', name: 'fa-instagram' }, { url: 'https://de.linkedin.com/school/hochschule-f%C3%BCr-technik-stuttgart-%E2%80%93-university-of-applied-sciences/', name: 'fa-linkedin' }, { url: 'https://www.youtube.com/channel/UCi0_JfF2qMZbOhOnNH5PyHA', name: 'fa-youtube' }]
var socialmedias = [{'url':'https://twitter.com/InnolabM4', 'name': 'fa-twitter'}, {'url':'https://www.facebook.com/HfTStuttgart/', 'name': 'fa-facebook-square'}, {'url':'https://www.instagram.com/m4_lab/', 'name': 'fa-instagram'}, {'url':'https://de.linkedin.com/school/hochschule-f%C3%BCr-technik-stuttgart-%E2%80%93-university-of-applied-sciences/', 'name': 'fa-linkedin'}, {'url':'https://www.youtube.com/channel/UCi0_JfF2qMZbOhOnNH5PyHA', 'name': 'fa-youtube'}]; const footer_images = [{ src: '/images/demo/Innovative_Hochschule_Initiative_BMBF_GWK_RGB.jpg', alt: 'Innovative Hochschule' }]
var footer_images = [/*{'src':'/images/demo/bbf_logo.png', 'alt':'BMBF'},*/ {'src':'/images/demo/Innovative_Hochschule_Initiative_BMBF_GWK_RGB.jpg', 'alt':'Innovative Hochschule'}] function prependChild (parent, child) {
parent.insertBefore(child, parent.childNodes[0])
function prependChild(parent,child){
parent.insertBefore(child, parent.childNodes[0]);
} }
function userAuthenticated(){ function userAuthenticated () {
let params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search)
if(params.get('isAuthenticatedUser')){ if (params.get('isAuthenticatedUser')) {
return true; return true
}else if(document.getElementById('loginswitch')){ //relikt login via OAuth } else if (document.getElementById('loginswitch')) { // relikt login via OAuth
if(document.getElementById('loginswitch').getAttribute('authenticated') == '1'){ if (document.getElementById('loginswitch').getAttribute('authenticated') == '1') {
return true; return true
}
}else{
return false;
} }
} else {
return false
}
} }
function readCookie (cname) {
function readCookie(cname) { const name = cname + '='
var name = cname + "="; const decodedCookie = decodeURIComponent(document.cookie)
var decodedCookie = decodeURIComponent(document.cookie); const ca = decodedCookie.split(';')
var ca = decodedCookie.split(';'); for (let i = 0; i < ca.length; i++) {
for(var i = 0; i <ca.length; i++) { let c = ca[i]
var c = ca[i];
while (c.charAt(0) == ' ') { while (c.charAt(0) == ' ') {
c = c.substring(1); c = c.substring(1)
} }
if (c.indexOf(name) == 0) { if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length); return c.substring(name.length, c.length)
} }
} }
return ""; return ''
} }
function sendRequest(URL){ function sendRequest (URL) {
console.log(document.cookie); console.log(document.cookie)
let xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest()
xhr.open("POST", URL, true); xhr.open('POST', URL, true)
let token = readCookie("XSRF-TOKEN"); const token = readCookie('XSRF-TOKEN')
//Send the proper header information along with the request // Send the proper header information along with the request
xhr.setRequestHeader('X-CSRF-TOKEN', token); xhr.setRequestHeader('X-CSRF-TOKEN', token)
xhr.send(); xhr.send()
} }
/* function head() /* function head()
* creates header and prepends it to the documents body * creates header and prepends it to the documents body
*/ */
function head(){ function head () {
let headerdiv = document.createElement('div'); const headerdiv = document.createElement('div')
let alertdiv = document.createElement('div'); const alertdiv = document.createElement('div')
headerdiv.classList.add("wrapper","row1"); headerdiv.classList.add('wrapper', 'row1')
let navheader = document.createElement('header'); const navheader = document.createElement('header')
navheader.id = "header"; navheader.id = 'header'
navheader.classList.add("clear"); navheader.classList.add('clear')
let alertbutton = document.createElement('button'); const alertbutton = document.createElement('button')
alertbutton.type = "button"; alertbutton.type = 'button'
alertbutton.classList.add("close"); alertbutton.classList.add('close')
alertbutton.setAttribute("data-dismiss", "alert"); alertbutton.setAttribute('data-dismiss', 'alert')
alertbutton.innerHTML = "&times;"; alertbutton.innerHTML = '&times;'
alertdiv.innerHTML="<strong>Disclaimer</strong> This website is under construction and in prototype-phase. It is not for public use." alertdiv.innerHTML = '<strong>Disclaimer</strong> This website is under construction and in prototype-phase. It is not for public use.'
prependChild(alertdiv, alertbutton); prependChild(alertdiv, alertbutton)
alertdiv.classList.add('alert','alert-danger', 'alert-dismissible', 'fade','show', 'text-center'); alertdiv.classList.add('alert', 'alert-danger', 'alert-dismissible', 'fade', 'show', 'text-center')
//alertdiv.style = "text-align:center;"; // alertdiv.style = "text-align:center;";
navheader.appendChild(alertdiv); navheader.appendChild(alertdiv)
let navbar = document.createElement('nav'); const navbar = document.createElement('nav')
navbar.classList.add("navbar", "navbar-default"); navbar.classList.add('navbar', 'navbar-default')
let fluiddiv = document.createElement('div'); const fluiddiv = document.createElement('div')
fluiddiv.classList.add("container-fluid"); fluiddiv.classList.add('container-fluid')
let navbardiv = document.createElement('div'); const navbardiv = document.createElement('div')
navbardiv.classList.add("navbar-header"); navbardiv.classList.add('navbar-header')
let navelements = document.createElement('ul'); const navelements = document.createElement('ul')
navelements.id="navelemente"; navelements.id = 'navelemente'
let logos = document.createElement('li'); const logos = document.createElement('li')
let link_m4lab = document.createElement('a'); const link_m4lab = document.createElement('a')
link_m4lab.href = "/"; link_m4lab.href = '/'
link_m4lab.innerHTML = "<img src='/images/demo/m4lab_logo.jpg' alt='Logo Innovationslabor M4_LAB'>"; link_m4lab.innerHTML = "<img src='/images/demo/m4lab_logo.jpg' alt='Logo Innovationslabor M4_LAB'>"
logos.appendChild(link_m4lab); logos.appendChild(link_m4lab)
navelements.appendChild(logos); navelements.appendChild(logos)
for(let j = 0; j<menu.length; j++){ for (let j = 0; j < menu.length; j++) {
let headitem = document.createElement('li'); const headitem = document.createElement('li')
let itemtype = menu[j].type; const itemtype = menu[j].type
headitem.classList.add("nav-item") headitem.classList.add('nav-item')
let headlink = document.createElement('a'); const headlink = document.createElement('a')
headlink.href=menu[j].link; headlink.href = menu[j].link
headlink.id="navbarDropdown" + j; headlink.id = 'navbarDropdown' + j
headlink.classList.add('nav-link'); headlink.classList.add('nav-link')
headlink.setAttribute("role", "button"); headlink.setAttribute('role', 'button')
if(itemtype=='dropdown'){ if (itemtype == 'dropdown') {
headitem.classList.add("dropdown"); headitem.classList.add('dropdown')
headlink.classList.add('dropdown-toggle'); headlink.classList.add('dropdown-toggle')
headlink.setAttribute("data-toggle", "dropdown"); headlink.setAttribute('data-toggle', 'dropdown')
headlink.setAttribute("aria-haspopup", "true"); headlink.setAttribute('aria-haspopup', 'true')
headlink.setAttribute("aria-expanded", "false"); headlink.setAttribute('aria-expanded', 'false')
}
headlink.innerHTML = menu[j].name
if (itemtype == 'dropdown') {
const combodiv = document.createElement('div')
combodiv.id = headlink.id + '_par'
combodiv.setAttribute('aria-labelledby', headlink.id)
combodiv.classList.add('dropdown-menu')
for (let k = 0; k < menu[j].combos.length; k++) {
const combolink = document.createElement('a')
combolink.classList.add('dropdown-item')
if (userAuthenticated() || typeof user !== 'undefined') { // either logged in the old way or logged in using SAML
if (menu[j].combos[k].link.includes('?')) {
combolink.href = menu[j].combos[k].link + '&isAuthenticatedUser=true'
} else {
combolink.href = menu[j].combos[k].link + '?isAuthenticatedUser=true'
}
} else {
combolink.href = menu[j].combos[k].link
} }
headlink.innerHTML=menu[j].name; combolink.innerHTML = menu[j].combos[k].name
if(itemtype=='dropdown'){ combodiv.appendChild(combolink)
let combodiv = document.createElement('div'); }
combodiv.id=headlink.id+"_par"; headitem.appendChild(combodiv)
combodiv.setAttribute("aria-labelledby",headlink.id); } else if (itemtype == 'logoutbutton') {
combodiv.classList.add("dropdown-menu"); /* if(userAuthenticated()){
for(let k = 0; k< menu[j].combos.length; k++){
let combolink = document.createElement('a');
combolink.classList.add("dropdown-item");
if(userAuthenticated() || typeof user !== 'undefined'){ //either logged in the old way or logged in using SAML
if(menu[j].combos[k].link.includes('?')){
combolink.href = menu[j].combos[k].link + "&isAuthenticatedUser=true";
}else{
combolink.href = menu[j].combos[k].link + "?isAuthenticatedUser=true";
}
}else{
combolink.href = menu[j].combos[k].link;
}
combolink.innerHTML = menu[j].combos[k].name;
combodiv.appendChild(combolink);
}
headitem.appendChild(combodiv);
}else if(itemtype=='logoutbutton'){
/* if(userAuthenticated()){
headlink.innerHTML="Account"; headlink.innerHTML="Account";
headlink.href="/account/"; headlink.href="/account/";
} */ } */
headlink.innerHTML="Logout"; headlink.innerHTML = 'Logout'
headlink.href="/logout"; headlink.href = '/logout'
headlink.classList.remove("nav-link"); headlink.classList.remove('nav-link')
headlink.classList.add("btn"); headlink.classList.add('btn')
headlink.classList.add("btn-outline-danger"); headlink.classList.add('btn-outline-danger')
}
headitem.appendChild(headlink);
navelements.appendChild(headitem);
} }
/* let searchitem = document.createElement('li'); headitem.appendChild(headlink)
navelements.appendChild(headitem)
}
/* let searchitem = document.createElement('li');
searchitem.classList.add("nav-item"); searchitem.classList.add("nav-item");
let searchinput = document.createElement('input'); let searchinput = document.createElement('input');
searchinput.value='Suche...' searchinput.value='Suche...'
...@@ -156,86 +153,85 @@ function head(){ ...@@ -156,86 +153,85 @@ function head(){
magnifier.id="sf_submit"; magnifier.id="sf_submit";
magnifier.value="search"; magnifier.value="search";
searchitem.appendChild(magnifier); searchitem.appendChild(magnifier);
navelements.appendChild(searchitem);*/ navelements.appendChild(searchitem); */
navbardiv.appendChild(navelements); navbardiv.appendChild(navelements)
fluiddiv.appendChild(navbardiv); fluiddiv.appendChild(navbardiv)
navbar.appendChild(fluiddiv); navbar.appendChild(fluiddiv)
navheader.appendChild(navbar); navheader.appendChild(navbar)
headerdiv.appendChild(navheader); headerdiv.appendChild(navheader)
prependChild(document.body, headerdiv); prependChild(document.body, headerdiv)
}; };
/* function foot() /* function foot()
* creates footer and appends it to the documents body * creates footer and appends it to the documents body
*/ */
function foot(){ function foot () {
let footerdiv = document.createElement('div'); const footerdiv = document.createElement('div')
footerdiv.id="homepage"; footerdiv.id = 'homepage'
footerdiv.classList.add("last", "clear"); footerdiv.classList.add('last', 'clear')
footerdiv.innerHTML = "<hr>"; footerdiv.innerHTML = '<hr>'
let containerdiv = document.createElement('div'); const containerdiv = document.createElement('div')
containerdiv.classList.add('flex-container'); containerdiv.classList.add('flex-container')
let hftlink = document.createElement('a'); const hftlink = document.createElement('a')
hftlink.classList.add("col-md-3"); hftlink.classList.add('col-md-3')
hftlink.setAttribute('style','flex-basis: 400px;'); hftlink.setAttribute('style', 'flex-basis: 400px;')
hftlink.href="https://www.hft-stuttgart.de"; hftlink.href = 'https://www.hft-stuttgart.de'
let hftimage = document.createElement('img'); const hftimage = document.createElement('img')
hftimage.src="/images/demo/hft_logo.jpg"; hftimage.src = '/images/demo/hft_logo.jpg'
hftimage.alt="Logo der Hochschule für Technik Stuttgart"; hftimage.alt = 'Logo der Hochschule für Technik Stuttgart'
hftimage.height= '75'; hftimage.height = '75'
hftlink.appendChild(hftimage); hftlink.appendChild(hftimage)
containerdiv.appendChild(hftlink); containerdiv.appendChild(hftlink)
let contactdiv = document.createElement('div'); const contactdiv = document.createElement('div')
contactdiv.classList.add("col-md-3", "footer-unten") contactdiv.classList.add('col-md-3', 'footer-unten')
contactdiv.setAttribute('style',"flex-basis:400px"); contactdiv.setAttribute('style', 'flex-basis:400px')
contactdiv.innerHTML="Hochschule für Technik Stuttgart"; contactdiv.innerHTML = 'Hochschule für Technik Stuttgart'
let rowdiv = document.createElement('div'); const rowdiv = document.createElement('div')
rowdiv.classList.add("row"); rowdiv.classList.add('row')
for(let i = 0; i<hft_links.length; i++){ for (let i = 0; i < hft_links.length; i++) {
let coldiv = document.createElement('div'); const coldiv = document.createElement('div')
coldiv.classList.add("contactrow", "footer-unten"); coldiv.classList.add('contactrow', 'footer-unten')
let collink = document.createElement('a'); const collink = document.createElement('a')
collink.innerHTML = hft_links[i].name; collink.innerHTML = hft_links[i].name
collink.classList.add("contact-lower") collink.classList.add('contact-lower')
collink.href = hft_links[i].url; collink.href = hft_links[i].url
coldiv.appendChild(collink) coldiv.appendChild(collink)
rowdiv.appendChild(coldiv); rowdiv.appendChild(coldiv)
} }
contactdiv.appendChild(rowdiv); contactdiv.appendChild(rowdiv)
containerdiv.appendChild(contactdiv); containerdiv.appendChild(contactdiv)
let socialdiv = document.createElement('div'); const socialdiv = document.createElement('div')
socialdiv.classList.add("col-md-3"); socialdiv.classList.add('col-md-3')
socialdiv.setAttribute('style','flex-basis: 400px;'); socialdiv.setAttribute('style', 'flex-basis: 400px;')
let socialrow = document.createElement('div'); const socialrow = document.createElement('div')
socialrow.id="socialmediabuttons"; socialrow.id = 'socialmediabuttons'
for(let j = 0; j< socialmedias.length; j++){ for (let j = 0; j < socialmedias.length; j++) {
let sociallink = document.createElement('a'); const sociallink = document.createElement('a')
sociallink.href = socialmedias[j].url; sociallink.href = socialmedias[j].url
let socialcontent = document.createElement('i'); const socialcontent = document.createElement('i')
socialcontent.classList.add("fab", socialmedias[j].name); socialcontent.classList.add('fab', socialmedias[j].name)
sociallink.appendChild(socialcontent); sociallink.appendChild(socialcontent)
socialrow.appendChild(sociallink); socialrow.appendChild(sociallink)
socialrow.innerHTML+="&nbsp;"; socialrow.innerHTML += '&nbsp;'
} }
socialdiv.appendChild(socialrow); socialdiv.appendChild(socialrow)
containerdiv.appendChild(socialdiv); containerdiv.appendChild(socialdiv)
let imagediv = document.createElement('div'); const imagediv = document.createElement('div')
imagediv.classList.add("col-md-3"); imagediv.classList.add('col-md-3')
imagediv.setAttribute("style", "flex-basis:400px;"); imagediv.setAttribute('style', 'flex-basis:400px;')
for (let k = 0; k< footer_images.length; k++){ for (let k = 0; k < footer_images.length; k++) {
let image = document.createElement('img'); const image = document.createElement('img')
image.src = footer_images[k].src; image.src = footer_images[k].src
image.width="300"; image.width = '300'
image.height= "73"; image.height = '73'
image.alt = footer_images[k].alt; image.alt = footer_images[k].alt
imagediv.appendChild(image); imagediv.appendChild(image)
} }
containerdiv.appendChild(imagediv); containerdiv.appendChild(imagediv)
footerdiv.appendChild(containerdiv); footerdiv.appendChild(containerdiv)
document.body.appendChild(footerdiv); document.body.appendChild(footerdiv)
}; };
head()
head(); foot()
foot();
\ No newline at end of file
var isEmailValid = false let isEmailValid = false
var isPasswordValid = false let isPasswordValid = false
// check if email already exist // check if email already exist
$('#inputEmail').change(function(){ $('#inputEmail').change(function () {
var email = $('#inputEmail').val() const email = $('#inputEmail').val()
$.get("email/"+email, function(data) { $.get('email/' + email, function (data) {
$('#emailWarning').empty() $('#emailWarning').empty()
isEmailValid = data isEmailValid = data
if(!isEmailValid) { if (!isEmailValid) {
$('#emailWarning').html('Mit dieser E-Mail-Adresse existiert bereits ein Benutzerkonto in unserem Transferportal.') $('#emailWarning').html('Mit dieser E-Mail-Adresse existiert bereits ein Benutzerkonto in unserem Transferportal.')
} }
switchSubmitButton() switchSubmitButton()
}) })
.fail(function() { .fail(function () {
console.log("cannot check email") console.log('cannot check email')
}) })
}); })
// check password // check password
$('#inputPassword').on('keyup', function () { $('#inputPassword').on('keyup', function () {
isPasswordValid = checkPasswordReq($('#inputPassword').val()) isPasswordValid = checkPasswordReq($('#inputPassword').val())
$('#passwordWarning').empty(); $('#passwordWarning').empty()
if (!isPasswordValid) { if (!isPasswordValid) {
//$('#passwordWarning').html('Must be at least 8 characters') // $('#passwordWarning').html('Must be at least 8 characters')
$('#passwordWarning').html('Das Passwort muss mindestens 8 Zeichen haben') $('#passwordWarning').html('Das Passwort muss mindestens 8 Zeichen haben')
} }
switchSubmitButton() switchSubmitButton()
}); })
function switchSubmitButton() { function switchSubmitButton () {
if (isEmailValid && isPasswordValid) { if (isEmailValid && isPasswordValid) {
$('#submitBtn').prop('disabled', false) $('#submitBtn').prop('disabled', false)
} } else {
else { $('#submitBtn').prop('disabled', true)
$('#submitBtn').prop('disabled', true) }
} }
}
\ No newline at end of file
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