All files / src/middleware validateUser.ts

100% Statements 7/7
100% Branches 4/4
100% Functions 1/1
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25                        7x 8x 8x   8x 2x 2x     6x      
// nextstep-backend/src/middleware/validateUser.ts
import { Response, NextFunction } from 'express';
import {CustomRequest} from "types/customRequest";
import {unless} from "express-unless";
 
/**
 * Middleware to validate user, to perform action only on his account
 * We will be able to use it, to bypass it in the future for the admin role, if we'll have one
 * @param req
 * @param res
 * @param next
 */
const validateUser: any & { unless: typeof unless } = (req: CustomRequest, res: Response, next: NextFunction): void => {
    const authenticatedUserId = req.user.id;
    const userIdInParams = req.params.id;
 
    if (userIdInParams && authenticatedUserId !== userIdInParams) {
        res.status(403).json({ message: 'Forbidden: You can only perform this action on your own account' });
        return;
    }
 
    next();
};
 
export default validateUser;