Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add email confirmation for password change #61

Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,16 @@ ResponseEntity<String> confirmRegistration(@RequestParam String tokenValue) {
}

@PostMapping("/change-password")
ResponseEntity<String> changeUserPassword(@RequestBody ChangeUserPasswordDTO dto, Principal principal) {

return new ResponseEntity<>(userService.changeUserPassword(dto, principal.getName()), HttpStatus.OK);
ResponseEntity<String> changeUserPassword(@RequestBody ChangeUserPasswordDTO dto, Principal principal, HttpServletRequest request) {
return new ResponseEntity<>(userService.changeUserPassword(dto, principal.getName(), request.getRequestURL().toString()), HttpStatus.OK);
}

@GetMapping("/confirm-change-password")
ResponseEntity<String> confirmChangeUserPassword(@RequestParam String tokenValue) {
return new ResponseEntity<>(userService.confirmChangeUserPassword(tokenValue), HttpStatus.OK);
}


@GetMapping("/{id}/reviews/received")
ResponseEntity<Page<ReviewDTO>> getReceivedReviewsForUser(@PathVariable long id, Pageable pageable) {
return new ResponseEntity<>(reviewService.getReceivedReviewsForUser(id, pageable), HttpStatus.OK);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ public class Token {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Enumerated(EnumType.STRING)
private TokenType type;

private String value = UUID.randomUUID().toString();

private String data;

@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private User user;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package pl.simpleascoding.tutoringplatform.domain.token;

public enum TokenType {
REGISTER, PASSWORD, EMAIL
REGISTER, PASSWORD, EMAIL, CHANGE_EMAIL_CONFIRMATION
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This enum name implies, that it is used for changing the user's email address. Please rename to something like CHANGE_PASSWORD_CONFIRMATION.
Also, if we're not using PASSWORD and EMAIL values, you can delete them.
I'd also advise changing the REGISTER enum to REGISTER_CONFIRMATION, so that all enums in this file have similar names.

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ public interface UserService extends UserDetailsService {

String confirmUserRegistration(String token);

String changeUserPassword(ChangeUserPasswordDTO dto, String username);
String changeUserPassword(ChangeUserPasswordDTO dto, String username, String rootUrl);

String confirmChangeUserPassword(String token);

boolean checkUserExists(long id);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,18 @@
@RequiredArgsConstructor
class UserServiceImpl implements UserService {

private final UserRepository userRepository;
private final TokenRepository tokenRepository;
private final PasswordEncoder passwordEncoder;

private final JavaMailSender mailSender;

private static final String REGISTRATION_MAIL_SUBJECT = "Confirm your email";
private static final String REGISTRATION_MAIL_TEXT = "Hi %s, please visit the link below to confirm your email address and activate your account: \n%s";
private static final String REGISTRATION_LINK = "%s/confirm-registration?tokenValue=%s";

private static final String USER_NOT_FOUND_MSG = "User with \"%s\" username, has not been found";
private static final String CONFIRMATION_MAIL_SUBJECT = "Confirm your password change";
private static final String CONFIRMATION_MAIL_TEXT = "Hi %s, please visit the link below to confirm your password change: \n%s";
private static final String CONFIRMATION_LINK = "%s/confirm-change-password?tokenValue=%s";

Eukon05 marked this conversation as resolved.
Show resolved Hide resolved
private final UserRepository userRepository;
private final TokenRepository tokenRepository;
private final PasswordEncoder passwordEncoder;
private final JavaMailSender mailSender;

@Override
public User getUserById(long id) {
Expand Down Expand Up @@ -110,21 +111,53 @@ public String confirmUserRegistration(String tokenValue) {
* @param username Username of the user
* @return The status of the operation
*/

@Override
@Transactional
public String changeUserPassword(ChangeUserPasswordDTO newPasswordsData, String username) {
public String changeUserPassword(ChangeUserPasswordDTO newPasswordsData, String username, String rootUrl) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead newPasswordsData should be changeUserPasswordDTO or just dto.

I know ChangeUserPasswordDTO contain:

  • old password,
  • new password,
  • confirmation password
    But this object is using for change one password - not to change many passwords.

User userEntity = userRepository.findUserByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException(username));

if (isChangeAllowed(userEntity.getPassword(), newPasswordsData)) {
userEntity.setPassword(passwordEncoder.encode(newPasswordsData.newPassword()));

Token token = new Token(TokenType.CHANGE_EMAIL_CONFIRMATION);
String password = newPasswordsData.newPassword();
token.setData(passwordEncoder.encode(password));
userEntity.getTokens().add(token);

SimpleMailMessage message = new SimpleMailMessage();
message.setTo(userEntity.getEmail());
message.setSubject(CONFIRMATION_MAIL_SUBJECT);
message.setText(String.format(CONFIRMATION_MAIL_TEXT, userEntity.getName(), String.format(CONFIRMATION_LINK, rootUrl, token.getValue())));

mailSender.send(message);

return HttpStatus.OK.getReasonPhrase();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of returning HttpStatus - please use RscpDTO with RscpStatus inside of it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of returning HttpStatus - please use RscpDTO with RscpStatus inside of it.

} else {
return HttpStatus.UNAUTHORIZED.getReasonPhrase();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of returning HttpStatus - please use RscpDTO with RscpStatus inside of it.

}
}

@Override
@Transactional
public String confirmChangeUserPassword(String tokenValue) {
Token token = tokenRepository.findTokenByValue(tokenValue).orElseThrow(TokenNotFoundException::new);

if (token.getType() != TokenType.CHANGE_EMAIL_CONFIRMATION) {
throw new InvalidTokenException();
}

if (token.getConfirmedAt() != null) {
throw new TokenAlreadyConfirmedException();
}
String password = token.getData();
token.getUser().setPassword(password);

token.confirm();

return HttpStatus.OK.getReasonPhrase();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of returning HttpStatus - please use RscpDTO with RscpStatus inside of it.

}

@Override
public boolean checkUserExists(long id) {
return userRepository.existsById(id);
Expand Down