79 lines
2.6 KiB
JavaScript
79 lines
2.6 KiB
JavaScript
import bcrypt from "bcrypt";
|
|
import jwt from "jsonwebtoken";
|
|
import { VAModel } from "../../../models/vaModel.js";
|
|
|
|
// Login VA
|
|
async function va_login_callback(req, res) {
|
|
try {
|
|
// const payload = req.body ? JSON.parse(req.body) : {};
|
|
const payload = req.body || {};
|
|
const { userDetails } = payload;
|
|
|
|
if (!userDetails || !userDetails.email || !userDetails.password) {
|
|
return res.status(400).json({ success: false, message: "Please provide email and password" });
|
|
}
|
|
|
|
// Find user by email
|
|
const user = await VAModel.findOne({ "userDetails.email": userDetails.email });
|
|
if (!user) {
|
|
return res.status(404).json({ success: false, message: "Invalid credentials" });
|
|
}
|
|
|
|
// const saltRounds = 10;
|
|
// const hashedPassword = await bcrypt.hash(userDetails.password, saltRounds);
|
|
|
|
// Compare password with stored hash
|
|
const isMatch = await bcrypt.compare(
|
|
userDetails.password,
|
|
user.userDetails.password
|
|
);
|
|
|
|
if (!isMatch) {
|
|
return res.status(401).json({ success: false, message: "Invalid password" });
|
|
}
|
|
|
|
// Generate JWT accessToken with 24h expiry
|
|
const accessToken = jwt.sign(
|
|
{
|
|
id: user._id,
|
|
email: user.userDetails.email,
|
|
name: user.userDetails.firstName,
|
|
},
|
|
process.env.JWT_SECRET_ACCESS_TOKEN || "DocTrackerSecretKey",
|
|
// { expiresIn: "24h" }
|
|
);
|
|
|
|
// Generate JWT refreshToken with 24h expiry
|
|
const refreshToken = jwt.sign(
|
|
{
|
|
id: user._id,
|
|
email: user.userDetails.email,
|
|
name: user.userDetails.firstName,
|
|
},
|
|
process.env.JWT_SECRET_REFRESH_TOKEN || "DocTrackerSecretKeyRefreshToken",
|
|
// { expiresIn: "30d" }
|
|
);
|
|
|
|
await VAModel.updateOne({ "userDetails.email": userDetails.email }, {
|
|
$set: { accessToken, refreshToken }
|
|
})
|
|
|
|
// Return accessToken and user info
|
|
return res.status(200).json({
|
|
success: true,
|
|
message: "Login Successfull",
|
|
accessToken,
|
|
refreshToken,
|
|
user: {
|
|
id: user._id,
|
|
name: user.userDetails.firstName,
|
|
email: user.userDetails.email,
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error("va_register error:", error);
|
|
return res.status(500).json({ success: false, message: "Internal Server Error" });
|
|
}
|
|
}
|
|
|
|
export { va_login_callback }; |