Issue
I made a login page were I am getting user Email id, and then I am generating a otp and sending to the user mail. Now I want to save the generated otp in database to the particular user by using his mailid. But the problem is when I am saving otp in database it is not storing in the given mailid, and I am not able to figure it out.
My code:
SendOtp code :
public String sendOtp(@RequestParam("email") String email) {
// int otp = random.nextInt(999999);
String otp = RandomString.make(8);
String subject = "OTP from session-handling-proj By Harshit";
String toEmail = email;
String body = "OTP : " + otp;
SessionHandling sessionHandling = new SessionHandling();
sessionHandling.setOneTimePassword(otp);
repo.save(sessionHandling);
this.emailService.sendMail(toEmail, subject, body);
return ("success");
Database :
Id | password | emailid | name | Cpass | otp | time
8 | 123 | [email protected] | shymm | 123 | NULL | NULL
9 | NULL | NULL | NULL | NULL | Wi0ioiuZ | NULL
10 | NULL | NULL | NULL | NULL | R98RT1OZ | NULL
When I had tried storing otp it made new row i.e 9 & 10.
Solution
As already explained by @Thomas, you should always hash your passwords in production.
However, here is an example to update the otp using JPA repositories:
@Repository
public interface SessionHandlingRepository extends JpaRepository<SessionHandling, Long> {
@Transactional
@Modifying
@Query(value = "UPDATE SessionHandling s SET s.otp = :otpCode WHERE s.id = :id")
void updateOtp(@Param("id") Long whereId, @Param("otpCode") String otp);
}
Answered By - Jedupont
Answer Checked By - Willingham (JavaFixing Volunteer)