Home > Net >  Check user that can view my files in my server
Check user that can view my files in my server

Time:05-25

I want to secure my files and not anyone can view my files in express, I want to check who has logged in into my website and then authenticate if he has access to view this file or not , how can I achieve that this is the code I am using to access my files url :

app.use("/profile", express.static(__dirname   '/profile'));

I want only the user that logged in, he is the only one that can view his profile image and if he is not the user then say for example you are not allowed to view this file.

I am using mongodb as a backend but i don't know if its mongodb authentication or express middleware security ?

CodePudding user response:

I Discovered how to solve this :

const checkImg = async (req, res, next) => {
const token = req.cookies.jwt;
if (token) {
    jwt.verify(
        token,
        process.env.JWTKEY,
        async (err, decodedToken) => {
            if (err) {
                res.json({ status: false });
            } else {
                const user = await UserModal.findById(decodedToken.id);
                const imgUrl = req.originalUrl.split('/')[2];
                const imgUser = user.profileImg;
                if (imgUrl === imgUser || user.admin === "ADMIN") {
                    next();
                }
                else {
                    return res.send("Your are not allowed to view this file")
                }
            }
        }
    );
}else{
return res.send("you are not allowed !")
}

}

and here is when i use my middleware :

app.use("/images", checkImg , express.static(__dirname   '/images'));

this code checks if the user is the same user then he can only see the data and also the admin user can display the data , otherwise send him that he is not allowed to get the data

  • Related