index.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import mongoose from "mongoose";
  2. import {
  3. User
  4. } from "../../../models/User";
  5. import redis from "../../../config/redis";
  6. import {
  7. SmsOTPResult,
  8. SmsOTPInput
  9. } from "./types";
  10. const smsOTP = async (input: SmsOTPInput): Promise<SmsOTPResult> => {
  11. try {
  12. const {
  13. userID,
  14. code
  15. } = input;
  16. if (!mongoose.Types.ObjectId.isValid(userID)) {
  17. return {
  18. message: "user-not-found",
  19. code: 404
  20. };
  21. }
  22. const user = await User.findById(userID);
  23. if (!user) {
  24. return {
  25. message: "user-not-found",
  26. code: 404
  27. };
  28. }
  29. const cachedCode = await redis.get(`sms-verify-${userID}`);
  30. if (!cachedCode) {
  31. return {
  32. message: "exceeded-time-limit-for-request",
  33. code: 400
  34. };
  35. }
  36. if (cachedCode !== code) {
  37. return {
  38. message: "invalid-code",
  39. code: 400
  40. };
  41. }
  42. await User.findByIdAndUpdate(userID, {
  43. isPhoneVerified: true
  44. });
  45. await redis.del(`sms-verify-${userID}`);
  46. return {
  47. message: "your-request-has-been-received-we-will-contact-you-shortly",
  48. code: 200
  49. };
  50. } catch (error) {
  51. console.error("smsOTP error:", error);
  52. return {
  53. message: "internal-server-error",
  54. code: 500
  55. };
  56. }
  57. };
  58. export default smsOTP;