Commit 58fc4884 authored by Wolfgang Knopki's avatar Wolfgang Knopki
Browse files

Merge branch 'prepare_prod' into 'master'

Prepare prod

See merge request !91
1 merge request!91Prepare prod
Pipeline #4342 passed with stage
in 15 seconds
Showing with 14250 additions and 1533 deletions
+14250 -1533
User Account Management User Account Management
Re-implementation of https://transfer.hft-stuttgart.de/gitlab/sihombing/portal/tree/master/app-useracc using NodeJS and ExpressJS This is the repository of the User Account of the TransferPortal.
\ No newline at end of file \ No newline at end of file
const gitlab = require('../functions/gitlab')
//const axios = require('axios')
//jest.mock('axios')
describe('GitLab API', () => {
test('returns an existing gitlab user by an email address', async () => {
let user = await gitlab.getUserByEmail('litehon958@whipjoy.com')
expect(user).not.toBeNull()
})
test('returns an undefined user', async () => {
let user = await gitlab.getUserByEmail('johndoe@nowhere.com')
expect(user).toBeUndefined()
})
test('returns users project', async () => {
let userProjects = await gitlab.getUserProjects(136)
expect(userProjects).toBeDefined()
})
test('returns undefined projects, due to non-existing gitlab user ID', async () => {
let userProjects = await gitlab.getUserProjects(0)
expect(userProjects).toBeUndefined()
})
test('returns a project by ID', async () => {
let project = await gitlab.getProjectById(13) // m4lab_landing_page
expect(project).toBeDefined()
})
test('returns undefined, due to invalid project ID', async () => {
let project = await gitlab.getProjectById(0)
expect(project).toBeUndefined()
})
})
\ No newline at end of file
const methods = require('../functions/methods')
describe("DB methohds test", () => {
it("returns a user from DB by email", async() => {
const user = await methods.getUserByEmail('litehon958@whipjoy.com')
expect(user).not.toBeNull()
})
it("returns a null user", async() => {
const user = await methods.getUserByEmail('jondoe@nowhere.com') // a non-exist user
expect(user).toBeNull()
})
it("returns a user's email", async() => {
const email = await methods.getUserEmailById(1)
expect(email).not.toBeNull()
})
it("returns null instead of a user's email", async() => {
const email = await methods.getUserEmailById(1005) // no user has this ID
expect(email).toBeNull()
})
it("returns null from DB by token", async() => {
const user = await methods.getUserByToken('12345678') // unvalid token
expect(user).toBeNull() // for valid token = expect(user).not.toBeNull()
})
it("returns a user's verification token, if any", async() => {
const token = await methods.getVerificationTokenByUserId(1)
expect(token).toBeNull()
})
it("returns a user's ID, if any", async() => {
const token = await methods.getUserIdByVerificationToken('12345678') // unvalid token
expect(token).toBeNull() // for valid token = expect(user).not.toBeNull()
})
it("returns a user's GitLab_ID, if any", async() => {
const id = await methods.getGitlabId(1)
expect(id).not.toBeNull()
})
it("checks user email", async() => {
const user = await methods.checkUserEmail('litehon958@whipjoy.com')
expect(user).not.toBeNull()
})
it("checks user email and return null", async() => {
const user = await methods.checkUserEmail('jondoe@nowhere.com') // a non-exist user
expect(user).toBeNull()
})
})
...@@ -7,19 +7,15 @@ const cookieParser = require('cookie-parser'); ...@@ -7,19 +7,15 @@ const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser'); const bodyParser = require('body-parser');
const session = require('express-session'); const session = require('express-session');
const errorhandler = require('errorhandler'); const errorhandler = require('errorhandler');
const flash = require('express-flash'); const flash = require('express-flash-2');
const fileUpload = require('express-fileupload'); const fileUpload = require('express-fileupload');
const helmet = require('helmet'); const helmet = require('helmet');
const compression = require('compression'); const compression = require('compression');
const methodOverride = require('method-override');
const i18n = require('i18n'); // internationalization
i18n.configure({
locales:['de', 'en'],
directory: './locales'
});
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';
var app = express(); var app = express();
...@@ -35,6 +31,7 @@ app.use(fileUpload({ ...@@ -35,6 +31,7 @@ app.use(fileUpload({
} }
})); }));
app.use(methodOverride('_method'));
app.use(helmet()); app.use(helmet());
app.use(compression()); app.use(compression());
app.use(morgan('combined')); app.use(morgan('combined'));
...@@ -42,9 +39,7 @@ app.use(cookieParser()); ...@@ -42,9 +39,7 @@ 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')));
app.use(i18n.init);
app.use((req, res, next) => { app.use((req, res, next) => {
res.setLocale('de');
next(); next();
}); });
...@@ -52,16 +47,10 @@ app.use(session( ...@@ -52,16 +47,10 @@ app.use(session(
{ {
resave: true, resave: true,
saveUninitialized: true, saveUninitialized: true,
secret: 'thisisasecret' secret: config.app.sessionSecret
} }
)); ));
app.use(flash()); app.use(flash());
app.use((req, res, next) => {
res.locals.errors = req.flash("error");
res.locals.successes = req.flash("success");
next();
});
app.use(passport.initialize()); app.use(passport.initialize());
app.use(passport.session()); app.use(passport.session());
...@@ -72,19 +61,18 @@ app.use(function(req, res, next) { ...@@ -72,19 +61,18 @@ app.use(function(req, res, next) {
next(); next();
}); });
require('./routes/routes-account')(app, config, passport, i18n); require('./routes/account')(app, config, passport, lang);
require('./routes/api')(app, config, passport); require('./routes/public')(app, config, lang);
// Handle 404 // Handle 404
app.use(function (req, res, next) { app.use(function (req, res) {
//res.status(404).send('404: Page not Found', 404) res.status(404).render(lang+'/404')
res.status(404).render('./DE/404')
}) })
// Handle 500 - any server error // Handle 500 - any server error
app.use(function (err, req, res, next) { app.use(function (err, req, res, next) {
console.error(err.stack) console.error(err.stack)
res.status(500).render('./DE/500', { res.status(500).render(lang+'/500', {
error: err error: err
}) })
}) })
......
class Project {
constructor(ownerGitlabId, id, name, desc, logo, path) {
this.ownerGitlabId = ownerGitlabId
this.id = id
this.name = name
this.desc = desc
this.logo = logo
this.path = path
}
// getter
getOwnerGitlabId() {
return this.ownerGitlabId
}
getId() {
return this.id
}
getName() {
return this.name
}
getDesc() {
return this.desc
}
getLogo() {
return this.logo
}
getPath() {
return this.path
}
// setter
setOwnerGitlabId(newOwnerGitlabId){
this.ownerGitlabId = newOwnerGitlabId
}
setId(newId) {
this.id = newId
}
setName(newName) {
this.name = newName
}
setDesc(newDesc) {
this.desc = newDesc
}
setLogo(newLogoUrl) {
this.logo = newLogoUrl
}
setPath(newPath) {
this.path = newPath
}
}
module.exports = Project
\ 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
class User {
constructor(id, email, salutation, title, firstName, lastName, industry, organisation, speciality, is_m4lab_idp, gitlabUserId, verificationStatus) {
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 // 1 or 0
this.gitlabUserId = gitlabUserId
this.verificationStatus = verificationStatus
}
// getter
getId() {
return this.id
}
getEmail() {
return this.email
}
getFullName() {
return this.firstName+' '+this.lastName
}
getIdpStatus() {
return this.is_m4lab_idp
}
getGitlabUserId() {
return this.gitlabUserId
}
getVerificationStatus() {
return this.verificationStatus
}
// setter
setEmail(email) {
this.email = email
}
setSalutation(salutation) {
this.salutation = salutation
}
setTitle(title) {
this.title = title
}
setFirstName(firstName) {
this.firstName = firstName
}
setLastName(lastName) {
this.lastName = lastName
}
setIndustry(industry) {
this.industry = industry
}
setOrganisation(organisation) {
this.organisation = organisation
}
setSpeciality(speciality) {
this.speciality = speciality
}
setM4lab_idp(m4lab_idp) {
this.m4lab_idp = m4lab_idp
}
setGitlabUserId(newGitlabUserId) {
this.gitlabUserId = newGitlabUserId
}
setVerificationStatus(verificationStatus) {
this.verificationStatus = verificationStatus
}
updateProfile(newSalutation, newTitle, newFirstname, newLastname, newEmail, newOrganisation, newIndustry, newSpeciality) {
this.salutation = newSalutation
this.title = newTitle
this.firstName = newFirstname
this.lastName = newLastname
this.email = newEmail
this.organisation = newOrganisation
this.industry = newIndustry
this.speciality = newSpeciality
}
}
module.exports = User
\ 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
...@@ -3,7 +3,8 @@ module.exports = { ...@@ -3,7 +3,8 @@ module.exports = {
app: { app: {
name: 'User Account Management', name: 'User Account Management',
port: process.env.PORT || 9989, port: process.env.PORT || 9989,
host: 'http://localhost:9989' host: 'http://localhost:9989',
sessionSecret: 'thisisasecret'
}, },
passport: { passport: {
strategy: 'saml', strategy: 'saml',
...@@ -31,13 +32,17 @@ module.exports = { ...@@ -31,13 +32,17 @@ module.exports = {
authPass: 'mailpass', authPass: 'mailpass',
tlsCiphers: 'SSLv3', tlsCiphers: 'SSLv3',
from: 'mailfrom', from: 'mailfrom',
},
gitlab: {
token_readWriteProjects: 'token-goes-here'
} }
}, },
testing: { testing: {
app: { app: {
name: 'User Account Management', name: 'User Account Management',
port: process.env.PORT || 9989, port: process.env.PORT || 9989,
host: 'https://m4lab.hft-stuttgart.de/account' host: 'https://m4lab.hft-stuttgart.de/account',
sessionSecret: 'thisisasecret'
}, },
passport: { passport: {
strategy: 'saml', strategy: 'saml',
...@@ -65,6 +70,9 @@ module.exports = { ...@@ -65,6 +70,9 @@ module.exports = {
authPass: 'mailpass', authPass: 'mailpass',
tlsCiphers: 'SSLv3', tlsCiphers: 'SSLv3',
from: 'mailfrom', from: 'mailfrom',
},
gitlab: {
token_readWriteProjects: 'token-goes-here'
} }
} }
} }
\ No newline at end of file
module.exports = {
mailSignature: 'Mit den besten Grüßen,<br/>das Transferportal-Team der HFT Stuttgart<br/><br/>' +
'Transferportal der Hochschule für Technik Stuttgart<br/>' +
'Schellingstr. 24 70174 Stuttgart<br/>' +
'm4lab@hft-stuttgart.de<br/>' +
'<a href="https://transfer.hft-stuttgart.de">https://transfer.hft-stuttgart.de</a><br/>' +
'<a href="http://www.hft-stuttgart.de/Aktuell/"><img border="0" alt="HFT" src="https://m4lab.hft-stuttgart.de/img/signature/hft_logo.png" width="30" height="30"></a> &nbsp;' +
'<a href="http://www.facebook.com/hftstuttgart"><img border="0" alt="Facebook" src="https://m4lab.hft-stuttgart.de/img/signature/fb_bw.png" width="30" height="30"></a> &nbsp;' +
'<a href="https://www.instagram.com/hft_stuttgart/"><img border="0" alt="Instagram" src="https://m4lab.hft-stuttgart.de/img/signature/instagram_bw.png" width="30" height="30"></a> &nbsp;' +
'<a href="https://twitter.com/hft_presse"><img border="0" alt="Twitter" src="https://m4lab.hft-stuttgart.de/img/signature/twitter_bw.png" width="30" height="30"></a> &nbsp;' +
'<a href="https://www.youtube.com/channel/UCi0_JfF2qMZbOhOnNH5PyHA"><img border="0" alt="Youtube" src="https://m4lab.hft-stuttgart.de/img/signature/youtube_bw.png" width="30" height="30"></a> &nbsp;' +
'<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>' +
'<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.",
updatePasswordMailContent: '<div>Lieber Nutzer,<br/><br/>Ihr Passwort wurde erfolgreich geändert.<br/><br/></div>'
}
\ No newline at end of file
const mysql = require('mysql') const mysql = require('mysql')
var env = process.env.NODE_ENV || 'testing'; var env = process.env.NODE_ENV || 'testing';
const config = require('../config/config')[env] const config = require('./config')[env]
// ==== USER ACOOUNT DB CONNECTION ==== // ==== USER ACOOUNT DB CONNECTION ====
var userConnection = mysql.createConnection({ var userConnection = mysql.createConnection({
...@@ -18,13 +18,6 @@ userConnection.connect(function(err) { ...@@ -18,13 +18,6 @@ userConnection.connect(function(err) {
}) })
userConnection.query('USE '+config.database.dbUser) userConnection.query('USE '+config.database.dbUser)
// user db connection test
userConnection.query('SELECT 1 + 5 AS solution', function (err, rows, fields) {
if (err) throw err
console.log('Solution = ', rows[0].solution)
})
//userConnection.end()
// ALTERNATIVE approach: close db connection manually after every query // ALTERNATIVE approach: close db connection manually after every query
/* /*
var dbconn = function dbconn(query, values, next) { var dbconn = function dbconn(query, values, next) {
...@@ -63,13 +56,6 @@ projectConnection.connect(function(err) { ...@@ -63,13 +56,6 @@ projectConnection.connect(function(err) {
}) })
projectConnection.query('USE '+config.database.dbProject) projectConnection.query('USE '+config.database.dbProject)
// projectdb connection test
projectConnection.query('SELECT 10 + 5 AS project', function (err, rows, fields) {
if (err) throw err
console.log('Project = ', rows[0].project)
})
//projectConnection.end()
var connection = { var connection = {
user: userConnection, user: userConnection,
project: projectConnection project: projectConnection
......
const mysql = require('mysql2')
var env = process.env.NODE_ENV || 'testing';
const config = require('./config')[env]
// ==== USER ACOOUNT DB CONNECTION ====
var userConnection = mysql.createConnection({
host: config.database.host,
user: config.database.user,
password: config.database.password,
port: config.database.port,
database: config.database.dbUser,
multipleStatements: true
})
userConnection.connect(function(err) {
if (err) throw err;
})
userConnection.query('USE '+config.database.dbUser)
// ALTERNATIVE approach: close db connection manually after every query
/*
var dbconn = function dbconn(query, values, next) {
var connection = mysql.createConnection({
host: config.database.host,
user: config.database.user,
password: config.database.password,
port: config.database.port,
database: config.database.db
})
connection.connect(function(err) {
if (err) throw err;
})
connection.query(query, values, function(err) {
connection.end(); // close the connection
if (err) {
throw err;
}
// Execute the callback
next.apply(this, arguments);
});
}
*/
// ==== PROJECT DB CONNECTION ====
var projectConnection = mysql.createConnection({
host: config.database.host_project,
user: config.database.user,
password: config.database.password,
port: config.database.port,
database: config.database.dbProject
})
projectConnection.connect(function(err) {
if (err) throw err;
})
projectConnection.query('USE '+config.database.dbProject)
var connection = {
user: userConnection,
project: projectConnection
}
module.exports = connection
\ No newline at end of file
const nodemailer = require('nodemailer') const nodemailer = require('nodemailer')
var env = process.env.NODE_ENV || 'testing'; var env = process.env.NODE_ENV || 'testing';
const config = require('../config/config')[env] const config = require('./config')[env]
var smtpTransport = nodemailer.createTransport({ var smtpTransport = nodemailer.createTransport({
host: config.mailer.host, host: config.mailer.host,
secureConnection: config.mailer.secureConnection, secure: config.mailer.secureConnection,
port: config.mailer.port, port: config.mailer.port,
auth: { auth: {
user: config.mailer.authUser, user: config.mailer.authUser,
pass: config.mailer.authPass pass: config.mailer.authPass
},
tls: {
ciphers: config.mailer.tlsCiphers
} }
}); });
......
-- MySQL dump 10.13 Distrib 8.0.15, for Win64 (x86_64)
--
-- Host: localhost Database: userdb
-- ------------------------------------------------------
-- Server version 8.0.15
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
SET NAMES utf8 ;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `role`
--
DROP TABLE IF EXISTS `role`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `role` (
`id` int(11) NOT NULL,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `role`
--
LOCK TABLES `role` WRITE;
/*!40000 ALTER TABLE `role` DISABLE KEYS */;
INSERT INTO `role` VALUES (1,'ADMIN'),(2,'USER'),(3,'OVERVIEW_CREATOR');
/*!40000 ALTER TABLE `role` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2020-03-19 9:21:39
var env = process.env.NODE_ENV || 'testing'
const config = require('../config/config')[env]
const axios = require('axios')
const fs = require('fs')
var formData = require('form-data')
var gitlab = {
// todo: GraphQL currentUser
getUserByEmail: async function(email) {
return axios({
method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/users?search='+email,
headers: {
'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects}
})
.then(res => res.data[0])
.catch(err => console.error(err))
},
createNewPages: async function(newPagesData, newLogoFile, template) {
let data = new formData()
data.append('avatar', fs.createReadStream(newLogoFile))
return axios({
method: 'post',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/user/'+newPagesData.getOwnerGitlabId()+
'?name='+newPagesData.getName()+'&description='+newPagesData.getDesc()+'&tag_list=website'+
'&use_custom_template=true&template_name='+template,
headers: {
'Authorization': 'Bearer '+config.gitlab.token_readWriteProjects,
...data.getHeaders()
},
data: data
})
.then(res => res = {
error: false,
data: res.data
})
.catch(err => res = {
error: true,
data: err.response.data
})
},
updateProject: async function(updatedProjectData, newLogoFile){
let data = new formData()
if (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 = {
error: false,
data: res.data
})
.catch(err => res = {
error: true,
data: err.response.data
})
},
deleteProjectById: function(projectId){
// 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 => res = {
error: false,
data: res.data
})
.catch(err => res = {
error: true,
data: err.response.data
})
},
getUserProjects: async function(gitlabUserId) {
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(err => console.error(err))
},
getProjectById: async function(projectId) {
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(err => console.error(err.response.status))
},
getProjectPipelineLatestStatus: async function(projectId) {
return axios({
method: 'get',
url: 'https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/'+projectId+'/pipelines'
})
.then(res => res.data[0].status)
.catch(err => console.error(err))
},
//
// 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))
});
}
}
module.exports = gitlab
\ No newline at end of file
File moved
const dbconn = require('./dbconn'); const dbconn_OBSOLETE = require('../config/dbconn') // DO NOT USE THIS FOR NEW FUNCTIONS
const dbconn = require('../config/dbconn2')
var methods = { var methods = {
// test method
currentDate: function() {
console.log('Current Date is: ' + new Date().toISOString().slice(0, 10));
},
// ===================== user db ===================== // ===================== user db =====================
registerNewUser: function(data, callback) { registerNewUser: function(data, callback) {
dbconn.user.beginTransaction(function(err) { // START TRANSACTION dbconn_OBSOLETE.user.beginTransaction(function(err) { // START TRANSACTION
if (err) { if (err) {
throw err throw err
} }
// insert profile // insert profile
dbconn.user.query('INSERT INTO user SET ?', data.profile, function (err, results, fields) { dbconn_OBSOLETE.user.query('INSERT INTO user SET ?', data.profile, function (err, results, fields) {
if (err) { if (err) {
return dbconn.user.rollback(function() { return dbconn_OBSOLETE.user.rollback(function() {
throw err throw err
}); });
} }
...@@ -24,9 +21,9 @@ var methods = { ...@@ -24,9 +21,9 @@ var methods = {
user_id: newUserId, user_id: newUserId,
password: data.password password: data.password
} }
dbconn.user.query('INSERT INTO credential SET ?', credentialData, function (err, results, fields) { dbconn_OBSOLETE.user.query('INSERT INTO credential SET ?', credentialData, function (err, results, fields) {
if (err) { if (err) {
return dbconn.user.rollback(function() { return dbconn_OBSOLETE.user.rollback(function() {
throw err throw err
}); });
} }
...@@ -36,9 +33,9 @@ var methods = { ...@@ -36,9 +33,9 @@ var methods = {
role_id: 2, // USER role_id: 2, // USER
user_id: newUserId user_id: newUserId
} }
dbconn.user.query('INSERT INTO user_project_role SET ?', projectRoleData, function (err, results, fields) { dbconn_OBSOLETE.user.query('INSERT INTO user_project_role SET ?', projectRoleData, function (err, results, fields) {
if (err) { if (err) {
return dbconn.user.rollback(function() { return dbconn_OBSOLETE.user.rollback(function() {
throw err throw err
}); });
} }
...@@ -47,16 +44,16 @@ var methods = { ...@@ -47,16 +44,16 @@ var methods = {
user_id: newUserId, user_id: newUserId,
token: data.verificationToken token: data.verificationToken
} }
dbconn.user.query('INSERT INTO verification SET ?', verificationData, function (err, results, fields) { dbconn_OBSOLETE.user.query('INSERT INTO verification SET ?', verificationData, function (err, results, fields) {
if (err) { if (err) {
return dbconn.user.rollback(function() { return dbconn_OBSOLETE.user.rollback(function() {
throw err throw err
}); });
} }
// COMMIT // COMMIT
dbconn.user.commit(function(err) { dbconn_OBSOLETE.user.commit(function(err) {
if (err) { if (err) {
return dbconn.user.rollback(function() { return dbconn_OBSOLETE.user.rollback(function() {
throw err throw err
}) })
} }
...@@ -68,78 +65,70 @@ var methods = { ...@@ -68,78 +65,70 @@ var methods = {
callback(err) callback(err)
}) })
}, },
getUserByEmail: function(email, callback) { getUserByEmail: async function(email) {
dbconn.user.query('SELECT verificationStatus, salutation, title, firstname, lastname, industry, organisation, speciality, m4lab_idp FROM user WHERE email = "' +email+'"', function (err, rows, fields) { try {
if (err) { let rows = await dbconn.user.promise().query('SELECT id, verificationStatus, salutation, title, firstname, lastname, industry, organisation, speciality, m4lab_idp FROM user WHERE email = "' +email+'"')
throw err; if (rows[0][0]) {
} return rows[0][0]
else {
if ( rows.length > 0) {
user = rows[0];
} }
else { return null }
} catch (err) {
console.error(err)
} }
callback(user, err); return null
});
}, },
getUserById: function(userId, callback) { getUserEmailById: async function(userId) {
dbconn.user.query('SELECT verificationStatus, email, salutation, title, firstname, lastname, industry, organisation, speciality FROM user WHERE id = ' +userId, function (err, rows, fields) { try {
if (err) { let rows = await dbconn.user.promise().query('SELECT email FROM user WHERE id = ' +userId)
throw err; if (rows[0][0]) {
return rows[0][0].email
} }
else { else { return null }
if ( rows.length > 0) { } catch (err) {
user = rows[0]; console.error(err)
} }
} return null
callback(user, err);
});
}, },
checkUserEmail: function(email, callback) { checkUserEmail: async function(email) {
let user try {
dbconn.user.query('SELECT id, email FROM user WHERE email = "' +email+'"', function (err, rows, fields) { let rows = await dbconn.user.promise().query('SELECT id, email FROM user WHERE email = "' +email+'"')
if (err) { if (rows[0][0]) {
throw err; return rows[0][0]
}
else {
if ( rows.length > 0) {
user = rows[0];
} }
else { return null }
} catch (err) {
console.error(err)
} }
callback(err, user); return null
});
}, },
getUserByToken: function(token, callback) { getUserByToken: async function(token) {
let user try {
dbconn.user.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(), function (err, rows, fields) { +token+'" and resetPasswordExpires > '+Date.now())
if (err) { if (rows[0][0]) {
throw err; return rows[0][0]
} }
else { else { return null }
if ( rows.length > 0) { } catch (err) {
user = rows[0] console.error(err)
console.log(user) }
} return null
}
callback(err, user);
}
);
}, },
updateUserById: function(userData, callback) { updateUserById: function(userData, callback) {
dbconn.user.query('UPDATE user SET ? WHERE id = ' +userData.id, userData, function (err, rows, fields) { dbconn_OBSOLETE.user.query('UPDATE user SET ? WHERE id = ' +userData.id, userData, function (err, rows, fields) {
if (err) throw err if (err) throw err
callback(err) callback(err)
}) })
}, },
updateCredential: function(data, callback) { updateCredential: function(data, callback) {
dbconn.user.query('UPDATE credential SET ? WHERE user_id = ' +data.user_id, data, function (err, rows, fields) { dbconn_OBSOLETE.user.query('UPDATE credential SET ? WHERE user_id = ' +data.user_id, data, function (err, rows, fields) {
if (err) throw err if (err) throw err
callback(err) callback(err)
}) })
}, },
getUserIdByEmail: function(email, callback) { getUserIdByEmail_OBSOLETE: function(email, callback) {
let userId let userId
dbconn.user.query('SELECT id FROM user WHERE email = "' +email+'"', function (err, rows, fields) { dbconn_OBSOLETE.user.query('SELECT id FROM user WHERE email = "' +email+'"', function (err, rows, fields) {
if (err) { if (err) {
throw err throw err
} }
...@@ -151,67 +140,88 @@ var methods = { ...@@ -151,67 +140,88 @@ var methods = {
callback(userId, err) callback(userId, err)
}); });
}, },
getUserProjectRole: function(userId, callback) { getUserProjectRole_OBSOLETE: function(userId, callback) {
dbconn.user.query('SELECT project_id, role_id FROM user_project_role WHERE user_id = "' +userId+'"', function (err, rows, fields) { 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 if (err) throw err
callback(rows, err) callback(rows, err)
}); });
}, },
addUserProjectRole: function(data, callback) { addUserProjectRole: function(data, callback) {
dbconn.user.query('INSERT INTO user_project_role SET ?', data, function (err, results, fields){ 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: function(userId, callback) { getVerificationTokenByUserId: async function(userId) {
let token try {
dbconn.user.query('SELECT token FROM verification WHERE user_id = "' +userId+'"', function (err, rows, fields) { let rows = await dbconn.user.promise().query('SELECT token FROM verification WHERE user_id = "' +userId+'"')
if (err) { if (rows[0][0]) {
throw err return rows[0][0].token
}
else {
if (rows.length > 0) {
token = rows[0].token
} }
else { return null }
} catch (err) {
console.error(err)
} }
callback(token, err) return null
})
}, },
getUserIdByVerificationToken: function(token, callback) { getUserIdByVerificationToken: async function(token) {
let userId try {
dbconn.user.query('SELECT user_id FROM verification WHERE token = "' +token+'"', function (err, rows, fields) { let rows = await dbconn.user.promise().query('SELECT user_id FROM verification WHERE token = "' +token+'"')
if (err) { if (rows[0][0]) {
throw err return rows[0][0].user_id
} }
else if(rows[0]) { else {
userId = rows[0].user_id return null
} }
callback(userId, err) } catch (err) {
}) console.error(err)
}
return null
}, },
verifyUserAccount: function(userData, callback) { verifyUserAccount: function(userData, callback) {
dbconn.user.beginTransaction(function(err) { // 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.user.query('UPDATE user SET ? WHERE id =' +userData.id, userData, function (err, rows, fields) { dbconn_OBSOLETE.user.query('UPDATE user SET ? WHERE id =' +userData.id, userData, function (err, rows, fields) {
if (err) { if (err) {
return dbconn.user.rollback(function() { throw err }) return dbconn_OBSOLETE.user.rollback(function() { throw err })
} }
// delete verification token // delete verification token
dbconn.user.query('DELETE FROM verification WHERE user_id = '+userData.id, function (err, rows, fields) { dbconn_OBSOLETE.user.query('DELETE FROM verification WHERE user_id = '+userData.id, function (err, rows, fields) {
if (err) { if (err) {
return dbconn.user.rollback(function() { throw err }) return dbconn_OBSOLETE.user.rollback(function() { throw err })
} }
// COMMIT // COMMIT
dbconn.user.commit(function(err) { dbconn_OBSOLETE.user.commit(function(err) {
if (err) { if (err) {
return dbconn.user.rollback(function() { throw err }) return dbconn_OBSOLETE.user.rollback(function() { throw err })
} }
}) })
}) })
}) })
callback(err) callback(err)
}) })
},
/* ===== GitLab ===== */
getGitlabId: async function(userId) {
try {
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]) {
return rows[0][0].gitlab_userId
} else {
return null
}
}
catch(err) {
console.error(err)
return err
}
},
addGitlabUser: function(data, callback){
dbconn_OBSOLETE.user.query('INSERT INTO user_gitlab SET ?', data, function (err) {
if (err) throw err
callback(err)
})
} }
}; };
......
{
"Hello World": "Hallo Welt",
"Hello": "Hallo"
}
\ No newline at end of file
{
"Hello World": "Hello World",
"Hello": "Hello",
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
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