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(this.getSession(req, res)) { this.ok(req, res, { authenticated: true, userInfos: this.userinfos, }) } else { this.ok(req, res, { authenticated: false, userInfos: null, }) } } async login(req, res) { console.log('====>req.json', req.body) 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.userinfo = { username: payload.username, roles: ['admin'] } this.ok(req, res, { authenticated: true, userInfos: req.session.userinfo, }) } else { this.ok(req, res, { authenticated: false, userInfos: null, }) } } }