Files
P42_API/p42ApiEndpoints.js
T
2025-09-03 21:02:48 +00:00

125 lines
3.6 KiB
JavaScript

import { Utils } from './helpers/utils.js'
export class P42ApiEndpoints{
constructor(app, db) {
this.db = db
this.app = app
this.userinfos = null
this.utils = new Utils()
this.registerPaths()
setInterval(() => {
this.db.query('SELECT 1');
}, 5000);
}
registerPaths(){
this.app.get('/hw', this.hw.bind(this))
this.app.get('/checkauth', this.checkauth.bind(this))
this.app.post('/login', this.login.bind(this))
}
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) {
if((!req.session.userinfo) || (!req.session.userinfo.isAuthenticated)) {
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)
}
///////////////////////////API starts here.../////////////////////////////
async hw(req, res) {
this.ok(req, res, {hello:'world'})
}
async checkauth(req, res)
if(req.session.userInfos && req.session.userInfos.authenticated && req.session.userInfos.username) {
this.ok(req, res, {
authenticated: true,
userInfos: this.userInfos,
})
} else {
this.ok(req, res, {
authenticated: false,
userInfos: null,
})
}
}
async login(req, res) {
let [isValid, payload, errors] = this.utils.validateMapObject(req.body, {
username: ((val, obj) => (typeof(val)=='string') && (val.length>3) ),
passwd: ((val, obj) => (typeof(val)=='string') && (val.length>7) ),
},{
'username': 'username',
'passwd': 'passwd',
})
if((!isValid)){
this.err(req, res, `Invalid request', 'Invalid login payload:: ${errors}`, 401)
return
}
if((payload.username=='toto') && (payload.passwd=='azertyuiop')){
req.session.userInfos = {
authenticated: true,
username: payload.username,
roles: ['admin']
}
this.ok(req, res, {
authenticated: true,
userInfos: req.session.userInfos,
})
} else {
this.ok(req, res, {
authenticated: false,
userInfos: null,
})
}
}
}