Colubrina/backend/lib/authorize.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

2022-06-05 22:58:18 +10:00
const { User, Theme, Session } = require("../models")
const Errors = require("./errors")
2022-08-03 19:11:19 +10:00
const { Op } = require("sequelize")
2022-06-05 22:58:18 +10:00
module.exports = async function (req, res, next) {
try {
if (req.header("Authorization") && req.header("Authorization") !== "null") {
const token = req.header("Authorization")
2022-08-03 19:11:19 +10:00
const session = await Session.findOne({
where: {
session: token,
expiredAt: {
[Op.gt]: new Date()
}
}
})
2022-06-05 22:58:18 +10:00
if (session) {
const user = await User.findOne({
where: { id: session.userId },
attributes: {
2022-07-31 14:56:43 +10:00
exclude: ["totp", "password", "emailToken"]
2022-06-05 22:58:18 +10:00
},
include: [
{
model: Theme,
as: "themeObject"
}
]
})
if (user) {
2022-07-29 19:20:19 +10:00
if (user.banned) {
2022-08-31 18:46:40 +10:00
res.status(401).json({ errors: [Errors.banned] })
2022-07-29 19:20:19 +10:00
return
}
2022-06-05 22:58:18 +10:00
await user.update({
lastSeenAt: new Date().toISOString()
})
req.user = user
next()
}
} else {
2022-08-31 18:46:40 +10:00
res.status(401).json({ errors: [Errors.unauthorized] })
2022-06-05 22:58:18 +10:00
}
} else {
res.status(401).json({
errors: [
{
message: "You need to be logged in."
}
]
})
}
} catch (e) {
console.log(e)
}
}