Added suspension mechanism.

This commit is contained in:
2022-04-07 17:56:04 -05:00
parent 2e8ba9c5b1
commit eb4e4b2444
5 changed files with 107 additions and 40 deletions

View File

@@ -2,6 +2,7 @@ import MongoStore from "connect-mongo";
import session from "express-session";
import { mongooseDbName, mongoURI } from "../database/mongoose.js";
import userModel from "../schemas/userModel.js";
import { checkDatabaseConnection } from "./database.js";
const sessionConf = {
secret: process.env.SESSION_SECRET || "super duper secret string.",
cookie: {
@@ -18,6 +19,10 @@ if (process.env.NODE_ENV === "production") {
export const userSession = session(sessionConf);
export async function requireAuthenticated(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);
next();
@@ -26,3 +31,22 @@ export async function requireAuthenticated(req, res, next) {
return;
}
}
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;
}
}

View File

@@ -1,9 +1,13 @@
import mongoose from "mongoose";
export function needDatabase(res, req, next) {
if (mongoose.connection.readyState != 1) {
export function needDatabase(req, res, next) {
if (checkDatabaseConnection()) {
res.status(500).send("Internal server error: Database connection faulty.");
} else {
next();
}
}
export function checkDatabaseConnection() {
return mongoose.connection.readyState == 1;
}