changed model

This commit is contained in:
unknown 2025-12-31 15:17:18 +05:30
parent e5bca1f2e9
commit 2d712682cf
3 changed files with 142 additions and 189 deletions

View File

@ -1051,157 +1051,156 @@ exports.forgotPasswordVerifyOTP = async (req, res) => {
};
exports.requestOTPForLogin = async (req, res) => {
try {
const { registered_email } = req.body;
// try {
// const { registered_email } = req.body;
if (!registered_email) {
return res.status(400).json({
status: "failed",
message: "Email is required",
});
}
// if (!registered_email) {
// return res.status(400).json({
// status: "failed",
// message: "Email is required",
// });
// }
// Check which model contains the user
let loggingUser = await EstablishmentUser.findOne({
where: { email: registered_email }
});
let userModel = EstablishmentUser;
// // Check which model contains the user
// let loggingUser = await EstablishmentUser.findOne({
// where: { email: registered_email }
// });
// let userModel = EstablishmentUser;
if (!loggingUser) {
loggingUser = await User.findOne({
where: { email: registered_email, is_active: true }
});
userModel = User;
}
// if (!loggingUser) {
// loggingUser = await User.findOne({
// where: { email: registered_email, is_active: true }
// });
// userModel = User;
// }
if (!loggingUser) {
logger.warn(`OTP requested for non-existing email: ${sanitizeForLog(registered_email)}`);
return res.status(404).json({
status: "failed",
message: "Invalid login request. Please check your email or register to continue.",
});
}
// if (!loggingUser) {
// logger.warn(`OTP requested for non-existing email: ${sanitizeForLog(registered_email)}`);
// return res.status(404).json({
// status: "failed",
// message: "Invalid login request. Please check your email or register to continue.",
// });
// }
// Secure OTP generation
const otp = crypto.randomInt(100000, 999999).toString();
// // Secure OTP generation
// const otp = crypto.randomInt(100000, 999999).toString();
// Hash OTP before storing
const hashedOtp = await bcrypt.hash(otp, 10);
// // Hash OTP before storing
// const hashedOtp = await bcrypt.hash(otp, 10);
// Store OTP in the correct model with WHERE clause
await userModel.update(
{
login_otp: hashedOtp,
login_otp_expires_at: new Date(Date.now() + 10 * 60 * 1000),
},
{
where: { email: registered_email }
}
);
const placeHolderData = {
username: loggingUser.name,
verfication_code: otp,
support_email: process.env.SUPPORT_EMAIL,
support_phone: process.env.SUPPORT_PHONE
};
// // Store OTP in the correct model with WHERE clause
// await userModel.update(
// {
// login_otp: hashedOtp,
// login_otp_expires_at: new Date(Date.now() + 10 * 60 * 1000),
// },
// {
// where: { email: registered_email }
// }
// );
// const placeHolderData = {
// username: loggingUser.name,
// verfication_code: otp,
// support_email: process.env.SUPPORT_EMAIL,
// support_phone: process.env.SUPPORT_PHONE
// };
await sendEmailService(registered_email, "sign_in_verification_code", placeHolderData);
// await sendEmailService(registered_email, "sign_in_verification_code", placeHolderData);
logger.info(`Login OTP email triggered for: ${sanitizeForLog(registered_email)}`);
// logger.info(`Login OTP email triggered for: ${sanitizeForLog(registered_email)}`);
return res.status(200).json({
status: "success",
message: "OTP sent successfully to your registered email",
});
// return res.status(200).json({
// status: "success",
// message: "OTP sent successfully to your registered email",
// });
} catch (err) {
logger.error(`OTP request failed: ${err.message}`);
logger.error(err.stack);
// } catch (err) {
// logger.error(`OTP request failed: ${err.message}`);
// logger.error(err.stack);
return res.status(500).json({
status: "failed",
message: "Internal Server Error",
});
}
// return res.status(500).json({
// status: "failed",
// message: "Internal Server Error",
// });
// }
};
exports.verifyOTPForLogin = async (req, res) => {
try {
const { registered_email, otp } = req.body;
// try {
// const { registered_email, otp } = req.body;
// if (!registered_email || !otp) {
// return res.status(400).json({
// status: "failed",
// message: "Email and OTP are required"
// });
// }
// Validation
if (!registered_email || !otp) {
return res.status(400).json({
status: "failed",
message: "Email and OTP are required"
});
}
// // Find user from either model
// let user = await EstablishmentUser.scope("withSensitive").findOne({
// where: { email: registered_email }
// });
// Find user from either model
let user = await EstablishmentUser.scope("withSensitive").findOne({
where: { email: registered_email }
});
// if (!user) {
// user = await User.scope("withSensitive").findOne({
// where: { email: registered_email, is_active: true }
// });
// }
if (!user) {
user = await User.scope("withSensitive").findOne({
where: { email: registered_email, is_active: true }
});
}
// // User validation
// if (!user) {
// return res.status(404).json({
// status: "failed",
// message: "User not found"
// });
// }
// User validation
if (!user) {
return res.status(404).json({
status: "failed",
message: "User not found"
});
}
// if (!user.login_otp) {
// return res.status(404).json({
// status: "failed",
// message: "Verification code not found or invalid user"
// });
// }
if (!user.login_otp) {
return res.status(404).json({
status: "failed",
message: "Verification code not found or invalid user"
});
}
// // Check OTP expiry
// if (new Date() > new Date(user.login_otp_expires_at)) {
// return res.status(400).json({
// status: "failed",
// message: "Verification code has expired. Please request a new one"
// });
// }
// Check OTP expiry
if (new Date() > new Date(user.login_otp_expires_at)) {
return res.status(400).json({
status: "failed",
message: "Verification code has expired. Please request a new one"
});
}
// // Verify OTP
// const isOtpValid = await bcrypt.compare(otp, user.login_otp);
// if (!isOtpValid) {
// return res.status(400).json({
// status: "failed",
// message: "Invalid verification code"
// });
// }
// Verify OTP
const isOtpValid = await bcrypt.compare(otp, user.login_otp);
if (!isOtpValid) {
return res.status(400).json({
status: "failed",
message: "Invalid verification code"
});
}
// // Clear OTP after successful verification
// await user.update({
// login_otp: null,
// login_otp_expires_at: null,
// });
// Clear OTP after successful verification
await user.update({
login_otp: null,
login_otp_expires_at: null,
});
// const safeEmail = sanitizeForLog(registered_email);
// logger.info(`OTP verification successful for user: ${safeEmail}`);
const safeEmail = sanitizeForLog(registered_email);
logger.info(`OTP verification successful for user: ${safeEmail}`);
// return res.status(200).json({
// status: "success",
// message: "Email verified successfully!",
// });
return res.status(200).json({
status: "success",
message: "Email verified successfully!",
});
} catch (err) {
logger.error(`OTP verification error: ${err.message}`);
logger.error(`Stack trace: ${err.stack}`);
return res.status(500).json({
status: "failed",
message: "Internal server error"
});
}
// } catch (err) {
// logger.error(`OTP verification error: ${err.message}`);
// logger.error(`Stack trace: ${err.stack}`);
// return res.status(500).json({
// status: "failed",
// message: "Internal server error"
// });
// }
};
const GENERIC_ERROR_MSG =

