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

Merge branch 'devel' into 'testing'

Refactoring and codes cleaning

See merge request !144
parents 961ab112 4450156e
Pipeline #6621 failed with stage
in 20 seconds
{
"presets": [
"@babel/preset-env", "@babel/preset-typescript", "minify"
]
}
\ No newline at end of file
/built
/routes/cert
/src/routes/cert
/node_modules
const dbController = require('../../src/controller/dbController')
describe('DB methohds test', () => {
it('returns a user from DB by email', async () => {
const user = await dbController.getUserByEmail('litehon958@whipjoy.com')
expect(user).not.toBeNull()
})
it('returns a null user', async () => {
const user = await dbController.getUserByEmail('jondoe@nowhere.com') // a non-exist user
expect(user).toBeNull()
})
it("returns a user's email", async () => {
const email = await dbController.getUserEmailById(1)
expect(email).not.toBeNull()
})
it("returns null instead of a user's email", async () => {
const email = await dbController.getUserEmailById(1005) // no user has this ID
expect(email).toBeNull()
})
it('returns null from DB by token', async () => {
const user = await dbController.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 dbController.getVerificationTokenByUserId(1)
expect(token).toBeNull()
})
it("returns a user's ID, if any", async () => {
const token = await dbController.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 dbController.getGitlabId(1)
expect(id).not.toBeNull()
})
it('checks user email', async () => {
const user = await dbController.checkUserEmail('litehon958@whipjoy.com')
expect(user).not.toBeNull()
})
it('checks user email and return null', async () => {
const user = await dbController.checkUserEmail('jondoe@nowhere.com') // a non-exist user
expect(user).toBeNull()
})
})
import gitlab from '../functions/gitlab'
//const axios = require('axios')
//jest.mock('axios')
const gitlabController = require('../src/controller/gitlabController')
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')
axios.get.mockResolvedValue({
})
const user = await gitlabController.getUserByEmail('litehon958@whipjoy.com')
expect(user).not.toBeNull()
})
test('returns an undefined user', async () => {
let user = await gitlab.getUserByEmail('johndoe@nowhere.com')
const user = await gitlabController.getUserByEmail('johndoe@nowhere.com')
expect(user).toBeUndefined()
})
test('returns users project', async () => {
let userProjects = await gitlab.getUserProjects(136)
const userProjects = await gitlabController.getUserProjects(136)
expect(userProjects).toBeDefined()
})
test('returns undefined projects, due to non-existing gitlab user ID', async () => {
let userProjects = await gitlab.getUserProjects(0)
const userProjects = await gitlabController.getUserProjects(0)
expect(userProjects).toBeUndefined()
})
test('returns a project by ID', async () => {
let project = await gitlab.getProjectById(13) // m4lab_landing_page
const project = await gitlabController.getProjectById(13) // m4lab_landing_page
expect(project).toBeDefined()
})
test('returns undefined, due to invalid project ID', async () => {
let project = await gitlab.getProjectById(0)
const project = await gitlabController.getProjectById(0)
expect(project).toBeUndefined()
})
})
\ No newline at end of file
})
const request = require('supertest')
const express = require('express')
const app = express()
app.set('port', 9989)
describe('Test endpoint(s)', () => {
it('should return a 200 status code', () => {
request(app)
.get('/contact')
.expect(200)
.end(function (err, res) {
if (err) throw err
})
})
})
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
import express from 'express';
import path from 'path';
import passport from 'passport';
import morgan from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import session from 'express-session';
import flash from 'express-flash-2';
import fileUpload from 'express-fileupload';
import helmet from 'helmet';
import compression from 'compression';
import methodOverride from 'method-override';
import dotenv from 'dotenv'
dotenv.config();
var env = process.env.NODE_ENV || 'testing';
const config = require('./config/config')[env];
const lang = 'DE';
var app = express();
app.set('port', config.app.port);
app.set('views', path.join( __dirname + '/views'));
app.set('view engine', 'pug');
// enable files upload
app.use(fileUpload({
createParentPath: true,
limits: {
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(cookieParser(config.app.sessionSecret));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
next();
});
app.use(session({
resave: true,
saveUninitialized: true,
secret: config.app.sessionSecret
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
// caching disabled for every route
// NOTE: Works in Firefox and Opera. Does not work in Edge
app.use(function(req, res, next) {
res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
next();
});
require('./routes/public')(app, config, lang);
require('./routes/account')(app, config, passport, lang);
// Handle 404
app.use(function (req:any, res:any) {
res.status(404).render(lang+'/404')
})
// Handle 500 - any server error
app.use(function (err:any, req:any, res:any, next:any) {
console.error(err.stack)
res.status(500).render(lang+'/500', {
error: err
})
})
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
\ No newline at end of file
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
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
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
})