Skip to content

Commit

Permalink
chore: hashing, models (#20)
Browse files Browse the repository at this point in the history
* fix: user model (#18)

* fix: user Model add is_verified

* fix: error message

* fix: verifyController

* chore: bcrypt hashing (#19)

* chore: init constants

* chore: hash password

* chore: userController :hash check login

* fix: vendorController
  • Loading branch information
tusharbansal22 authored Apr 8, 2024
1 parent 9c35896 commit 14df1a9
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 46 deletions.
1 change: 1 addition & 0 deletions constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exports.kSaltRounds = 10;
31 changes: 16 additions & 15 deletions controllers/userAuth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const User = require("../models/user.model");
const UserCredentials = require("../models/user.credentials");
const OTP = require("../models/otp.model");
const nodemailer = require("nodemailer");
const bcrypt = require("bcrypt");
const {kSaltRounds} = require("../constants");

const transporter = nodemailer.createTransport({
port: 465,
Expand All @@ -21,6 +23,7 @@ const {
ACCESS_DENIED_ERR,
EMAIL_NOT_FOUND_ERR,
OTP_EXPIRED_ERR,
USER_NOT_VERIFIED,
} = require("../errors");

const { createJwtToken } = require("../utils/token.util");
Expand All @@ -31,6 +34,7 @@ exports.verifyOtp = async (req, res, next) => {
const currentDateTime = new Date();

const user = await User.findOne({ email });
const userCredentials = await UserCredentials.findOne({ email });
if (!user) {
next({ status: 400, message: USER_NOT_FOUND_ERR });
console.log("user not found");
Expand All @@ -47,10 +51,13 @@ exports.verifyOtp = async (req, res, next) => {
}
if (otp.expiresAt < currentDateTime) {
next({ status: 400, message: OTP_EXPIRED_ERR });
await user.deleteOne();
await userCredentials.deleteOne();
return;
}

const token = createJwtToken({ userId: user._id });
await userCredentials.updateOne({ is_verified: true });

res.status(201).json({
type: "success",
Expand Down Expand Up @@ -88,10 +95,12 @@ exports.createNewUser = async (req, res, next) => {
// save user
const user = await createUser.save();

const hashedPassword = await bcrypt.hash(password,kSaltRounds);

const createUserCredentials = new UserCredentials({
user_id: user._id,
email,
password,
password: hashedPassword,
});

createUserCredentials.save();
Expand All @@ -104,18 +113,6 @@ exports.createNewUser = async (req, res, next) => {
entityModel: "User",
});

// await new Promise((resolve, reject) => {
// // verify connection configuration
// transporter.verify(function (error, success) {
// if (error) {
// console.log(error);
// reject(error);
// } else {
// console.log("Server is ready to take our messages");
// resolve(success);
// }
// });
// });

let mailData = {
from: {
Expand All @@ -127,7 +124,7 @@ exports.createNewUser = async (req, res, next) => {
text: `Your Otp is - ${otp}`,
};

await new Promise((resolve, reject) => {
new Promise((resolve, reject) => {
// send mail
transporter.sendMail(mailData, (err, info) => {
if (err) {
Expand Down Expand Up @@ -160,7 +157,11 @@ exports.login = async (req, res, next) => {
return;
}

const passwordMatch = password === user.password ? 1 : 0;
if(!user.is_verified){
next({ status: 401, message: USER_NOT_VERIFIED });
}

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

if (passwordMatch) {
const token = createJwtToken({ userId: user.user_id });
Expand Down
63 changes: 33 additions & 30 deletions controllers/vendorAuth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const OTP = require("../models/otp.model");

const nodemailer = require("nodemailer");
const bcrypt = require("bcrypt");
const {kSaltRounds} = require('../constants')

const {
USER_NOT_FOUND_ERR,
Expand All @@ -22,7 +23,7 @@ let mailTransporter = nodemailer.createTransport({
pass: "mxzc acbf revb xcxh",
});

// --------------------- create new user ---------------------------------
// --------------------- create new Vendor ---------------------------------

exports.createNewVendor = async (req, res, next) => {
try {
Expand All @@ -42,14 +43,16 @@ exports.createNewVendor = async (req, res, next) => {

console.log(description);

// let images = [image_url];


const emailExist = await Vendor.findOne({ email });
if (emailExist) {
next({ status: 400, message: EMAIL_ALREADY_EXISTS_ERR });
return;
}

const hashedPassword = await bcrypt.hash(password, kSaltRounds);

const createVendor = new Vendor({
ownerName,
email,
Expand All @@ -66,7 +69,7 @@ exports.createNewVendor = async (req, res, next) => {

const createVendorCredentials = new VendorCredentials({
email,
password,
password: hashedPassword,
vendor_id: vendor._id,
});
await createVendorCredentials.save();
Expand All @@ -77,32 +80,32 @@ exports.createNewVendor = async (req, res, next) => {
});
await menu.save();

const otp = Math.floor(1000 + Math.random() * 9000);
const sentOtp = new OTP({
code: otp,
expiresAt: new Date(new Date().getTime() + 2 * 60 * 1000),
entity: vendor._id,
entityModel: "Vendor",
});
await sentOtp.save();

let mailDetails = {
from: "[email protected]",
to: email,
subject: "Test mail",
text: `Your OTP is: ${otp}`,
};

mailTransporter.sendMail(mailDetails, function (err, data) {
if (err) {
console.log("Error Occurs");
console.log(err);
} else {
console.log("Email sent successfully");
}
});

res.status(200).json("OTP send successfully");
// const otp = Math.floor(1000 + Math.random() * 9000);
// const sentOtp = new OTP({
// code: otp,
// expiresAt: new Date(new Date().getTime() + 2 * 60 * 1000),
// entity: vendor._id,
// entityModel: "Vendor",
// });
// await sentOtp.save();

// let mailDetails = {
// from: "[email protected]",
// to: email,
// subject: "Test mail",
// text: `Your OTP is: ${otp}`,
// };c

// mailTransporter.sendMail(mailDetails, function (err, data) {
// if (err) {
// console.log("Error Occurs");
// console.log(err);
// } else {
// console.log("Email sent successfully");
// }
// });

res.status(200).json("Register successfully");
} catch (error) {
next(error);
}
Expand All @@ -120,7 +123,7 @@ exports.vendorLogin = async (req, res, next) => {
return;
}

const passwordMatch = vendor.password === password;
const passwordMatch = await bcrypt.compare(password, vendor.password);
if (passwordMatch) {
// Generate JWT token
const token = createJwtToken({ userId: vendor.vendor_id });
Expand Down
4 changes: 3 additions & 1 deletion errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ exports.JWT_DECODE_ERR = "incorrect token";

exports.USER_NOT_FOUND_ERR = "User not found";

exports.USER_NOT_VERIFIED = 'Please complete email verification'

exports.ACCESS_DENIED_ERR = "Access deny for normal user";

exports.Email_NOT_FOUND_ERR = "email not found";
Expand All @@ -23,6 +25,6 @@ exports.INCORRECT_CRED_ERR =
exports.EMAIL_NOT_FOUND_ERR = "Email not found";

exports.ADMIN_NOT_FOUND = "Admin not found";
exports.OTP_EXPIRED_ERR = "OTP has expired";
exports.OTP_EXPIRED_ERR = "OTP has expired. Re-Register to continue";

exports.VENDOR_NOT_PERMITTED = "Vendor is not verified or has been debarred"
4 changes: 4 additions & 0 deletions models/user.credentials.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ const userCredentialsSchema = new Schema({
type: String,
required: true,
},
is_verified: {
type: Boolean,
default: false,
}
});

module.exports = model("UserCredentials", userCredentialsSchema);

0 comments on commit 14df1a9

Please sign in to comment.