CoolFace
Apppublic

sakthivikram/geo-location

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
OtpService.java77 linesDownload Raw Back to service
1package com.georeport.service;2 3import org.slf4j.Logger;4import org.slf4j.LoggerFactory;5import org.springframework.beans.factory.annotation.Autowired;6import org.springframework.stereotype.Service;7 8import java.time.LocalDateTime;9import java.util.Map;10import java.util.Random;11import java.util.concurrent.ConcurrentHashMap;12 13@Service14public class OtpService {15    private static final Logger logger = LoggerFactory.getLogger(OtpService.class);16    private static final int OTP_EXPIRY_SECONDS = 120;17    18    @Autowired19    private EmailService emailService;20 21    // Concurrent map to store OTP: phoneNumber -> OtpData22    private final Map<String, OtpData> otpStorage = new ConcurrentHashMap<>();23    private final Random random = new Random();24 25    public String generateOtp(String phoneNumber, String email) {26        String otp = String.format("%06d", random.nextInt(1000000));27        otpStorage.put(phoneNumber, new OtpData(otp, LocalDateTime.now()));28        29        // Send Email30        String subject = "Your GeoReport Verification Code";31        String message = "Your GeoReport verification code is: " + otp + ".\n\nThis code expires in 2 minutes.";32        33        // Asynchronously send email to avoid blocking the API request34        new Thread(() -> {35            try {36                emailService.sendEmail(email, subject, message);37            } catch (Exception e) {38                logger.error("Error sending OTP email: {}", e.getMessage());39            }40        }).start();41        42        return otp;43    }44 45    public boolean verifyOtp(String phoneNumber, String otp) {46        OtpData data = otpStorage.get(phoneNumber);47        48        if (data == null) {49            return false;50        }51 52        // Check expiry53        if (data.timestamp.plusSeconds(OTP_EXPIRY_SECONDS).isBefore(LocalDateTime.now())) {54            otpStorage.remove(phoneNumber);55            return false;56        }57 58        // Check OTP59        if (data.otp.equals(otp)) {60            otpStorage.remove(phoneNumber);61            return true;62        }63 64        return false;65    }66 67    private static class OtpData {68        String otp;69        LocalDateTime timestamp;70 71        OtpData(String otp, LocalDateTime timestamp) {72            this.otp = otp;73            this.timestamp = timestamp;74        }75    }76}77