GIF89a php
Current File : /home/viralhoga/glambooth_viralhoga_com/src/controllers/auth.controller.js
import { ApiResponse } from "../utils/ApiResponse.js";
import { Otp, User } from "../models/user.model.js";


export const generateOtp = async (req, res) => {

    const { mobile } = req.body;

    if (!mobile) {
        return res.json(new ApiResponse(400, {}, "Mobile number is required"));
    }

    if (mobile.length !== 10) {
        return res.json(new ApiResponse(400, {}, "Invalid mobile number"));
    }

    let otp = Math.floor(1000 + Math.random() * 9000);
    const expiryAt = new Date(Date.now() + 5 * 60000); // OTP expires in 5 minutes

    if (mobile === "1234567890") {
        otp = 1234;
    }
    const otpDetails = await Otp.findOne({ mobile });

    if (otpDetails) {
        await Otp.updateOne({ mobile }, { otp, expiryAt });
    } else {
        await Otp.create({ mobile, otp, expiryAt });
    }

    return res.json(new ApiResponse(200, { otp }, "OTP sent successfully"));

}


export const verifyOtp = async (req, res) => {

    const { mobile, otp } = req.body;

    const otpDetails = await Otp.findOne({ mobile });

    if (!otpDetails) {
        return res.status(400).json(new ApiResponse(400, {}, "Invalid OTP"));
    }
    if (otpDetails.otp !== otp) {
        return res.status(400).json(new ApiResponse(400, {}, "Invalid OTP"));
    }

    if (otpDetails.expiryAt < new Date()) {
        return res.status(400).json(new ApiResponse(400, {}, "OTP expired"));
    }


    await Otp.deleteOne({ mobile });

    const user = await User.findOne({ mobile });

    if (user) {
        return res.json(new ApiResponse(200, {
            user,
            isRegistered: true
        }, "OTP verified successfully"));
    }

    return res.json(new ApiResponse(200, { user:null,isRegistered: false }, "OTP verified successfully"));
}


export const checkUser = async (req, res) => {
    const { mobile } = req.body;

    try {
        const user = await User.findOne({ mobile: mobile });

        console.log(user);

        if (user) {
            return res.json(new ApiResponse(200, {
                user,
                isRegistered: true
            }, "User found"));
        }
        return res.json(new ApiResponse(200, { isRegistered: false }, "User not found"));
    } catch (err) {
        console.log(err);
        return res.status(500).json(new ApiResponse(500, {}, "Something went wrong"));
    }
}