Skip to content

Commit

Permalink
FIX: getting password & changes on voting system
Browse files Browse the repository at this point in the history
  • Loading branch information
pratik9333 committed Jun 8, 2022
1 parent be57b86 commit 1e1199b
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 47 deletions.
5 changes: 4 additions & 1 deletion api/vote.api.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
const router = require("express").Router();

const { rateUser } = require("../controllers/vote.controller");
const { rateUser, getRatedLogs } = require("../controllers/vote.controller");

const isLoggedIn = require("../middlewares/authenticate.middleware");

//rate friend
router.route("/user/:action/:userId").post(isLoggedIn, rateUser);

// get rated logs
router.route("/").get(isLoggedIn, getRatedLogs);

module.exports = router;
8 changes: 4 additions & 4 deletions controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const User = require("../models/User.model");
const getCookieToken = require("../utils/cookieToken");
const cloudinary = require("cloudinary");
const bcrypt = require("bcryptjs");

exports.signup = async (req, res) => {
const {
Expand Down Expand Up @@ -84,16 +85,15 @@ exports.login = async (req, res) => {
}

try {
const user = await User.findOne({ email });
const user = await User.findOne({ email }).select("+password");

if (!user) {
return res.status(401).json({ error: "email is incorrect" });
}

const validatePassword = await user.validatePassword(password);
const result = bcrypt.compare(password, user.password);

//validating email and password
if (!validatePassword) {
if (!result) {
return res.status(401).json({ error: "password is incorrect" });
}

Expand Down
86 changes: 51 additions & 35 deletions controllers/vote.controller.js
Original file line number Diff line number Diff line change
@@ -1,63 +1,79 @@
const Query = require("../utils/query");
const User = require("../models/User.model");
const Votes = require("../models/Votes.model");

// 1 min = 60,000 milliseconds
const oneMinToMilli = 60_000;

const updateExpiryTimeForRating = 2 * oneMinToMilli;

exports.rateUser = async (req, res) => {
try {
const { userId, action } = req.params;
let flag = 0;
let { userId, action } = req.params;

action = parseInt(action);

if (!userId) {
return res.status(400).json({ error: "Please provide user id" });
if (!userId || !action) {
return res
.status(400)
.json({ error: "Please provide userId and vote(-1 or 1) in params" });
}

let user = await User.findById(userId);
const Vote = await Votes.findOne({ user: userId, voter: req.user._id });
const user = await User.findById(userId);
const currTime = new Date().getTime();

for (let ratingUser of user.ratedBy) {
if (ratingUser.user.toString() === req.user._id.toString()) {
if (currTime <= ratingUser.expiryTime) {
return res
.status(400)
.json({ error: "You have already rated this user" });
}
if (currTime >= ratingUser.expiryTime) {
flag = 1;
ratingUser.expiryTime =
new Date().getTime() + updateExpiryTimeForRating;
}
}
}

if (flag === 0) {
user.ratedBy.push({
user: req.user._id,
expiryTime: new Date().getTime() + updateExpiryTimeForRating,
if (Vote && currTime <= Vote.expiryTime) {
return res.status(400).json({
error: `you already had rated ${user.name}, you can revote after sometime`,
});
}

if (action === "upvote") {
user.upvotes += 1;
if (action) user.upvotes += 1;
else user.downvotes -= 1;
user.rating = (user.upvotes / (user.upvotes + user.downvotes || 1)) * 100;
user.votes.push(req.user._id);

if (!Vote) {
await Votes.create({
user: userId,
voter: req.user._id,
status: action,
expiryTime: currTime + updateExpiryTimeForRating,
});
} else {
user.downvotes += 1;
}
Vote.expiryTime = currTime + updateExpiryTimeForRating;
Vote.status = action;

user.votes += 1;
user.rating = (user.upvotes / (user.upvotes + user.downvotes || 1)) * 100;
await Vote.save();
}

await user.save();

res
.status(200)
.json({ success: true, message: `${user.name} was rated successfully` });
res.status(200).json({
success: true,
message: `${user.name} was rated successfully`,
});
} catch (error) {
console.log(error);
res
.status(500)
.json({ error: "Server has occured some problem, please try again" });
}
};

exports.getRatedLogs = async (req, res) => {
try {
const currTime = new Date().getTime();

const ratingUsers = await Votes.find({
user: req.user._id,
}).populate("voter", "name rating");

res.status(200).json({
success: true,
ratingUsers,
});
} catch (error) {
console.log(error);
res.status(500).json({ error: "Cannot able to fetch users" });
}
};
9 changes: 3 additions & 6 deletions models/User.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ const userSchema = new mongoose.Schema(
languagesUsed: [],
},
},
rating: { type: Number, default: 0 },
rating: { type: Number, default: 100 },
upvotes: { type: Number, default: 0 },
downvotes: { type: Number, default: 0 },
votes: [{ type: mongoose.Schema.ObjectId, ref: "Vote" }],
friends: [{ type: mongoose.Schema.ObjectId, ref: "Friend" }],
nextUpdateCycle: { type: Number, required: true },
Expand All @@ -79,11 +81,6 @@ userSchema.pre("save", async function (next) {
this.password = await bcrypt.hash(this.password, 10);
});

//validate the password with password user sending
userSchema.methods.validatePassword = async function (userPassword) {
return await bcrypt.compare(userPassword, this.password); // doubt in this
};

//create and return JWT token
userSchema.methods.getJwtToken = function () {
return jsonwebtoken.sign({ id: this._id }, process.env.JWT_SECRET, {
Expand Down
1 change: 0 additions & 1 deletion models/Votes.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ const votingSchema = new mongoose.Schema(
1, //Upvote
-1, //Downvote
],
default: 0,
},
expiryTime: { type: Number },
},
Expand Down

1 comment on commit 1e1199b

@vercel
Copy link

@vercel vercel bot commented on 1e1199b Jun 8, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.