Reactord
Reactord

Reputation: 106

How can i identify if user is admin or not in Express?

Good day,

i am trying to make a login system where both the client and the admin can log in. If the user is an admin then he/she will be redirected to the admin panel if not then the user will be redirected to the home page of the webshop. I am struggling a little with the logic for authentication. I am trying to identify wether the user is logged in. if the/she is then i authenticate the user role by checking if 'isAdmin' is true or false. I do this by finding the user in the database by looking for the isAdmin state. I am using jwt tokens to get the state of the user.

Authentication:

const { verify } = require("jsonwebtoken");
const userModel = require("../model/userModel");

// const isAuth = req => {
//  const authorization = req.headers["authorization"];
//  if (!authorization) throw new Error("You need to login");
//  const token = authorization.split(" ")[1];
//  const { userId } = verify(token, process.env.ACCESS_TOKEN_SECRET);
//  return userId;
// };

const isAuth = (req, res, next) => {
    const token = req.header("auth-token");
    if (!token) return res.status(401).send("Access denied");
    //verifying the token then  sending the id back of the user
    try {
        const verified = verify(token, process.env.SECRET);
        req.user = verified;
        next();
    } catch (err) {
        res.status(400).send("Invalid");
    }
};

//isAdmin
const isAdmin = async (req, res, next) => {
    const token = req.header("auth-token");
    if (!token) return res.status(401).send("No User");
    try {
        const verified = verify(token, process.env.SECRET);
        req.user = verified;
        let user = await userModel.findOne({ isAdmin });
        if (req.user && user.isAdmin === true) {
            return next();
        }
    } catch (err) {
        return res.status(401).send({ msg: "Admin token is not valid" });
    }
};

//check user
// const checkUser = (req, res, next) => {
//  //get token from cookies
//  const token = req.cookies.jwt;
//  //check if token exists
//  if (token) {
//      verify(token, process.env.SECRET, async (err, decode) => {
//          if (err) {
//              console.log(err.message);
//              next();
//              res.locals.user = null;
//          } else {
//              console.log(decode);
//              next();
//              let user = await userModel.findOne(decode.isAdmin);
//              res.local.user = user;
//              next();
//          }
//      });
//  } else {
//  }
// };

module.exports = {
    isAuth,
    isAdmin,
};

Route:

router.post("/login", async (req, res) => {
    const user = await User.findOne({ email: req.body.email });
    if (!user) res.send({ error: "User does not exists" });
    const validPass = await compare(req.body.password, user.password);
    if (!validPass) {
        return res.json({ error: "email or password is incorrect" });
    }

    
    const token = sign(
        { _id: user._id, isAdmin: user.isAdmin },
        process.env.SECRET,
        {
            expiresIn: "24h",
        },
    );
    res.header("auth-token", token).send({
        token,
        email: req.body.email,
        id: user._id,
    });

    
});


router.get("/adminPanel", isAdmin, isAuth, (req, res) => {
    res.json({
        title: "ADMIN PANEL",
    });
});

Upvotes: 1

Views: 4721

Answers (1)

Molda
Molda

Reputation: 5704

Code based on my comments bellow your question

const { verify } = require("jsonwebtoken");
const userModel = require("../model/userModel");

const isAuth = (req, res, next) => {
    const token = req.header("auth-token");
    if (!token) return res.status(401).send("Access denied");

    try {
        const verified = verify(token, process.env.SECRET);
        req.user = verified;
        console.log('Am i admin?', req.user.isAdmin);
        next();
    } catch (err) {
        res.status(400).send("Invalid token");
    }
};

const isAdmin = async (req, res, next) => {

    // no need to verify token again
    // the `req.user.isAdmin` is already available from isAuth
    // also no need to query a database, we have all the info we need from the token
    if (!req.user.isAdmin)
        return res.status(401).send({ msg: "Not an admin, sorry" });

    next();
};

router.post("/login", async (req, res) => {
    const user = findUserSomehow();
    
    const token = sign({ _id: user._id, isAdmin: user.isAdmin }, process.env.SECRET, { expiresIn: "24h" });

    res.header("auth-token", token).send({
        token,
        email: req.body.email,
        id: user._id,
    });    
});

// notice the order of middlewares, isAuth first
router.get("/adminPanel", isAuth, isAdmin, (req, res) => {
    res.json({
        title: "ADMIN PANEL",
    });
});

Upvotes: 1

Related Questions