Files
P42_API/p42ApiEndpoints.js
T
STEINNI 6fb75a0888 1st
2025-08-30 23:26:12 +00:00

211 lines
6.8 KiB
JavaScript

const mysql = require('mysql2/promise');
class P42ApiEndpoints{
constructor(app) {
this.db = null
this.app = app
this.userinfos = null
this.registerPaths()
}
registerPaths(){
this.app.get('/hw', this.hw.bind(this))
}
async connectDB(mysqlCreds) {
this.db = await mysql.createConnection({
host: mysqlCreds.host,
port: mysqlCreds.port,
socketPath: mysqlCreds.socketPath,
database: mysqlCreds.database,
user: mysqlCreds.user,
password: mysqlCreds.password
});
setInterval(() => {
this.db.query('SELECT 1');
}, 5000);
}
err(req, res, msg, debug, status=500) {
if(!debug) debug = msg
let jsonResp = {'success':false,
'payload': null,
'error': {
'displayMessage' : msg,
'debugMessage' : debug
}
};
res.set('Content-Type', 'application/json');
res.status(status)
res.send(JSON.stringify(jsonResp));
}
ok(req, res, payload) {
let jsonResp = { "success": true,
"payload": payload,
};
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(jsonResp));
}
async makeSession(req, res) {
req.session.userinfo = req.body
console.log('REQ body:', req.body)
this.ok(req, res, {})
}
getSession(req, res) {
this.userinfos = {
"at_hash": "fhaNqJbWprmseino7D7vQhdEIWzlss6a08DvgY_Y7ik",
"sub": "steinic",
"amr": [
"pwd"
],
"iss": "https://ecas.acceptance.ec.europa.eu/cas/oauth2",
// Impersonate here
"preferred_username": "fallimi", //"steinic",
"locale": "en",
"https://ecas.ec.europa.eu/claims/domain": "eu.europa.ec",
"acr": "https://ecas.ec.europa.eu/loa/basic",
"auth_time": 1686415198,
"nickname": "steinic",
"https://ecas.ec.europa.eu/claims/teleworking_priority": false,
"exp": 1686415501,
"iat": 1686415201,
"email": "Nicolas.STEIN@ext.ec.europa.eu",
"https://ecas.ec.europa.eu/claims/employee_number": "90218167",
"email_verified": true,
"https://ecas.ec.europa.eu/claims/department_number": "EISMEA.C.02.2",
"https://ecas.ec.europa.eu/claims/employee_type": "x",
"given_name": "Nicolas",
"https://ecas.ec.europa.eu/claims/org_id": "232619",
"aud": "zjDAOobFg2JJzMxhzfoTyPg1BrOzPzG4EMUJOoqUbF1mYTkwddaZwL4o9YzzK3unIZAEunze7fQAfOoOgXnq9Xhr-NaAc23CqASenqizgfAeUl6",
"c_hash": "8pzkBbmGEZW48yLZYoEoR_H3QC0GIeWYxlzUCfRMElg",
"https://ecas.ec.europa.eu/claims/sso": false,
"https://ecas.ec.europa.eu/claims/authentication_factors": [
{
"username": "steinic"
}
],
"name": "Nicolas STEIN",
"https://ecas.ec.europa.eu/claims/uid": "steinic",
"family_name": "STEIN",
"userRoles": [
"BP_PO",
"APPLICANT",
]
}
return(true)
if((!req.session.userinfo) || (!req.session.userinfo.isAuthenticated)) {
this.err(req, res, 'Not authenticated !')
this.userinfos = null
return(false)
} else {
req.session.touch()
this.userinfos = req.session.userinfo
return(true)
}
}
hasRole(roles) {
if(!this.userinfos.userRoles) return(false)
if(typeof(roles) == 'string') return(this.userinfos.userRoles.includes(roles))
else if(Array.isArray(roles)) {
for(let role of roles) {
if(this.userinfos.userRoles.includes(role)) return(true)
}
}
return(false)
}
CheckMapOutput(data, remap, transformers) {
if(!data) return(null)
let rows = Array.isArray(data) ? data : [data]
let filteredRows = []
for(let row of rows) {
let filteredRow = {}
Object.keys(row).forEach((key, index) => {
if(Object.keys(remap).indexOf(key)>-1) {
if(transformers && transformers[key] && (typeof(transformers[key])=='function')) {
filteredRow[remap[key]] = transformers[key](row[key])
} else filteredRow[remap[key]] = row[key]
}
});
filteredRows.push(filteredRow)
}
if(Array.isArray(data)) return(filteredRows)
else return(filteredRows[0])
}
CheckMapInput(dataIn, remap, checks) {
let dataOut = {}
for(let field in checks) {
let dbName = checks[field](dataIn[field])
if(dbName && (dataIn[field]!=null)) dataOut[remap[field]] = dataIn[field]
}
return(dataOut)
}
async isMemberOf(pic) {
let [rows, fields] = await this.db.query(`
SELECT count(*) as cnt FROM organisation_members
WHERE (om_pic=?)
AND (om_uid=?)
`,
[pic, this.userinfos.preferred_username]);
return(rows[0]['cnt']>0)
}
async isOrgAdminOf(pic) {
let [rows, fields] = await this.db.query(`
SELECT count(*) as cnt FROM organisation_members
WHERE (om_pic=?)
AND (om_uid=?)
AND om_administrator=1
`,
[pic, this.userinfos.preferred_username]);
return(rows[0]['cnt']>0)
}
async isPropAdminOf(pid) {
let [rows, fields] = await this.db.query(`
SELECT count(*) as cnt FROM shortprops_members
WHERE (spm_prop_id=?)
AND (spm_uid=?)
AND spm_administrator=1
`,
[pid, this.userinfos.preferred_username]);
return(rows[0]['cnt']>0)
}
async isPropMemberOf(pid) {
let [rows, fields] = await this.db.query(`
SELECT count(*) as cnt FROM shortprops_members
WHERE (spm_prop_id=?)
AND (spm_uid=?)
`,
[pid, this.userinfos.preferred_username]);
return(rows[0]['cnt']>0)
}
async merge(table, where, whereVals, data) {
let [rows, field] = await this.db.query(`SELECT * FROM ${table} WHERE ${where}`, whereVals)
if(rows.length==0) return(data)
else return(Object.assign(rows[0], data))
}
///////////////////////////API starts here.../////////////////////////////
async hw(req, res) {
this.ok(req, res, {hello:'world'})
}
}
module.exports = P42ApiEndpoints;