'Check to see if a registered user has been enabled after email verification
I am currently working on building a JWT authentication flow that requires an email confirmation. It is pretty straightforward. As long as the user has not confirmed the e-mail, he is not activated. Everything works perfectly.
Sadly, I have no idea how to check whether the user has already activated his email when he logs in, or mine doesn't work.
I have access to the user entity. The output also gives me the correct user again. Unfortunately, I don't have access to the isEnabled getter.
Since I'm relatively new to Spring Boot, I've read it's best practice to have your own UserDetailsImpl class that implements the UserDetails. So I'm not quite sure whether I should use this class or the user entity class to call isEnabled.
When I use if(userDetails.isEnabled()), I always get true (thats actually right), and appUser.isEnabled() also doesn't work because my user is Optional.
SignInUser
public ResponseEntity signInUser(SignInRequest signInRequest) throws AuthenticationException {
try {
Authentication authentication =
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
signInRequest.getUsername(), signInRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String accessToken = jwtUtils.generateJwtAccessToken(signInRequest.getUsername());
String refreshToken = jwtUtils.generateJwtRefreshToken(signInRequest.getUsername());
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
Optional<AppUser> appUser = userRepository.findByUsername(userDetails.getUsername());
//
// System.out.println("USER" + appUser.isEnabled()); --> is not possible
// userDetails.isEnabled() --> alway true
List<String> roles =
userDetails.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
return ResponseEntity.ok(
new JwtResponse(
accessToken,
refreshToken,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
} catch (AuthenticationException e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(new CustomException("Wrong Password or Username", HttpStatus.FORBIDDEN));
}
}
AppUser Model
@Entity()
@Table(
name = "Users",
uniqueConstraints = {
@UniqueConstraint(columnNames = "username"),
@UniqueConstraint(columnNames = "email")
})
@Getter
@Setter
@ToString
@NoArgsConstructor
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long id;
@NotBlank
@Size(min = 4, max = 20)
private String username;
@NotBlank
@Size(max = 50)
@Email
private String email;
@NotBlank
@Size(max = 120)
private String password;
@ManyToMany(fetch = EAGER)
@JoinTable(
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "roles_id"))
private Set<Role> roles = new HashSet<>();
private boolean isEnabled;
public AppUser(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
public AppUser(String username, String email, String password, boolean isEnabled) {
this.username = username;
this.email = email;
this.password = password;
this.isEnabled = isEnabled;
}
UserDetailsImpl Class
@AllArgsConstructor
@NoArgsConstructor
@Data
public class UserDetailsImpl implements UserDetails {
private AppUser appUser;
private Long id;
private String username;
private String email;
private String password;
private Boolean enabled;
private Collection<? extends GrantedAuthority> authorities;
private UserDetailsImpl(AppUser appUser) {
this.appUser = appUser;
}
private UserDetailsImpl(
Long id, String username, String email, String password, List<GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;
}
static UserDetailsImpl build(AppUser appUser) {
List<GrantedAuthority> authorities =
appUser.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name()))
.collect(Collectors.toList());
return new UserDetailsImpl(
appUser.getId(),
appUser.getUsername(),
appUser.getEmail(),
appUser.getPassword(),
authorities);
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
}
UserRepository
@Repository
public interface UserRepository extends JpaRepository<AppUser, Long> {
Optional<AppUser> findByUsername(String username);
boolean existsByUsername(String username);
Boolean existsByEmail(String email);
AppUser findByEmailIgnoreCase(String email);
boolean i
sEnabled(AppUser appUser); }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
