Home > database >  How to check the user's verification code?
How to check the user's verification code?

Time:09-03

I am very new to Spring Boot. This is what I want to do: The user's email is [email protected]. That user already exists in my database, but I would like to know if their verificationCode is 123.

Entity:

public class Users {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String email;
    private String password;
    private String verificationCode;
    @Column(name = "verified", columnDefinition = "default false")
    private boolean verified = false;
    @CreationTimestamp
    private Date registrationDate;

    protected Users() {}

    public Users(String email, String password, String verificationCode) {
        this.email = email;
        this.password = password;
        this.verificationCode = verificationCode;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getVerificationCode() {
        return verificationCode;
    }

    public void setVerificationCode(String verificationCode) {
        this.verificationCode = verificationCode;
    }

    public boolean isVerified() {
        return verified;
    }

    public void setVerified(boolean verified) {
        this.verified = verified;
    }
}

So with userRepository.findByEmail("[email protected]") I am getting the correct user, but how do I check their verification code?

CodePudding user response:

if you're using userRepository.findByEmail("[email protected]"), just take the verification code from entity.

private static final String CODE = "123";

    final User user = userRepository.findByEmail("[email protected]");
    if (CODE.equals(user.getVerificationCode())) {
    // do something
    }

Another option to have it within query.

userRepository.findByEmailAndVerificationCode("[email protected]", CODE);

Or you can have something similar as Philipp wrote, but I would not get whole entity just find out if it exist. So solution would be

if (userRepository.existsByCode(CODE)) {
// do something
}

CodePudding user response:

You search for something like that:

public void checkVerificationCode(final String verificationCode) {
 final User user = userRepository.findByEmail("[email protected]");

 if (!user.getVerificationCode(verificationCode)) {
  throw new VerificationCodeException("Incorrect verification code.");
 }
}
  • Related