79 lines
2.0 KiB
JavaScript
79 lines
2.0 KiB
JavaScript
const User = require('../models/User');
|
|
|
|
exports.createUser = async (req, res) => {
|
|
try {
|
|
const { name, phone } = req.body;
|
|
|
|
if (!name || !phone) {
|
|
return res.status(400).json({ success: false, message: 'Name and phone are required' });
|
|
}
|
|
|
|
// Generate a random 4 digit OTP
|
|
const generatedOtp = Math.floor(1000 + Math.random() * 9000).toString();
|
|
const otpExpiry = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes from now
|
|
|
|
let user = await User.findOne({ phone });
|
|
let isExisting = false;
|
|
|
|
if (user) {
|
|
isExisting = true;
|
|
user.otp = generatedOtp;
|
|
user.otpExpiry = otpExpiry;
|
|
user.name = name; // Update name just in case
|
|
await user.save();
|
|
} else {
|
|
user = await User.create({
|
|
name,
|
|
phone,
|
|
otp: generatedOtp,
|
|
otpExpiry
|
|
});
|
|
}
|
|
|
|
res.json({
|
|
success: true,
|
|
user: {
|
|
otp: user.otp,
|
|
isExisting
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.error('Error creating user:', error);
|
|
res.status(500).json({ success: false, message: 'Server error' });
|
|
}
|
|
};
|
|
|
|
exports.verifyOtp = async (req, res) => {
|
|
try {
|
|
const { phone, otp } = req.body;
|
|
|
|
if (!phone || !otp) {
|
|
return res.status(400).json({ success: false, message: 'Phone and OTP required' });
|
|
}
|
|
|
|
const user = await User.findOne({ phone });
|
|
|
|
if (!user) {
|
|
return res.status(404).json({ success: false, message: 'User not found' });
|
|
}
|
|
|
|
if (user.otp !== otp) {
|
|
return res.status(400).json({ success: false, message: 'Invalid OTP' });
|
|
}
|
|
|
|
if (user.otpExpiry < new Date()) {
|
|
return res.status(400).json({ success: false, message: 'OTP expired' });
|
|
}
|
|
|
|
// Clear OTP after successful verification
|
|
user.otp = null;
|
|
user.otpExpiry = null;
|
|
await user.save();
|
|
|
|
res.json({ success: true, message: 'OTP verified successfully' });
|
|
} catch (error) {
|
|
console.error('Error verifying OTP:', error);
|
|
res.status(500).json({ success: false, message: 'Server error' });
|
|
}
|
|
};
|