View File

@ -74,64 +74,41 @@ module.exports = (sequelize, DataTypes) => {
allowNull: true,
},
},
{
login_otp: {
type: DataTypes.STRING,
allowNull: true,
},
login_otp_expires_at: {
type: DataTypes.DATE,
allowNull: true,
},
},
{
// ============================================================
// Model Options
// ============================================================
timestamps: false,
tableName: "establishment_users",
// Hide sensitive fields by default
// 1. Hide sensitive fields by default
defaultScope: {
attributes: {
exclude: [
"password",
"reset_otp",
"reset_otp_expires_at",
"login_otp",
"login_otp_expires_at",
],
exclude: ["password", "reset_otp", "reset_otp_expires_at"],
},
},
// Scope for login & sensitive operations
// 2. Scope for login / sensitive queries
scopes: {
withSensitive: {
attributes: {
include: [
"password",
"reset_otp",
"reset_otp_expires_at",
"login_otp",
"login_otp_expires_at",
],
include: ["password", "reset_otp", "reset_otp_expires_at"],
},
},
},
}
);
// 3. Remove sensitive fields from all API responses
EstablishmentUser.prototype.toJSON = function () {
const values = { ...this.get() };
delete values.password;
delete values.reset_otp;
delete values.reset_otp_expires_at;
delete values.login_otp;
delete values.login_otp_expires_at;
return values;
};
// ====================================================
// Associations
// ====================================================
// Relationships
EstablishmentUser.associate = (models) => {
EstablishmentUser.belongsTo(models.Establishment, {
foreignKey: "establishment_id",
@ -140,4 +117,4 @@ module.exports = (sequelize, DataTypes) => {
};
return EstablishmentUser;
};
};

View File

@ -32,32 +32,15 @@ module.exports = (sequelize, DataTypes) => {
type: DataTypes.DATE,
allowNull: true,
},
login_otp: {
type: DataTypes.STRING,
allowNull: true,
},
login_otp_expires_at: {
type: DataTypes.DATE,
allowNull: true,
},
is_active: {
type: DataTypes.BOOLEAN,
defaultValue: true,
},
},
{
defaultScope: {
attributes: {
exclude: [
"password",
"reset_otp",
"reset_otp_expires_at",
"login_otp",
"login_otp_expires_at",
],
},
// 1. EXCLUDE sensitive fields from all queries
defaultScope: {
attributes: { exclude: ["password", "reset_otp", "reset_otp_expires_at"] },
},
// -------------------------------------------------------------
@ -67,18 +50,12 @@ module.exports = (sequelize, DataTypes) => {
scopes: {
withSensitive: {
attributes: {
include: [
"password",
"reset_otp",
"reset_otp_expires_at",
"login_otp",
"login_otp_expires_at",
],
include: ["password", "reset_otp", "reset_otp_expires_at"],
},
},
},
}
);
return User;
};
return User;
};