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"; ...@@ -3,7 +3,7 @@ import { NextFunction, Request, Response } from "express";
import CardImage from "../../../models/CardImageSchema"; import CardImage from "../../../models/CardImageSchema";
/** /**
* Get the Entry card background image * Middleware to get the Entry card background image
* and set res.data.cardImage * and set res.data.cardImage
*/ */
const getCardImage = () => async ( const getCardImage = () => async (
......
import { NextFunction, Request, Response } from "express"; 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 { 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 ( const addUser = () => async (
req: Request, req: Request,
res: Response, res: Response,
next: NextFunction next: NextFunction
) => { ) => {
if (!req.session!.user) {
return res.status(401).json({ message: "You have to login to register!" });
}
// Already registered // Already registered
if (req.session?.user?.id) { if (req.session?.user?.id) {
await Profile.findOne( res.data.profile = await Profile.findById(req.session.user.id)
{ external_id: req.session.user.id }, .lean()
(error, profile) => { .exec();
if (error) {
console.warn(error);
return res.status(400);
} else {
res.status(200);
res.data.profile = profile;
}
}
);
return next(); return next();
} }
// Register // Register
try { const newProfile = new Profile();
const profile = new Profile();
// Check required fields // Validate and set fields from request body
const fields = [ validateFields({ fields, reqBody: req.body });
{ name: "studentCardNumber", required: true },
{ name: "roomNumber", required: true },
{ name: "picture", required: false },
];
fields.forEach((field) => { fields.forEach((field) => {
const value = req.body[field.name]; const value = req.body[field.name];
if (field.required && !value) { if (value) newProfile.set(field.name, req.body[field.name]);
res.status(400);
throw new ValidationError(400, `Field: {${field.name}} is required!`);
}
if (value) profile.set(field.name, value);
}); });
profile.external_id = req.session!.user!.external_id; newProfile.external_id = req.session!.user!.external_id;
profile.email = String(req.session?.user?.email); newProfile.email = String(req.session?.user?.email);
profile.name = String(req.session?.user?.name); newProfile.name = String(req.session?.user?.name);
profile.save((err) => { await newProfile.save();
if (err) {
res.status(400); res.data.profile = newProfile;
} else { req.session!.user!.id = newProfile.id;
res.status(201);
res.data.profile = profile;
req.session!.user!.id = profile.id;
}
next(); next();
});
} catch (error) {
if (error instanceof ValidationError) {
const { code, message } = error;
return res.status(code).send({ message });
}
}
}; };
export default addUser; export default addUser;
...@@ -2,15 +2,16 @@ import { NextFunction, Request, Response } from "express"; ...@@ -2,15 +2,16 @@ import { NextFunction, Request, Response } from "express";
import Profile from "../../models/ProfileSchema"; import Profile from "../../models/ProfileSchema";
const deletUser = () => (req: Request, res: Response, next: NextFunction) => { /**
Profile.findByIdAndDelete(req.params.id, (error) => { * Middleware to delete User where id = req.params.id
if (error) { */
res.status(400); const deleteUser = () => async (
} else { req: Request,
res.status(204); res: Response,
} next: NextFunction
) => {
await Profile.findByIdAndDelete(req.params.id);
next(); next();
});
}; };
export default deletUser; export default deleteUser;
...@@ -4,28 +4,12 @@ import Profile, { IProfile } from "../../models/ProfileSchema"; ...@@ -4,28 +4,12 @@ import Profile, { IProfile } from "../../models/ProfileSchema";
import { IWarning } from "../../models/WarningSchema"; import { IWarning } from "../../models/WarningSchema";
import Warning 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) => { const getOwnUser = () => (req: Request, res: Response, next: NextFunction) => {
Profile.findOne( req.params.id = req.session.user!.id!;
{ 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;
}
next(); next();
}
);
}; };
export default getOwnUser; export default getOwnUser;
...@@ -4,26 +4,17 @@ import { IWarning } from "../../models/WarningSchema"; ...@@ -4,26 +4,17 @@ import { IWarning } from "../../models/WarningSchema";
import Profile from "../../models/ProfileSchema"; import Profile from "../../models/ProfileSchema";
import Warning from "../../models/WarningSchema"; import Warning from "../../models/WarningSchema";
const getUser = () => (req: Request, res: Response, next: NextFunction) => { /**
Profile.findById(req.params.id, async (error, profile) => { * Middleware to get a User by req.params.id
if (error) { * and set res.data.profile
console.warn(error); */
res.status(400); const getUser = () => async (
} else { req: Request,
res.status(200); res: Response,
next: NextFunction
let objProfile = profile?.toObject(); ) => {
if (!!objProfile) { res.data.profile = await Profile.findById(req.params.id).lean().exec();
objProfile.warnings = await Warning.find({
_id: { $in: profile?.warningIds },
}).exec();
}
delete objProfile.warningIds;
res.data.profile = objProfile;
}
next(); next();
});
}; };
export default getUser; export default getUser;
...@@ -2,20 +2,13 @@ import { NextFunction, Request, Response } from "express"; ...@@ -2,20 +2,13 @@ import { NextFunction, Request, Response } from "express";
import Profile from "../../models/ProfileSchema"; import Profile from "../../models/ProfileSchema";
const getUsersList = () => ( const getUsersList = () => async (
req: Request, req: Request,
res: Response, res: Response,
next: NextFunction next: NextFunction
) => { ) => {
Profile.find({}, (err, profiles) => { res.data.profiles = await Profile.find();
if (err) {
res.status(400);
} else {
res.status(200);
res.data.profiles = profiles;
}
next(); next();
});
}; };
export default getUsersList; export default getUsersList;
import { NextFunction, Request, Response, response } from "express"; import { NextFunction, Request, Response, response } from "express";
/**
* Return the found user from res.data.profile
*/
const responseUser = () => (req: Request, res: Response) => { const responseUser = () => (req: Request, res: Response) => {
if (!res.data.profile) { if (!res.data.profile) {
res.status(404).json({ message: "User not found!" }); res.status(404).json({ message: "User not found!" });
......
import { NextFunction, Request, Response, response } from "express"; import { NextFunction, Request, Response, response } from "express";
/**
* Return the found users from res.data.profiles
*/
const responseUserList = () => (req: Request, res: Response) => { const responseUserList = () => (req: Request, res: Response) => {
res.json(res.data.profiles); res.json(res.data.profiles);
}; };
......
...@@ -5,24 +5,26 @@ import Profile from "../../models/ProfileSchema"; ...@@ -5,24 +5,26 @@ import Profile from "../../models/ProfileSchema";
// Valid fields to update // Valid fields to update
const validFields = ["studentCardNumber", "roomNumber", "picture"]; const validFields = ["studentCardNumber", "roomNumber", "picture"];
// Update user /**
const updateUser = () => (req: Request, res: Response, next: NextFunction) => { * Update a user
Profile.findOne({ _id: req.params.id }, (error, profile) => { */
res.status(200); const updateUser = () => async (
if (error) { req: Request,
res.status(400); res: Response,
} else { next: NextFunction
) => {
const profile = await Profile.findById(req.params.id).exec();
if (profile) { if (profile) {
validFields.forEach((field) => { validFields.forEach((field) => {
const value = req.body[field]; const value = req.body[field];
if (value) profile.set(field, value); if (value) profile.set(field, value);
}); });
profile.save(); profile.save();
res.data.profile = profile;
}
} }
res.data.profile = profile;
next(); next();
});
}; };
export default updateUser; export default updateUser;
...@@ -18,7 +18,6 @@ export interface IProfile extends Document { ...@@ -18,7 +18,6 @@ export interface IProfile extends Document {
email: string; email: string;
name: string; name: string;
warningIds: string[] | []; warningIds: string[] | [];
warnings: IWarning[] | [];
} }
const ProfileSchema = new Schema({ 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