Skip to content
Snippets Groups Projects
Commit ecbf6ce8 authored by Rafael László's avatar Rafael László :speech_balloon:
Browse files

refactor User middlewares and add isLoggedIn middleware

parent 02e25d85
No related branches found
No related tags found
2 merge requests!27refresh dev branch,!26Feature/refactor
Pipeline #5629 passed
import { NextFunction, Request, Response } from "express";
/**
* Middleware to check if the user
* is logged in.
*/
const isLoggedIn = () => (req: Request, res: Response, next: NextFunction) => {
if (req.session!.user) {
next();
} else {
res.status(401);
res.json({ message: "You have to login to see this page!" });
}
};
export default isLoggedIn;
......@@ -3,7 +3,7 @@ import { NextFunction, Request, Response } from "express";
import CardImage from "../../../models/CardImageSchema";
/**
* Get the Entry card background image
* Middleware to get the Entry card background image
* and set res.data.cardImage
*/
const getCardImage = () => async (
......
import { NextFunction, Request, Response } from "express";
import Profile, { Role } from "../../models/ProfileSchema";
import Profile, { IProfile, Role } from "../../models/ProfileSchema";
import { ValidationError } from "../utils/ValidationError";
import { validateFields } from "../utils/validateFields";
// After login the user can register itself
const fields = [
{ name: "studentCardNumber", required: true },
{ name: "roomNumber", required: true },
{ name: "picture", required: false },
];
/**
* Middleware to create own User if doesn't exist
* and set res.data.profile to it
*/
const addUser = () => async (
req: Request,
res: Response,
next: NextFunction
) => {
if (!req.session!.user) {
return res.status(401).json({ message: "You have to login to register!" });
}
// Already registered
if (req.session?.user?.id) {
await Profile.findOne(
{ external_id: req.session.user.id },
(error, profile) => {
if (error) {
console.warn(error);
return res.status(400);
} else {
res.status(200);
res.data.profile = profile;
}
}
);
res.data.profile = await Profile.findById(req.session.user.id)
.lean()
.exec();
return next();
}
// Register
try {
const profile = new Profile();
const newProfile = new Profile();
// Check required fields
const fields = [
{ name: "studentCardNumber", required: true },
{ name: "roomNumber", required: true },
{ name: "picture", required: false },
];
// Validate and set fields from request body
validateFields({ fields, reqBody: req.body });
fields.forEach((field) => {
const value = req.body[field.name];
if (field.required && !value) {
res.status(400);
throw new ValidationError(400, `Field: {${field.name}} is required!`);
}
if (value) profile.set(field.name, value);
if (value) newProfile.set(field.name, req.body[field.name]);
});
profile.external_id = req.session!.user!.external_id;
profile.email = String(req.session?.user?.email);
profile.name = String(req.session?.user?.name);
newProfile.external_id = req.session!.user!.external_id;
newProfile.email = String(req.session?.user?.email);
newProfile.name = String(req.session?.user?.name);
profile.save((err) => {
if (err) {
res.status(400);
} else {
res.status(201);
res.data.profile = profile;
req.session!.user!.id = profile.id;
}
await newProfile.save();
res.data.profile = newProfile;
req.session!.user!.id = newProfile.id;
next();
});
} catch (error) {
if (error instanceof ValidationError) {
const { code, message } = error;
return res.status(code).send({ message });
}
}
};
export default addUser;
......@@ -2,15 +2,16 @@ import { NextFunction, Request, Response } from "express";
import Profile from "../../models/ProfileSchema";
const deletUser = () => (req: Request, res: Response, next: NextFunction) => {
Profile.findByIdAndDelete(req.params.id, (error) => {
if (error) {
res.status(400);
} else {
res.status(204);
}
/**
* Middleware to delete User where id = req.params.id
*/
const deleteUser = () => async (
req: Request,
res: Response,
next: NextFunction
) => {
await Profile.findByIdAndDelete(req.params.id);
next();
});
};
export default deletUser;
export default deleteUser;
......@@ -4,28 +4,12 @@ import Profile, { IProfile } from "../../models/ProfileSchema";
import { IWarning } from "../../models/WarningSchema";
import Warning from "../../models/WarningSchema";
/**
* Middleware to set req.params.id to the current users id.
* getUser() middleware should be called after this.
*/
const getOwnUser = () => (req: Request, res: Response, next: NextFunction) => {
Profile.findOne(
{ external_id: req.session!.user!.id },
async (error, profile) => {
if (error) {
console.warn(error);
res.status(400);
} else {
res.status(200);
let objProfile = profile?.toObject();
if (!!objProfile) {
objProfile.warnings = await Warning.find({
_id: { $in: profile?.warningIds },
}).exec();
}
delete objProfile.warningIds;
res.data.profile = objProfile;
}
req.params.id = req.session.user!.id!;
next();
}
);
};
export default getOwnUser;
......@@ -4,26 +4,17 @@ import { IWarning } from "../../models/WarningSchema";
import Profile from "../../models/ProfileSchema";
import Warning from "../../models/WarningSchema";
const getUser = () => (req: Request, res: Response, next: NextFunction) => {
Profile.findById(req.params.id, async (error, profile) => {
if (error) {
console.warn(error);
res.status(400);
} else {
res.status(200);
let objProfile = profile?.toObject();
if (!!objProfile) {
objProfile.warnings = await Warning.find({
_id: { $in: profile?.warningIds },
}).exec();
}
delete objProfile.warningIds;
res.data.profile = objProfile;
}
/**
* Middleware to get a User by req.params.id
* and set res.data.profile
*/
const getUser = () => async (
req: Request,
res: Response,
next: NextFunction
) => {
res.data.profile = await Profile.findById(req.params.id).lean().exec();
next();
});
};
export default getUser;
......@@ -2,20 +2,13 @@ import { NextFunction, Request, Response } from "express";
import Profile from "../../models/ProfileSchema";
const getUsersList = () => (
const getUsersList = () => async (
req: Request,
res: Response,
next: NextFunction
) => {
Profile.find({}, (err, profiles) => {
if (err) {
res.status(400);
} else {
res.status(200);
res.data.profiles = profiles;
}
res.data.profiles = await Profile.find();
next();
});
};
export default getUsersList;
import { NextFunction, Request, Response, response } from "express";
/**
* Return the found user from res.data.profile
*/
const responseUser = () => (req: Request, res: Response) => {
if (!res.data.profile) {
res.status(404).json({ message: "User not found!" });
......
import { NextFunction, Request, Response, response } from "express";
/**
* Return the found users from res.data.profiles
*/
const responseUserList = () => (req: Request, res: Response) => {
res.json(res.data.profiles);
};
......
......@@ -5,24 +5,26 @@ import Profile from "../../models/ProfileSchema";
// Valid fields to update
const validFields = ["studentCardNumber", "roomNumber", "picture"];
// Update user
const updateUser = () => (req: Request, res: Response, next: NextFunction) => {
Profile.findOne({ _id: req.params.id }, (error, profile) => {
res.status(200);
if (error) {
res.status(400);
} else {
/**
* Update a user
*/
const updateUser = () => async (
req: Request,
res: Response,
next: NextFunction
) => {
const profile = await Profile.findById(req.params.id).exec();
if (profile) {
validFields.forEach((field) => {
const value = req.body[field];
if (value) profile.set(field, value);
});
profile.save();
res.data.profile = profile;
}
}
res.data.profile = profile;
next();
});
};
export default updateUser;
......@@ -18,7 +18,6 @@ export interface IProfile extends Document {
email: string;
name: string;
warningIds: string[] | [];
warnings: IWarning[] | [];
}
const ProfileSchema = new Schema({
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment