Added auth.js for session enforcing and other methods (for API and others)

This commit is contained in:
Niko 2022-02-13 02:03:02 +01:00
parent 1c05bb5186
commit d0cd3e2caa
1 changed files with 29 additions and 0 deletions

29
api/src/auth.js Normal file
View File

@ -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()
},
}