Skip to content
Advertisement

Java spring userRegister creates two database entries instead of one

As above this creates two database entries in user table. The process should be following:

  1. a new user enters their email and password -> saved in login table
  2. user confirm Email address -> entry in user table with username (email) and first&second name should be null at first.

For second the code would be like that (working)

User user = new User("username", null, null)
public RegistrationConfirmResponse registerNewUser(User user, String password) {
        loginRepository.findByUsername(user.getUsername()).get().setUsername(null);
        userRepository.save(user);
        passwordRepository.save(new Password(user.getUserId(), password));
        return new RegistrationConfirmResponse("done", user.getUsername());
    }

is returning

{"answer":"done","username":null}

in Database creates this 2 entries

ID enabled fistname locked secondname username
1 0 NULL 0 NULL test@example.com
2 0 NULL 0 NULL NULL

The entry with ID 1 is correct but number 2 must not be created.

RegistrationConfirmResponse

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class RegistrationConfirmResponse {
    private String answer;
    private String username;
}

Method calling registerNewUser

@Transactional
    public RegistrationConfirmResponse confirmToken(String token){
        var confirmationToken = confirmationTokenService.getToken(token);
        var confirmedAt = confirmationToken.getConfirmedAt();
        /* Uncommented due to testing usage
        if(confirmedAt != null && Duration.between(LocalDateTime.now(), confirmedAt).toSeconds() < 10) {
                System.out.println(Duration.between(LocalDateTime.now(), confirmedAt).toString());
                throw new IllegalStateException("email already confirmed confirmed at " + confirmedAt);
        }*/
        LocalDateTime expiredAt = confirmationToken.getExpiredAt();
        if(expiredAt.isBefore(LocalDateTime.now())){
            throw new IllegalStateException("token expired");
        }
        confirmationToken.setConfirmedAt(LocalDateTime.now());

        var user = new User(confirmationToken.getLogin().getUsername(), null, null);
        confirmationToken.getLogin().setUsername(null);
        return userService.registerNewUser(user, confirmationToken.getLogin().getPassword());
    }

Advertisement

Answer

Solution:

I removed the Login table and write directly in user table

now everything is working as it should be

Advertisement