From d0cd3e2caa7bf59034a74dcf58565dfd98802a8d Mon Sep 17 00:00:00 2001 From: Niko Date: Sun, 13 Feb 2022 02:03:02 +0100 Subject: [PATCH] Added auth.js for session enforcing and other methods (for API and others) --- api/src/auth.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 api/src/auth.js diff --git a/api/src/auth.js b/api/src/auth.js new file mode 100644 index 0000000..df08791 --- /dev/null +++ b/api/src/auth.js @@ -0,0 +1,29 @@ +const pwd = require('./passwd.js') +const utils = require('./utils.js') + +module.exports = { + enforceSession: async (req, res, next) => { + const ret403 = (reason) => { + const suffix = reason !== undefined ? '. Reason: '+reason : '' + return res.status(403).send('API endpoint forbidden'+suffix) + } + + if (req.cookies['fedilove_session'] === undefined) + return ret403() + + const sess = await db.table.sessions().findOne({ session: req.cookies['fedilove_session'] }) + if (sess === null) + return ret403() + + const user = await db.table.users().findOne({ _id: sess.id_user }) + if (user.activated !== 1) + return ret403('User is no activated yet') + if (user.banned !== undefined && user.banned === 1) + return ret403('User has been banned') + if (user.deleted !== undefined && user.deleted === 1) + return ret403('User has been deleted') + + res.locals.user = user + next() + }, +}