2022-04-05 01:15:43 +00:00
|
|
|
import MongoStore from "connect-mongo";
|
|
|
|
import session from "express-session";
|
|
|
|
import { mongooseDbName, mongoURI } from "../database/mongoose.js";
|
2022-04-05 03:50:26 +00:00
|
|
|
import userModel from "../schemas/userModel.js";
|
2022-04-07 22:56:04 +00:00
|
|
|
import { checkDatabaseConnection } from "./database.js";
|
2022-04-05 01:15:43 +00:00
|
|
|
const sessionConf = {
|
|
|
|
secret: process.env.SESSION_SECRET || "super duper secret string.",
|
|
|
|
cookie: {
|
|
|
|
expires: process.env.SESSION_TIMEOUT || 300000,
|
|
|
|
httpOnly: true,
|
|
|
|
},
|
|
|
|
saveUninitialized: false,
|
|
|
|
resave: false,
|
|
|
|
};
|
|
|
|
if (process.env.NODE_ENV === "production") {
|
|
|
|
sessionConf.cookie.secure = true;
|
|
|
|
sessionConf.store = MongoStore.create({ mongoUrl: mongoURI, dbName: mongooseDbName });
|
|
|
|
}
|
|
|
|
export const userSession = session(sessionConf);
|
|
|
|
|
2022-04-05 16:50:35 +00:00
|
|
|
export async function requireAuthenticated(req, res, next) {
|
2022-04-07 22:56:04 +00:00
|
|
|
if (!checkDatabaseConnection()) {
|
|
|
|
req.status(500).send("Internal server error.");
|
|
|
|
return;
|
|
|
|
}
|
2022-04-05 01:15:43 +00:00
|
|
|
if (req.session.userId) {
|
2022-04-05 03:50:26 +00:00
|
|
|
req.user = await userModel.findById(req.session.userId);
|
2022-04-05 01:15:43 +00:00
|
|
|
next();
|
|
|
|
} else {
|
2022-04-05 03:50:26 +00:00
|
|
|
res.status(401).send("Not authorized.");
|
2022-04-05 01:15:43 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2022-04-07 22:56:04 +00:00
|
|
|
|
|
|
|
|
|
|
|
export async function requireAdmin(req, res, next) {
|
|
|
|
if (!checkDatabaseConnection()) {
|
|
|
|
req.status(500).send("Internal server error.");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (req.session.userId) {
|
|
|
|
req.user = await userModel.findById(req.session.userId);
|
|
|
|
if (req.user.accessLevel < 3) {
|
|
|
|
res.status(401).send("Not authorized");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
next();
|
|
|
|
} else {
|
|
|
|
res.status(401).send("Not authorized.");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|