How to read registered users list from mean stack server

98 views Asked by At

I would like to be able to read the registered users list from the Mean Stack Mongo DB server and display it on my Web App.

So far, I've only been able to access this list, which is encrypted, through the terminal by running the Mongo shell.

Any ideas? This is the code piece where "getUsers" should be implemented, but my "getUsers" attempts have not been successful so far.

const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");

const User = require("../models/user");

exports.createUser = (req, res, next) => {
  bcrypt.hash(req.body.password, 10).then(hash => {
    const user = new User({
      email: req.body.email,
      password: hash
    });
    if(req.body.adminCode === "secretCode123") {
      newUser.isAdmin === true;
    }
    user
      .save()
      .then(result => {
        res.status(201).json({
          message: "User created!",
          result: result
        });
      })
      .catch(err => {
        res.status(500).json({
          message: "Invalid authentication credentials!"
        });
      });
  });
};

// Here we create the token
exports.userLogin = (req, res, next) => {
  let fetchedUser; // Otherwise user would only exist in the first then block
  User.findOne({ email: req.body.email })
    .then(user => {
      if (!user) {
        return res.status(401).json({
          message: "Authentication failed"
        });
      }
      fetchedUser = user;
      console.log("The fetched user is " + fetchedUser);
      console.log("The user is " + user);
      console.log("The encrypted req.body.password is " + req.body.password);
      console.log("The user.password is " + user.password);
      return bcrypt.compare(req.body.password, user.password);
    })
    .then(result => {
      console.log("The result is " + result); // It is either false or true
      if (!result) {
        return res.status(401).json({
          message: "Authentication failed" // "Return" prevents execution of next part of code
        });
      }
      const token = jwt.sign(
        { email: fetchedUser.email, userId: fetchedUser._id },
        process.env.JWT_KEY,
        { expiresIn: "1h" }
      );
      res.status(200).json({
        token: token, // No need to return because no code afterwards
        expiresIn: 3600,
        userId: fetchedUser._id
      });
      console.log("The token is " + token)
    })
    .catch(err => {
      return res.status(401).json({
        message: "invalid authentication credentials!"
      });
    });
};

/* exports.getUsers = (req, res, next) => {
  const listofUsers = [
    { id: 12, email: "[email protected]" },
    { id: 13, email: "[email protected]" },
    { id: 14, email: "[email protected]" },
    { id: 15, email: "[email protected]" },
    { id: 16, email: "[email protected]" },
    { id: 17, email: "[email protected]" },
    { id: 19, email: "[email protected]" },
    { id: 20, email: "[email protected]" }
  ];
  res.status(200).json({
    message: "Dummy User ID fetched from the server",
    admin: listofUsers
  })
} */


exports.getUsers = (req, res, next) => {
  const userQuery = User.find();
  let fetchedUsers;
  userQuery
    .then(userDocuments => {
      const token = jwt.sign(
        { email: fetchedUser.email, userId: fetchedUser._id },
        process.env.JWT_KEY,
        { expiresIn: "1h" }
      );
      res.status(200).json({
        token: token, // No need to return because no code afterwards
        expiresIn: 3600,
        userId: fetchedUser._id
      });
      console.log("The token is " + token)
      fetchedUsers = userDocuments;
      console.log("The fetchedUsers are: "+ fetchedUsers);
      return User.count();
    })
    .then(count => {
      res.status(200).json({
        message: "Users fetched successfully!",
        users: fetchedUsers,
        maxUsers: count
      });
      console.log(fetchedUsers);
    })
    .catch(error => {
      res.status(500).json({
        message: "Fetching users failed!"
      });
    });
}

Thanks GB

0

There are 0 answers