Home > Software design >  How to get data from springboot and compare it?
How to get data from springboot and compare it?

Time:06-18

I have made a project where user first register and using the same email and password it will login which will generate a random string and it will be sent to user mail id and also it will be stored in database. Now, I have to validate the user input OTP(random string) with the OTP stored in database to check if user is putting the OTP correct. For that I have written some logic but everytime I check it shows invalid OTP. Here is my code :

OTPMailContoller class :

@PostMapping("/validate-otp")
    public SessionHandling validateOtp(@RequestBody SessionHandling otp) throws Exception{
    
    String tempOtp = otp.getOneTimePassword();
    
    SessionHandling UserOtp = null;
    
    if(tempOtp != null) {
    UserOtp = emailService.fetchUserByOneTimePassword(tempOtp);
    }
    if(UserOtp == null){
        throw new Exception("invalid otp !!!");
    }
    return UserOtp;
    }

Service class :

public SessionHandling fetchUserByOneTimePassword(String tempOtp) {
        return repo.findByOneTimePassword(tempOtp);
    }

Repository class :

 @Query(value = "select * from session_handling where one_time_password= :otp", nativeQuery =true)
    public SessionHandling findByOneTimePassword(@Param("otp")String tempOtp);

Model class :

    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private String email;
    private String password;
    private String cpassword;
    
    private static final long OTP_VALID_DURATION = 5 * 60 * 1000;   // 5 minutes
    
    @Column(name = "one_time_password")
    private String oneTimePassword;

Error :

Invalid otp !!!

CodePudding user response:

@Query(value = "select * from session_handling where one_time_password= :otp", nativeQuery =true)
public SessionHandling findByOneTimePassword(@Param("otp")String tempOtp);

Try to change your query from above to following

@Query(value = "select sh from SessionHandling sh where sh.oneTimePassword = :otp")
public SessionHandling findByOneTimePassword(String otp);

CodePudding user response:

We can try removing the @Query annotation altogether. If we use JpaRepository, we can simply give repository method as findByOneTimePassword(String) method and we'll get the results as we have column named "oneTimePassword".

in your case.. try using below code in repository

public SessionHandling findByOneTimePassword(String otp);

Just make sure camel casing in your model class. (Which you already have)

@Column(name = "one_time_password")
private String oneTimePassword;
  • Related