Commit 9b0bffa7 authored by Rosanny Sihombing's avatar Rosanny Sihombing
Browse files

Merge branch 'testing' into devel

parents 91e7f42e 961ab112
/built
/routes/cert
/node_modules /node_modules
sp-account-metadata.xml
.idea
pages-devel: deploy-testing:
stage: deploy stage: deploy
script: script:
- 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 ./app.js --name=account - pm2 start ./built/app.js --name=account
- pm2 save - pm2 save
tags: tags:
- testing - testing
only: only:
- testing - testing
- test_logoutbutton
pages-devel: deploy-master:
stage: deploy stage: deploy
script: script:
- cat $configfileprod > ./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
- "pm2 delete --silent account || :" - "pm2 delete --silent account || :"
- pm2 start ./app.js --name=account - pm2 start ./app.js --name=account
......
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
import gitlab from '../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
import methods from '../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()
})
})
\ No newline at end of file
const express = require('express'); import express from 'express';
const http = require('http'); import path from 'path';
const path = require('path'); import passport from 'passport';
const passport = require('passport'); import morgan from 'morgan';
const morgan = require('morgan'); import cookieParser from 'cookie-parser';
const cookieParser = require('cookie-parser'); import bodyParser from 'body-parser';
const bodyParser = require('body-parser'); import session from 'express-session';
const session = require('express-session'); import flash from 'express-flash-2';
const errorhandler = require('errorhandler'); import fileUpload from 'express-fileupload';
const flash = require('express-flash'); import helmet from 'helmet';
const fileUpload = require('express-fileupload'); import compression from 'compression';
import methodOverride from 'method-override';
import dotenv from 'dotenv'
const i18n = require('i18n'); // internationalization dotenv.config();
i18n.configure({
locales:['de', 'en'],
directory: './locales'
});
var env = process.env.NODE_ENV || 'development'; 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();
app.set('port', config.app.port); app.set('port', config.app.port);
app.set('views', __dirname + '/views'); app.set('views', path.join( __dirname + '/views'));
app.set('view engine', 'pug'); app.set('view engine', 'pug');
// enable files upload // enable files upload
...@@ -32,32 +30,38 @@ app.use(fileUpload({ ...@@ -32,32 +30,38 @@ 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(compression());
app.use(morgan('combined')); app.use(morgan('combined'));
app.use(cookieParser()); 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(i18n.init);
app.use((req, res, next) => { app.use((req, res, next) => {
res.setLocale('de');
next(); next();
}); });
app.use(session( 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());
...@@ -68,19 +72,18 @@ app.use(function(req, res, next) { ...@@ -68,19 +72,18 @@ app.use(function(req, res, next) {
next(); next();
}); });
require('./routes/routes-account')(app, config, passport, i18n); require('./routes/public')(app, config, lang);
require('./routes/api')(app, config, passport); require('./routes/account')(app, config, passport, lang);
// Handle 404 // Handle 404
app.use(function (req, res, next) { app.use(function (req:any, res:any) {
//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:any, req:any, res:any, next:any) {
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 {
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.name = name
this.desc = desc
this.id = id
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:number){
this.ownerGitlabId = newOwnerGitlabId
}
setId(newId:number) {
this.id = newId
}
setName(newName:string) {
this.name = newName
}
setDesc(newDesc:string) {
this.desc = newDesc
}
setLogo(newLogoUrl:string) {
this.logo = newLogoUrl
}
setPath(newPath:string) {
this.path = newPath
}
}
export = Project
\ 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 {
id:number
email:string
salutation:string // should be enum
title:string // should be enum
firstName:string
lastName:string
industry:string
organisation:string
speciality:string
is_m4lab_idp:number // 1 or 0
verificationStatus:number // 1 or 0 - // should be boolean
gitlabUserId?:number
constructor(id:number, email:string, salutation:string, title:string, firstName:string, lastName:string, industry:string, organisation:string,
speciality:string, is_m4lab_idp:number, verificationStatus:number, gitlabUserId?:number) {
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
getId() {
return this.id
}
getEmail() {
return this.email
}
getFullName() {
return this.firstName+' '+this.lastName
}
getIdpStatus() {
return this.is_m4lab_idp
}
getVerificationStatus() {
return this.verificationStatus
}
getGitlabUserId() {
return this.gitlabUserId
}
// setter
setEmail(email:string) {
this.email = email
}
setSalutation(salutation:string) {
this.salutation = salutation
}
setTitle(title:string) {
this.title = title
}
setFirstName(firstName:string) {
this.firstName = firstName
}
setLastName(lastName:string) {
this.lastName = lastName
}
setIndustry(industry:string) {
this.industry = industry
}
setOrganisation(organisation:string) {
this.organisation = organisation
}
setSpeciality(speciality:string) {
this.speciality = speciality
}
setM4lab_idp(m4lab_idp:number) {
this.is_m4lab_idp = m4lab_idp
}
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
\ 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
module.exports = { export = {
development: { development: {
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',
saml: { saml: {
path: process.env.SAML_PATH || '/saml/SSO', path: process.env.SAML_PATH || '/saml/SSO',
entryPoint: process.env.SAML_ENTRY_POINT || 'https://m4lab.hft-stuttgart.de/idp/saml2/idp/SSOService.php', entryPoint: process.env.SAML_ENTRY_POINT || 'Saml Entry Point',
issuer: 'sp-account.m4lab.hft-stuttgart.de', //local metadata issuer: 'SAML issuer', //local metadata
logoutUrl: 'https://m4lab.hft-stuttgart.de/idp/saml2/idp/SingleLogoutService.php' logoutUrl: 'SAML logout URL'
} }
}, },
database: { database: {
host: 'localhost', // DB host host: 'localhost', // DB host
user: 'DBManager', // DB username user: 'usernamedb', // DB username
password: 'Stuttgart2019', // DB password password: 'passworddb', // 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: 'mail.hft-stuttgart.de', // 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
authUser: 'ad\\support-transfer', TLS: true,
authPass: '6laumri2', authUser: 'mailuser',
authPass: 'mailpass',
tlsCiphers: 'SSLv3', tlsCiphers: 'SSLv3',
from: 'support-transfer@hft-stuttgart.de', 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',
saml: { saml: {
path: process.env.SAML_PATH || '/saml/SSO', path: process.env.SAML_PATH || '/saml/SSO',
entryPoint: process.env.SAML_ENTRY_POINT || 'https://m4lab.hft-stuttgart.de/idp/saml2/idp/SSOService.php', entryPoint: process.env.SAML_ENTRY_POINT || 'saml entry point',
issuer: 'sp-account-testing.m4lab.hft-stuttgart.de', //testing metadata issuer: 'SAML issuer', //testing metadata
//issuer: 'sp-account-prod.m4lab.hft-stuttgart.de', //production metadata logoutUrl: 'SAML logout URL'
logoutUrl: 'https://m4lab.hft-stuttgart.de/idp/saml2/idp/SingleLogoutService.php'
} }
}, },
database: { database: {
host: 'transfer.hft-stuttgart.de', // DB host host: 'dbhost', // DB host
user: 'DBManager', // DB username user: 'dbuser', // DB username
password: 'Stuttgart2019', // DB password password: 'dbpass', // DB password
port: 3306, // MySQL port port: 3306, // MySQL port
dbUser: 'userdb', // User DB dbUser: 'userdb', // User DB
host_project: 'm4lab.hft-stuttgart.de', // DB host project db host_project: 'dbhost', // DB host project db
dbProject: 'projectDB' // Project DB dbProject: 'projectdb' // Project DB
}, },
mailer: { mailer: {
host: 'mail.hft-stuttgart.de', // 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
authUser: 'ad\\support-transfer', TLS: true,
authPass: '6laumri2', authUser: 'mailuser',
authPass: 'mailpass',
tlsCiphers: 'SSLv3', tlsCiphers: 'SSLv3',
from: 'support-transfer@hft-stuttgart.de', from: 'mailfrom',
},
gitlab: {
token_readWriteProjects: 'token-goes-here'
} }
} }
} }
\ No newline at end of file
export = {
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
import mysql from 'mysql2'
var env = process.env.NODE_ENV || 'testing'
const config = require('./config')[env]
// ==== USER ACOOUNT DB CONNECTION ====
const userConnection = mysql.createPool({
host: config.database.host,
user: config.database.user,
password: config.database.password,
port: config.database.port,
database: config.database.dbUser,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
userConnection.query('USE '+config.database.dbUser)
// ==== PROJECT DB CONNECTION ====
const projectConnection = mysql.createPool({
host: config.database.host_project,
user: config.database.user,
password: config.database.password,
port: config.database.port,
database: config.database.dbProject,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
projectConnection.query('USE '+config.database.dbProject)
const connection = {
user: userConnection,
project: projectConnection
}
export = connection
\ 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 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
-- 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
import axios from 'axios'
import fs from 'fs'
import formData from 'form-data'
var env = process.env.NODE_ENV || 'testing'
const config = require('../config/config')[env]
var gitlab = {
getUserByEmail: async function(email:string) {
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(function(err){
console.error(err)
return null
})
},
createNewPages: async function(newPagesData:any, newLogoFile:string, template:any) {
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.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
})
},
updateProject: async function(updatedProjectData:any, newLogoFile:string){
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.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
})
}
}
export = gitlab
\ No newline at end of file
var helpers = { var helpers = {
stringToArray: function (input){ stringToArray: function (input:string){
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 = {
} }
}; };
module.exports = helpers; export = helpers;
\ No newline at end of file \ No newline at end of file
import dbconn = require('../config/dbconn')
var methods = {
// ===================== user db =====================
registerNewUser: function(data:any, callback:any) {
dbconn.user.getConnection(function(err:any, thisconn){
thisconn.beginTransaction(function(err:any) { // START TRANSACTION
if (err) { throw err }
// insert profile
thisconn.query('INSERT INTO user SET ?', data.profile, function (err:any, results:any, fields:any) {
if (err) {
return thisconn.rollback(function() {
throw err
});
}
let newUserId:number = results.insertId
// set password
var credentialData:any = {
user_id: newUserId,
password: data.password
}
thisconn.query('INSERT INTO credential SET ?', credentialData, function (err:any, results:any, fields:any) {
if (err) {
return thisconn.rollback(function() {
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 {
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
thisconn.commit(function(err:any) {
if (err) {
return thisconn.rollback(function() { throw err })
}
})
})
})
})
callback(err)
})
},
/* ===== GitLab ===== */
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')
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
{}
\ 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