store logged user's instructor status to header

Check when user logins if their student number is stored in any group
that belong to the last created configuration. This information is
stored into the token.

Use this change to define a middleware function to check if a logged
token is classified as an instructor.

These cahanges are to enable alternate backend requests for data used
to develop admin and instructor views for time logs.
This commit is contained in:
regularmute
2024-04-25 22:00:48 +03:00
parent 5069fa6ba5
commit 93ca13fc45
2 changed files with 42 additions and 1 deletions
+26 -1
View File
@@ -10,6 +10,30 @@ const handleDatabaseError = (res, error) => {
.json({ error: 'Something is wrong... try reloading the page' })
}
const checkIfActiveInstructor = async (student_number) => {
try {
const latestConfigurationId = await db.Configuration.findOne({
order: [['created_at', 'DESC']],
attributes: ['id']
})
if (!latestConfigurationId) {
return false
}
const group = await db.Group.findOne({
where: {
configuration_id: latestConfigurationId.id,
instructor_id: student_number
}
})
return !!group
} catch (error) {
console.error('Error checking if active instructor:', error)
return false
}
}
loginRouter.post('/', async (req, res) => {
if (!req.headers.hypersonstudentid)
return res
@@ -27,7 +51,8 @@ loginRouter.post('/', async (req, res) => {
if (foundUser) {
//user already in database, no need to add
const token = jwt.sign(
{ id: foundUser.student_number, admin: foundUser.admin },
{ id: foundUser.student_number, admin: foundUser.admin,
instructor: checkIfActiveInstructor(foundUser.student_number) },
config.secret
)
return res.status(200).set('Cache-Control', 'no-store').json({
+16
View File
@@ -68,6 +68,21 @@ const checkLogin = (req, res, next) => {
next()
}
/** @type {RequestHandler} */
const checkInstructor = (req, res, next) => {
const { error, status, token } = authenticateToken(req)
if (!token) {
return res.status(status).json({ error })
}
if (!token.instructor && !token.admin) {
return res.status(401).json({ error: 'not instructor' })
}
req.user = token
next()
}
/** @type {RequestHandler} */
const checkAdmin = (req, res, next) => {
const { error, status, token } = authenticateToken(req)
@@ -106,6 +121,7 @@ const logger = (request, response, next) => {
module.exports = {
checkLogin,
checkInstructor,
checkAdmin,
logger,
fakeshibbo,