Commit af66b069 authored by Wolfgang Knopki's avatar Wolfgang Knopki
Browse files

Revert "Merge branch 'prepare_prod' into 'master'"

This reverts merge request !102
parent f287ea2c
1 merge request!104Revert "Merge branch 'prepare_prod' into 'master'"
Showing with 394 additions and 214 deletions
+394 -214
/built
/routes/cert
/node_modules /node_modules
sp-account-metadata.xml
.idea
deploy-testing: deploy-testing:
stage: deploy stage: deploy
script: script:
- cat $configfiledev > ./config/config.js
- cat $cert > ./routes/cert/cert.pem
- cat $certidp > ./routes/cert/cert_idp.pem
- cat $key > ./routes/cert/key.pem
- npm install - npm install
- npm run clean
- npm run build
- rm -rf ./built/public/default
- rm -rf ./built/routes/cert
- rm -rf ./built/views
- cp -R ./public/default ./built/public
- cp -R ./routes/cert ./built/routes
- cp -R ./views ./built
- cat $configfiledev > ./built/config/config.js
- cat $cert > ./built/routes/cert/cert.pem
- cat $certidp > ./built/routes/cert/cert_idp.pem
- cat $key > ./built/routes/cert/key.pem
- "pm2 delete --silent account || :" - "pm2 delete --silent account || :"
- pm2 start ./built/app.js --name=account - pm2 start ./app.js --name=account
- pm2 save - pm2 save
tags: tags:
- testing - testing
......
import gitlab from '../functions/gitlab' const gitlab = require('../functions/gitlab')
//const axios = require('axios') //const axios = require('axios')
//jest.mock('axios') //jest.mock('axios')
......
import methods from '../functions/methods' const methods = require('../functions/methods')
describe("DB methohds test", () => { describe("DB methohds test", () => {
...@@ -49,4 +49,4 @@ describe("DB methohds test", () => { ...@@ -49,4 +49,4 @@ describe("DB methohds test", () => {
expect(user).toBeNull() expect(user).toBeNull()
}) })
}) })
\ No newline at end of file
import express from 'express'; const express = require('express');
import path from 'path'; const http = require('http');
import passport from 'passport'; const path = require('path');
import morgan from 'morgan'; const passport = require('passport');
import cookieParser from 'cookie-parser'; const morgan = require('morgan');
import bodyParser from 'body-parser'; const cookieParser = require('cookie-parser');
import session from 'express-session'; const bodyParser = require('body-parser');
import flash from 'express-flash-2'; const session = require('express-session');
import fileUpload from 'express-fileupload'; const errorhandler = require('errorhandler');
import helmet from 'helmet'; const flash = require('express-flash-2');
import compression from 'compression'; const fileUpload = require('express-fileupload');
import methodOverride from 'method-override'; const helmet = require('helmet');
import dotenv from 'dotenv' const compression = require('compression');
const methodOverride = require('method-override');
dotenv.config();
var env = process.env.NODE_ENV || 'testing'; var env = process.env.NODE_ENV || 'testing';
const config = require('./config/config')[env]; const config = require('./config/config')[env];
const lang = 'DE'; const lang = 'DE';
var app = express(); var app = express();
app.set('port', config.app.port); app.set('port', config.app.port);
app.set('views', path.join( __dirname + '/views')); app.set('views', __dirname + '/views');
app.set('view engine', 'pug'); app.set('view engine', 'pug');
// enable files upload // enable files upload
...@@ -30,25 +30,12 @@ app.use(fileUpload({ ...@@ -30,25 +30,12 @@ app.use(fileUpload({
fileSize: 1000000 // 1 MB max. file size fileSize: 1000000 // 1 MB max. file size
} }
})); }));
app.use(methodOverride('_method'));
app.use(
helmet.contentSecurityPolicy({
useDefaults: true,
directives: {
"font-src": ["'self'", "https://use.fontawesome.com"],
"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",
"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"],
"frame-src": ["'self'"]
},
reportOnly: true,
})
);
app.use(methodOverride('_method'));
app.use(helmet());
app.use(compression()); app.use(compression());
app.use(morgan('combined')); app.use(morgan('combined'));
app.use(cookieParser(config.app.sessionSecret)); app.use(cookieParser());
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')));
...@@ -56,11 +43,13 @@ app.use((req, res, next) => { ...@@ -56,11 +43,13 @@ app.use((req, res, next) => {
next(); next();
}); });
app.use(session({ app.use(session(
resave: true, {
saveUninitialized: true, resave: true,
secret: config.app.sessionSecret saveUninitialized: true,
})); 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());
...@@ -72,16 +61,16 @@ app.use(function(req, res, next) { ...@@ -72,16 +61,16 @@ app.use(function(req, res, next) {
next(); next();
}); });
require('./routes/public')(app, config, lang);
require('./routes/account')(app, config, passport, lang); require('./routes/account')(app, config, passport, lang);
require('./routes/public')(app, config, lang);
// Handle 404 // Handle 404
app.use(function (req:any, res:any) { app.use(function (req, res) {
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, req, res, next) {
console.error(err.stack) console.error(err.stack)
res.status(500).render(lang+'/500', { res.status(500).render(lang+'/500', {
error: err error: err
......
class Project { class Project {
ownerGitlabId:number constructor(ownerGitlabId, id, name, desc, logo, path) {
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.id = id
this.name = name this.name = name
this.desc = desc this.desc = desc
this.id = id
this.logo = logo this.logo = logo
this.path = path this.path = path
} }
...@@ -35,24 +28,24 @@ class Project { ...@@ -35,24 +28,24 @@ class Project {
return this.path return this.path
} }
// setter // setter
setOwnerGitlabId(newOwnerGitlabId:number){ setOwnerGitlabId(newOwnerGitlabId){
this.ownerGitlabId = newOwnerGitlabId this.ownerGitlabId = newOwnerGitlabId
} }
setId(newId:number) { setId(newId) {
this.id = newId this.id = newId
} }
setName(newName:string) { setName(newName) {
this.name = newName this.name = newName
} }
setDesc(newDesc:string) { setDesc(newDesc) {
this.desc = newDesc this.desc = newDesc
} }
setLogo(newLogoUrl:string) { setLogo(newLogoUrl) {
this.logo = newLogoUrl this.logo = newLogoUrl
} }
setPath(newPath:string) { setPath(newPath) {
this.path = newPath this.path = newPath
} }
} }
export = Project module.exports = Project
\ No newline at end of file \ No newline at end of file
const Project = require("./project");
class Repo extends Project {
constructor(ownerGitlabId, id, name, desc, logo, path) {
super(ownerGitlabId, id, name, desc, logo, path)
}
}
module.exports = Repo
\ No newline at end of file
import Project from "./project"
class Repo extends Project {
constructor(ownerGitlabId:number, name:string, desc:string, id?:number, logo?:string, path?:string) {
super(ownerGitlabId, name, desc, id, logo, path)
}
}
export = Repo
\ No newline at end of file
class User { class User {
id:number constructor(id, email, salutation, title, firstName, lastName, industry, organisation, speciality, is_m4lab_idp, gitlabUserId, verificationStatus) {
email:string this.id = id
salutation:string // should be enum this.email = email
title:string // should be enum this.salutation = salutation
firstName:string this.title = title
lastName:string this.firstName = firstName
industry:string this.lastName = lastName
organisation:string this.industry = industry
speciality:string this.organisation = organisation
is_m4lab_idp:number // 1 or 0 this.speciality = speciality
verificationStatus:number // 1 or 0 - // should be boolean this.is_m4lab_idp = is_m4lab_idp // 1 or 0
gitlabUserId?:number this.gitlabUserId = gitlabUserId
this.verificationStatus = verificationStatus
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) {
this.id = id
this.email = email
this.salutation = salutation
this.title = title
this.firstName = firstName
this.lastName = lastName
this.industry = industry
this.organisation = organisation
this.speciality = speciality
this.is_m4lab_idp = is_m4lab_idp
this.verificationStatus = verificationStatus
this.gitlabUserId = gitlabUserId
} }
// getter // getter
...@@ -41,48 +27,48 @@ class User { ...@@ -41,48 +27,48 @@ class User {
getIdpStatus() { getIdpStatus() {
return this.is_m4lab_idp return this.is_m4lab_idp
} }
getVerificationStatus() {
return this.verificationStatus
}
getGitlabUserId() { getGitlabUserId() {
return this.gitlabUserId return this.gitlabUserId
} }
getVerificationStatus() {
return this.verificationStatus
}
// setter // setter
setEmail(email:string) { setEmail(email) {
this.email = email this.email = email
} }
setSalutation(salutation:string) { setSalutation(salutation) {
this.salutation = salutation this.salutation = salutation
} }
setTitle(title:string) { setTitle(title) {
this.title = title this.title = title
} }
setFirstName(firstName:string) { setFirstName(firstName) {
this.firstName = firstName this.firstName = firstName
} }
setLastName(lastName:string) { setLastName(lastName) {
this.lastName = lastName this.lastName = lastName
} }
setIndustry(industry:string) { setIndustry(industry) {
this.industry = industry this.industry = industry
} }
setOrganisation(organisation:string) { setOrganisation(organisation) {
this.organisation = organisation this.organisation = organisation
} }
setSpeciality(speciality:string) { setSpeciality(speciality) {
this.speciality = speciality this.speciality = speciality
} }
setM4lab_idp(m4lab_idp:number) { setM4lab_idp(m4lab_idp) {
this.is_m4lab_idp = m4lab_idp this.m4lab_idp = m4lab_idp
}
setVerificationStatus(verificationStatus:number) {
this.verificationStatus = verificationStatus
} }
setGitlabUserId(newGitlabUserId:number) { setGitlabUserId(newGitlabUserId) {
this.gitlabUserId = newGitlabUserId this.gitlabUserId = newGitlabUserId
} }
setVerificationStatus(verificationStatus) {
this.verificationStatus = verificationStatus
}
updateProfile(newSalutation:string, newTitle:string, newFirstname:string, newLastname:string, newEmail:string, newOrganisation:string, newIndustry:string, newSpeciality:string) { updateProfile(newSalutation, newTitle, newFirstname, newLastname, newEmail, newOrganisation, newIndustry, newSpeciality) {
this.salutation = newSalutation this.salutation = newSalutation
this.title = newTitle this.title = newTitle
this.firstName = newFirstname this.firstName = newFirstname
...@@ -94,4 +80,4 @@ class User { ...@@ -94,4 +80,4 @@ class User {
} }
} }
export = User module.exports = User
\ No newline at end of file \ No newline at end of file
const Project = require("./project");
class Website extends Project {
constructor(ownerGitlabId, id, name, desc, logo, path) {
super(ownerGitlabId, id, name, desc, logo, path)
}
}
module.exports = Website
\ No newline at end of file
import Project from "./project"
class Website extends Project {
constructor(ownerGitlabId:number, name:string, desc:string, id?:number, logo?:string, path?:string) {
super(ownerGitlabId, name, desc, id, logo, path)
}
}
export = Website
\ No newline at end of file
export = { module.exports = {
development: { development: {
app: { app: {
name: 'User Account Management', name: 'User Account Management',
...@@ -28,7 +28,7 @@ export = { ...@@ -28,7 +28,7 @@ export = {
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, // sets requireTLS
authUser: 'mailuser', authUser: 'mailuser',
authPass: 'mailpass', authPass: 'mailpass',
tlsCiphers: 'SSLv3', tlsCiphers: 'SSLv3',
...@@ -67,7 +67,7 @@ export = { ...@@ -67,7 +67,7 @@ export = {
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, // sets requireTLS
authUser: 'mailuser', authUser: 'mailuser',
authPass: 'mailpass', authPass: 'mailpass',
tlsCiphers: 'SSLv3', tlsCiphers: 'SSLv3',
...@@ -77,4 +77,4 @@ export = { ...@@ -77,4 +77,4 @@ export = {
token_readWriteProjects: 'token-goes-here' token_readWriteProjects: 'token-goes-here'
} }
} }
} }
\ No newline at end of file
export = { module.exports = {
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/>' +
......
import mysql from 'mysql' const mysql = require('mysql')
var env = process.env.NODE_ENV || 'testing' var env = process.env.NODE_ENV || 'testing';
const config = require('./config')[env] const config = require('./config')[env]
// ==== USER ACOOUNT DB CONNECTION ==== // ==== USER ACOOUNT DB CONNECTION ====
...@@ -14,7 +14,7 @@ var userConnection = mysql.createConnection({ ...@@ -14,7 +14,7 @@ var userConnection = mysql.createConnection({
}) })
userConnection.connect(function(err) { userConnection.connect(function(err) {
if (err) throw err if (err) throw err;
}) })
userConnection.query('USE '+config.database.dbUser) userConnection.query('USE '+config.database.dbUser)
...@@ -52,7 +52,7 @@ var projectConnection = mysql.createConnection({ ...@@ -52,7 +52,7 @@ var projectConnection = mysql.createConnection({
}) })
projectConnection.connect(function(err) { projectConnection.connect(function(err) {
if (err) throw err if (err) throw err;
}) })
projectConnection.query('USE '+config.database.dbProject) projectConnection.query('USE '+config.database.dbProject)
...@@ -61,4 +61,4 @@ var connection = { ...@@ -61,4 +61,4 @@ var connection = {
project: projectConnection project: projectConnection
} }
export = connection module.exports = connection
\ No newline at end of file \ No newline at end of file
import mysql from 'mysql2' const mysql = require('mysql2')
var env = process.env.NODE_ENV || 'testing' var env = process.env.NODE_ENV || 'testing';
const config = require('./config')[env] const config = require('./config')[env]
// ==== USER ACOOUNT DB CONNECTION ==== // ==== USER ACOOUNT DB CONNECTION ====
...@@ -14,7 +14,7 @@ var userConnection = mysql.createConnection({ ...@@ -14,7 +14,7 @@ var userConnection = mysql.createConnection({
}) })
userConnection.connect(function(err) { userConnection.connect(function(err) {
if (err) throw err if (err) throw err;
}) })
userConnection.query('USE '+config.database.dbUser) userConnection.query('USE '+config.database.dbUser)
...@@ -52,7 +52,7 @@ var projectConnection = mysql.createConnection({ ...@@ -52,7 +52,7 @@ var projectConnection = mysql.createConnection({
}) })
projectConnection.connect(function(err) { projectConnection.connect(function(err) {
if (err) throw err if (err) throw err;
}) })
projectConnection.query('USE '+config.database.dbProject) projectConnection.query('USE '+config.database.dbProject)
...@@ -61,4 +61,4 @@ var connection = { ...@@ -61,4 +61,4 @@ var connection = {
project: projectConnection project: projectConnection
} }
export = connection module.exports = connection
\ No newline at end of file \ No newline at end of file
const nodemailer = require('nodemailer');
const nodemailerNTLMAuth = require('nodemailer-ntlm-auth');
var env = process.env.NODE_ENV || 'testing';
const config = require('./config')[env]
var smtpTransport = nodemailer.createTransport({
host: config.mailer.host,
secure: config.mailer.secureConnection,
port: config.mailer.port,
requireTLS: config.mailer.TLS,
auth: {
type: 'custom',
method: 'NTLM',
user: config.mailer.authUser,
pass: config.mailer.authPass,
options: {
domain: 'ad'
}
},
customAuth:{
NTLM: nodemailerNTLMAuth
}
});
var mailOptions = {
to: "",
from: config.mailer.from,
subject: "",
text: ""
};
var mailer = {
transport: smtpTransport,
options: mailOptions
}
module.exports = mailer
const nodemailer = require('nodemailer')
const nodemailerNTLMAuth = require('nodemailer-ntlm-auth')
var env = process.env.NODE_ENV || 'testing'
const config = require('./config')[env]
var smtpTransporter = nodemailer.createTransport({
host: config.mailer.host,
secure: config.mailer.secureConnection,
port: config.mailer.port,
requireTLS: config.mailer.TLS,
auth: {
type: 'custom',
method: 'NTLM',
user: config.mailer.authUser,
pass: config.mailer.authPass,
options: {
domain: 'ad'
}
},
customAuth:{
NTLM: nodemailerNTLMAuth
}
});
var mailOptions:any = {
to: "",
cc: "",
from: config.mailer.from,
subject: "",
text: "",
html: ""
}
var mailer:any = {
transporter: smtpTransporter,
options: mailOptions
}
export = mailer
\ No newline at end of file
import axios from 'axios'
import fs from 'fs'
import formData from 'form-data'
var env = process.env.NODE_ENV || 'testing' var env = process.env.NODE_ENV || 'testing'
const config = require('../config/config')[env] const config = require('../config/config')[env]
const axios = require('axios')
const fs = require('fs')
var formData = require('form-data')
var gitlab = { var gitlab = {
getUserByEmail: async function(email:string) { // todo: GraphQL currentUser
getUserByEmail: async function(email) {
return axios({ return 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,
...@@ -14,12 +15,9 @@ var gitlab = { ...@@ -14,12 +15,9 @@ var gitlab = {
'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(err => console.error(err))
console.error(err)
return null
})
}, },
createNewPages: async function(newPagesData:any, newLogoFile:string, template:any) { createNewPages: async function(newPagesData, newLogoFile, template) {
let data = new formData() let data = new formData()
data.append('avatar', fs.createReadStream(newLogoFile)) data.append('avatar', fs.createReadStream(newLogoFile))
...@@ -34,15 +32,16 @@ var gitlab = { ...@@ -34,15 +32,16 @@ var gitlab = {
}, },
data: data data: data
}) })
.then(res => res.data) .then(res => res = {
.catch(function(err) { error: false,
console.error("ERR Status: "+err.response.status) data: res.data
console.error("ERR Name: "+err.response.data.message.name) })
console.error("ERR Path: "+err.response.data.message.path) .catch(err => res = {
return err.response error: true,
data: err.response.data
}) })
}, },
updateProject: async function(updatedProjectData:any, newLogoFile:string){ updateProject: async function(updatedProjectData, newLogoFile){
let data = new formData() let data = new formData()
if (newLogoFile) { if (newLogoFile) {
data.append('avatar', fs.createReadStream(newLogoFile)) data.append('avatar', fs.createReadStream(newLogoFile))
...@@ -58,16 +57,16 @@ var gitlab = { ...@@ -58,16 +57,16 @@ var gitlab = {
}, },
data : data data : data
}) })
//.then(res => res.data[0]) .then(res => res = {
.then(res => res.data) error: false,
.catch(function(err){ data: res.data
console.error("ERR Status: "+err.response.status) })
console.error("ERR Name: "+err.response.data.message.name) .catch(err => res = {
console.error("ERR Path: "+err.response.data.message.path) error: true,
return err.response data: err.response.data
}) })
}, },
deleteProjectById: function(projectId:number){ deleteProjectById: function(projectId){
// https://docs.gitlab.com/ee/api/projects.html#delete-project // https://docs.gitlab.com/ee/api/projects.html#delete-project
return axios({ return axios({
method: 'delete', method: 'delete',
...@@ -76,15 +75,16 @@ var gitlab = { ...@@ -76,15 +75,16 @@ var gitlab = {
'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects 'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects
} }
}) })
.then(res => true) .then(res => res = {
.catch(function(err) { error: false,
console.error("ERR Status: "+err.response.status) data: res.data
console.error("ERR Name: "+err.response.data.message.name) })
console.error("ERR Path: "+err.response.data.message.path) .catch(err => res = {
return false error: true,
data: err.response.data
}) })
}, },
getUserProjects: async function(gitlabUserId:number) { getUserProjects: async function(gitlabUserId) {
return axios({ return axios({
method: 'get', method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/users/'+gitlabUserId+'/projects?owned=true&visibility=public', url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/users/'+gitlabUserId+'/projects?owned=true&visibility=public',
...@@ -93,12 +93,9 @@ var gitlab = { ...@@ -93,12 +93,9 @@ var gitlab = {
} }
}) })
.then(res => res.data) .then(res => res.data)
.catch(function(err) { .catch(err => console.error(err))
console.error(err)
return null
})
}, },
getProjectById: async function(projectId:number) { getProjectById: async function(projectId) {
return axios({ return axios({
method: 'get', method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/'+projectId, url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/'+projectId,
...@@ -107,22 +104,45 @@ var gitlab = { ...@@ -107,22 +104,45 @@ var gitlab = {
} }
}) })
.then(res => res.data) .then(res => res.data)
.catch(function(err) { .catch(err => console.error(err.response.status))
console.error(err)
return null
})
}, },
getProjectPipelineLatestStatus: async function(projectId:number) { getProjectPipelineLatestStatus: async function(projectId) {
return axios({ return axios({
method: 'get', method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/'+projectId+'/pipelines' url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/'+projectId+'/pipelines'
}) })
.then(res => res.data[0].status) .then(res => res.data[0].status)
.catch(function(err) { .catch(err => console.error(err))
console.error(err) },
return null //
}) // test GraphQL
getGraphqlTest: function(callback) {
axios({
url: 'https://gitlab.com/api/graphql',
method: 'get',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects
},
data: {
query: `{
currentUser {
id
username
}
}`
/* query: `{
projects {
nodes {
id
}
}
}` */
}
}).then((result) => {
console.log(JSON.stringify(result.data))
});
} }
} }
export = gitlab module.exports = gitlab
\ No newline at end of file \ No newline at end of file
var helpers = { var helpers = {
stringToArray: function (input:string){ stringToArray: function (input){
if(input != null){ if(input != null){
return input.split(','); return input.split(',');
}else{ }else{
...@@ -8,4 +8,4 @@ var helpers = { ...@@ -8,4 +8,4 @@ var helpers = {
} }
}; };
export = helpers; module.exports = helpers;
\ No newline at end of file \ No newline at end of file
import dbconn_OBSOLETE = require('../config/dbconn') // DO NOT USE THIS FOR NEW FUNCTIONS const dbconn_OBSOLETE = require('../config/dbconn') // DO NOT USE THIS FOR NEW FUNCTIONS
import dbconn = require('../config/dbconn2') const dbconn = require('../config/dbconn2')
var methods = { var methods = {
// ===================== user db ===================== // ===================== user db =====================
registerNewUser: function(data:any, callback:any) { registerNewUser: function(data, callback) {
dbconn_OBSOLETE.user.beginTransaction(function(err:any) { // START TRANSACTION dbconn_OBSOLETE.user.beginTransaction(function(err) { // START TRANSACTION
if (err) { throw err } if (err) {
throw err
}
// insert profile // insert profile
dbconn_OBSOLETE.user.query('INSERT INTO user SET ?', data.profile, function (err:any, results:any, fields:any) { dbconn_OBSOLETE.user.query('INSERT INTO user SET ?', data.profile, function (err, results, fields) {
if (err) { if (err) {
return dbconn_OBSOLETE.user.rollback(function() { return dbconn_OBSOLETE.user.rollback(function() {
throw err throw err
}); });
} }
let newUserId:number = results.insertId var newUserId = results.insertId
// set password // set password
var credentialData:any = { var credentialData = {
user_id: newUserId, user_id: newUserId,
password: data.password password: data.password
} }
dbconn_OBSOLETE.user.query('INSERT INTO credential SET ?', credentialData, function (err:any, results:any, fields:any) { dbconn_OBSOLETE.user.query('INSERT INTO credential SET ?', credentialData, function (err, results, fields) {
if (err) { if (err) {
return dbconn_OBSOLETE.user.rollback(function() { return dbconn_OBSOLETE.user.rollback(function() {
throw err throw err
}); });
} }
// set default user-project-role // set default user-project-role
var projectRoleData:any = { var projectRoleData = {
project_id: 1, //M4_LAB project_id: 1, //M4_LAB
role_id: 2, // USER role_id: 2, // USER
user_id: newUserId user_id: newUserId
} }
dbconn_OBSOLETE.user.query('INSERT INTO user_project_role SET ?', projectRoleData, function (err:any, results:any, fields:any) { dbconn_OBSOLETE.user.query('INSERT INTO user_project_role SET ?', projectRoleData, function (err, results, fields) {
if (err) { if (err) {
return dbconn_OBSOLETE.user.rollback(function() { return dbconn_OBSOLETE.user.rollback(function() {
throw err throw err
}); });
} }
// MLAB-129: INSERT verification token // MLAB-129: INSERT verification token
let verificationData:any = { let verificationData = {
user_id: newUserId, user_id: newUserId,
token: data.verificationToken token: data.verificationToken
} }
dbconn_OBSOLETE.user.query('INSERT INTO verification SET ?', verificationData, function (err:any, results:any, fields:any) { dbconn_OBSOLETE.user.query('INSERT INTO verification SET ?', verificationData, function (err, results, fields) {
if (err) { if (err) {
return dbconn_OBSOLETE.user.rollback(function() { return dbconn_OBSOLETE.user.rollback(function() {
throw err throw err
}); });
} }
// COMMIT // COMMIT
dbconn_OBSOLETE.user.commit(function(err:any) { dbconn_OBSOLETE.user.commit(function(err) {
if (err) { if (err) {
return dbconn_OBSOLETE.user.rollback(function() { return dbconn_OBSOLETE.user.rollback(function() {
throw err throw err
...@@ -63,9 +65,9 @@ var methods = { ...@@ -63,9 +65,9 @@ var methods = {
callback(err) callback(err)
}) })
}, },
getUserByEmail: async function(email:any) { getUserByEmail: async function(email) {
try { 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+'"') let rows = 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]) { if (rows[0][0]) {
return rows[0][0] return rows[0][0]
} }
...@@ -75,9 +77,9 @@ var methods = { ...@@ -75,9 +77,9 @@ var methods = {
} }
return null return null
}, },
getUserEmailById: async function(userId:number) { getUserEmailById: async function(userId) {
try { try {
let rows:any = await dbconn.user.promise().query('SELECT email FROM user WHERE id = ' +userId) let rows = await dbconn.user.promise().query('SELECT email FROM user WHERE id = ' +userId)
if (rows[0][0]) { if (rows[0][0]) {
return rows[0][0].email return rows[0][0].email
} }
...@@ -87,9 +89,9 @@ var methods = { ...@@ -87,9 +89,9 @@ var methods = {
} }
return null return null
}, },
checkUserEmail: async function(email:any) { checkUserEmail: async function(email) {
try { try {
let rows:any = await dbconn.user.promise().query('SELECT id, email FROM user WHERE email = "' +email+'"') let rows = await dbconn.user.promise().query('SELECT id, email FROM user WHERE email = "' +email+'"')
if (rows[0][0]) { if (rows[0][0]) {
return rows[0][0] return rows[0][0]
} }
...@@ -99,9 +101,9 @@ var methods = { ...@@ -99,9 +101,9 @@ var methods = {
} }
return null return null
}, },
getUserByToken: async function(token:any) { getUserByToken: async function(token) {
try { 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 = "' let rows = 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()) +token+'" and resetPasswordExpires > '+Date.now())
if (rows[0][0]) { if (rows[0][0]) {
return rows[0][0] return rows[0][0]
...@@ -112,38 +114,47 @@ var methods = { ...@@ -112,38 +114,47 @@ var methods = {
} }
return null return null
}, },
updateUserById: async function(userId:number, userData:any) { updateUserById: function(userData, callback) {
try { dbconn_OBSOLETE.user.query('UPDATE user SET ? WHERE id = ' +userData.id, userData, function (err, rows, fields) {
let result:any = await dbconn.user.promise().query('UPDATE user SET ? WHERE id = ' +userId, userData) if (err) throw err
return result callback(err)
} 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) { updateCredential: function(data, callback) {
/* dbconn_OBSOLETE.user.query('UPDATE credential SET ? WHERE user_id = ' +data.user_id, data, function (err, rows, fields) {
dbconn_OBSOLETE.user.query('INSERT INTO user_project_role SET ?', data, function (err:any, results:any, fields:any){
if (err) throw err if (err) throw err
callback(err) callback(err)
}) */ })
dbconn.user.query('INSERT INTO user_project_role SET ?', data, function (err:any){ },
getUserIdByEmail_OBSOLETE: function(email, callback) {
let userId
dbconn_OBSOLETE.user.query('SELECT id FROM user WHERE email = "' +email+'"', function (err, rows, fields) {
if (err) {
throw err
}
else {
if ( rows.length > 0) {
userId = rows[0].id
}
}
callback(userId, err)
});
},
getUserProjectRole_OBSOLETE: function(userId, callback) {
dbconn_OBSOLETE.user.query('SELECT project_id, role_id FROM user_project_role WHERE user_id = "' +userId+'"', function (err, rows, fields) {
if (err) throw err
callback(rows, err)
});
},
addUserProjectRole: function(data, callback) {
dbconn_OBSOLETE.user.query('INSERT INTO user_project_role SET ?', data, function (err, results, fields){
if (err) throw err if (err) throw err
callback(err) callback(err)
}) })
}, },
getVerificationTokenByUserId: async function(userId:number) { getVerificationTokenByUserId: async function(userId) {
try { try {
let rows:any = await dbconn.user.promise().query('SELECT token FROM verification WHERE user_id = "' +userId+'"') let rows = await dbconn.user.promise().query('SELECT token FROM verification WHERE user_id = "' +userId+'"')
if (rows[0][0]) { if (rows[0][0]) {
return rows[0][0].token return rows[0][0].token
} }
...@@ -153,9 +164,9 @@ var methods = { ...@@ -153,9 +164,9 @@ var methods = {
} }
return null return null
}, },
getUserIdByVerificationToken: async function(token:any) { getUserIdByVerificationToken: async function(token) {
try { try {
let rows:any = await dbconn.user.promise().query('SELECT user_id FROM verification WHERE token = "' +token+'"') let rows = await dbconn.user.promise().query('SELECT user_id FROM verification WHERE token = "' +token+'"')
if (rows[0][0]) { if (rows[0][0]) {
return rows[0][0].user_id return rows[0][0].user_id
} }
...@@ -167,21 +178,21 @@ var methods = { ...@@ -167,21 +178,21 @@ var methods = {
} }
return null return null
}, },
verifyUserAccount: function(userData:any, callback:any) { verifyUserAccount: function(userData, callback) {
dbconn_OBSOLETE.user.beginTransaction(function(err:any) { // START TRANSACTION dbconn_OBSOLETE.user.beginTransaction(function(err) { // START TRANSACTION
if (err) { throw err } if (err) { throw err }
// update user status // update user status
dbconn_OBSOLETE.user.query('UPDATE user SET ? WHERE id =' +userData.id, userData, function (err:any, rows:any, fields:any) { dbconn_OBSOLETE.user.query('UPDATE user SET ? WHERE id =' +userData.id, userData, function (err, rows, fields) {
if (err) { if (err) {
return dbconn_OBSOLETE.user.rollback(function() { throw err }) return dbconn_OBSOLETE.user.rollback(function() { throw err })
} }
// delete verification token // delete verification token
dbconn_OBSOLETE.user.query('DELETE FROM verification WHERE user_id = '+userData.id, function (err:any, rows:any, fields:any) { dbconn_OBSOLETE.user.query('DELETE FROM verification WHERE user_id = '+userData.id, function (err, rows, fields) {
if (err) { if (err) {
return dbconn_OBSOLETE.user.rollback(function() { throw err }) return dbconn_OBSOLETE.user.rollback(function() { throw err })
} }
// COMMIT // COMMIT
dbconn_OBSOLETE.user.commit(function(err:any) { dbconn_OBSOLETE.user.commit(function(err) {
if (err) { if (err) {
return dbconn_OBSOLETE.user.rollback(function() { throw err }) return dbconn_OBSOLETE.user.rollback(function() { throw err })
} }
...@@ -192,9 +203,9 @@ var methods = { ...@@ -192,9 +203,9 @@ var methods = {
}) })
}, },
/* ===== GitLab ===== */ /* ===== GitLab ===== */
getGitlabId: async function(userId:number) { getGitlabId: async function(userId) {
try { 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') let rows = 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]) { if (rows[0][0]) {
return rows[0][0].gitlab_userId return rows[0][0].gitlab_userId
} else { } else {
...@@ -206,12 +217,12 @@ var methods = { ...@@ -206,12 +217,12 @@ var methods = {
return err return err
} }
}, },
addGitlabUser: function(data:any, callback:any){ addGitlabUser: function(data, callback){
dbconn.user.query('INSERT INTO user_gitlab SET ?', data, function (err:any) { dbconn_OBSOLETE.user.query('INSERT INTO user_gitlab SET ?', data, function (err) {
if (err) throw err if (err) throw err
callback(err) callback(err)
}) })
} }
}; };
export = methods module.exports = methods;
\ No newline at end of file \ 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