diff --git a/authGuard.js b/authGuard.js new file mode 100644 index 0000000..0d73821 --- /dev/null +++ b/authGuard.js @@ -0,0 +1,14 @@ +export function authGuard(req, res, next) { + const { userInfos, authenticated } = req.session || {} + if (!userInfos || !authenticated) { + let jsonResp = {'success':false, + 'payload': null, + 'error': { + 'displayMessage' : 'Please login first !', + 'debugMessage' : 'No session or unauthorized one.' + } + } + return res.status(401).json(jsonResp) + } + next() +} \ No newline at end of file diff --git a/p42ApiEndpoints.js b/p42ApiEndpoints.js index 7b0efec..019ba46 100644 --- a/p42ApiEndpoints.js +++ b/p42ApiEndpoints.js @@ -1,6 +1,8 @@ import { Utils } from './helpers/utils.js' import { verifyPassword } from './helpers/pwd.js' import { MySQLClient } from './helpers/mysqlClient.js' +import { authGuard } from './authGuard.js' + export class P42ApiEndpoints{ constructor(app, db) { this.db = new MySQLClient(db, 60) @@ -11,11 +13,11 @@ export class P42ApiEndpoints{ } 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)) this.app.get('/logout', this.logout.bind(this)) - + this.app.get('/preferences', authGuard, this.getPrefs.bind(this)) + this.app.put('/preferences', authGuard, this.setPrefs.bind(this)) } err(req, res, msg, debug, status=500) { @@ -26,7 +28,7 @@ export class P42ApiEndpoints{ 'displayMessage' : msg, 'debugMessage' : debug } - }; + } res.set('Content-Type', 'application/json'); res.status(status) res.send(JSON.stringify(jsonResp)); @@ -59,10 +61,6 @@ export class P42ApiEndpoints{ } ///////////////////////////API starts here...///////////////////////////// - async hw(req, res) { - this.ok(req, res, {hello:'world'}) - } - async checkauth(req, res) { if(req.session.userInfos && req.session.authenticated && req.session.userInfos && req.session.userInfos.identity && req.session.userInfos.identity.username) { this.ok(req, res, { @@ -183,4 +181,27 @@ export class P42ApiEndpoints{ } } + + async getPrefs(req, res) { + const results = await this.db.execute(` + SELECT * FROM preferences + LEFT JOIN users ON prf_usr_id=usr_id + WHERE usr_uuid = ? + `, [req.session.userInfos.identity.uuid]) + let prefs = {} + if(results.length){ prefs = results[0].prf_value } + this.ok(req, res, prefs) + } + + + async setPrefs(req, res) { + const results = await this.db.execute(` + INSERT INTO preferences (prf_usr_id, prf_value) + SELECT usr_id, ? + FROM users + WHERE usr_uuid = ? + ON DUPLICATE KEY UPDATE prf_value = ? + `, [req.body, req.session.userInfos.identity.uuid, req.body]) + this.ok(req, res, {}) + } }