Skip to content

Commit

Permalink
formatted files
Browse files Browse the repository at this point in the history
  • Loading branch information
haliskunduz committed Oct 23, 2023
1 parent 3faea89 commit e193588
Show file tree
Hide file tree
Showing 8 changed files with 161 additions and 158 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,95 +25,101 @@
@RequestMapping("/api/auth")
public class AuthController {

private final AuthService authService;
private final EmailService emailService;
private final UserService userService;
private final ResetCodeRepository resetCodeRepository;

@Autowired
public AuthController(AuthService authService, EmailService emailService, UserService userService, ResetCodeRepository resetCodeRepository) {
this.authService = authService;
this.emailService= emailService;
this.userService= userService;
this.resetCodeRepository = resetCodeRepository;
}

@PostMapping("/register")
public ResponseEntity<User> registerUser(@RequestBody RegisterUserRequestDto registerUserRequestDto){
User userToCreate = authService.registerUser(registerUserRequestDto);
return ResponseEntity.ok(userToCreate);
}

@PostMapping("/change-password")
public ResponseEntity<Boolean> changePassword(@RequestBody ChangeUserPasswordRequestDto passwordRequestDto) {
Boolean changePasswordResult = authService.changeUserPassword(passwordRequestDto);
return ResponseEntity.ok(changePasswordResult);
}

@PostMapping("/login")
public ResponseEntity<LoginUserResponseDto> login(@RequestBody LoginUserRequestDto loginRequest) {
LoginUserResponseDto loginResponse = authService.loginUser(loginRequest);
return ResponseEntity.ok(loginResponse);
}

@PostMapping("/forgot-password")
public ResponseEntity<String> forgotPassword(@RequestParam String email) {
User user = userService.getUserByEmail(email);

if (user == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
}

// Generate and save a reset code (you can use UUID or any secure method)
String code = generateResetCode(user.getId());

// Send email with reset code
String subject = "Password Reset";
String message = "Your password reset code is: " + code;
message += "\n The reset code will expire after 24 hours.";
emailService.sendEmail(email, subject, message);

return ResponseEntity.ok("Reset code sent successfully");
}

@PostMapping("/verify-reset-code")
public ResponseEntity<String> verifyResetCode(@RequestBody VerifyResetCodeRequestDto request) {
Optional<ResetCode> resetCodeOptional = resetCodeRepository.findByCode(request.getResetCode());
if (resetCodeOptional.isEmpty() || resetCodeOptional.get().getExpirationDate().before(new Date())) {
// Invalid or expired reset code
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid or expired reset code");
}

ResetCode resetCode = resetCodeOptional.get();

// Check if the reset code matches the user
String userEmail = userService.getUserById(resetCode.getUserId()).getEmail();
if (!userEmail.equals(request.getUserEmail())) {
// Reset code does not match the user
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(userEmail+ " " + request.getUserEmail());
}

// Reset code is valid, generate a JWT token for the user
String token = JwtUtil.generateToken(userService.getUserById(resetCode.getUserId()).getEmail());

// Clear the reset code after generating the token
resetCodeRepository.deleteByUserId(resetCode.getUserId());

return ResponseEntity.ok(token);
}
private String generateResetCode(String userId) {
// Check if a reset code exists for the user
ResetCode existingResetCode = resetCodeRepository.findByUserId(userId);

// If a reset code exists, delete it
if (existingResetCode != null) {
resetCodeRepository.delete(existingResetCode);
}
String code = UUID.randomUUID().toString().replace("-", "").substring(0, 6).toUpperCase();

ResetCode resetCode = new ResetCode(code, userId, new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000));
resetCodeRepository.save(resetCode);

return code;
}
private final AuthService authService;

private final EmailService emailService;

private final UserService userService;

private final ResetCodeRepository resetCodeRepository;

@Autowired
public AuthController(AuthService authService, EmailService emailService, UserService userService,
ResetCodeRepository resetCodeRepository) {
this.authService = authService;
this.emailService = emailService;
this.userService = userService;
this.resetCodeRepository = resetCodeRepository;
}

@PostMapping("/register")
public ResponseEntity<User> registerUser(@RequestBody RegisterUserRequestDto registerUserRequestDto) {
User userToCreate = authService.registerUser(registerUserRequestDto);
return ResponseEntity.ok(userToCreate);
}

@PostMapping("/change-password")
public ResponseEntity<Boolean> changePassword(@RequestBody ChangeUserPasswordRequestDto passwordRequestDto) {
Boolean changePasswordResult = authService.changeUserPassword(passwordRequestDto);
return ResponseEntity.ok(changePasswordResult);
}

@PostMapping("/login")
public ResponseEntity<LoginUserResponseDto> login(@RequestBody LoginUserRequestDto loginRequest) {
LoginUserResponseDto loginResponse = authService.loginUser(loginRequest);
return ResponseEntity.ok(loginResponse);
}

@PostMapping("/forgot-password")
public ResponseEntity<String> forgotPassword(@RequestParam String email) {
User user = userService.getUserByEmail(email);

if (user == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
}

// Generate and save a reset code (you can use UUID or any secure method)
String code = generateResetCode(user.getId());

// Send email with reset code
String subject = "Password Reset";
String message = "Your password reset code is: " + code;
message += "\n The reset code will expire after 24 hours.";
emailService.sendEmail(email, subject, message);

return ResponseEntity.ok("Reset code sent successfully");
}

@PostMapping("/verify-reset-code")
public ResponseEntity<String> verifyResetCode(@RequestBody VerifyResetCodeRequestDto request) {
Optional<ResetCode> resetCodeOptional = resetCodeRepository.findByCode(request.getResetCode());
if (resetCodeOptional.isEmpty() || resetCodeOptional.get().getExpirationDate().before(new Date())) {
// Invalid or expired reset code
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid or expired reset code");
}

ResetCode resetCode = resetCodeOptional.get();

// Check if the reset code matches the user
String userEmail = userService.getUserById(resetCode.getUserId()).getEmail();
if (!userEmail.equals(request.getUserEmail())) {
// Reset code does not match the user
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(userEmail + " " + request.getUserEmail());
}

// Reset code is valid, generate a JWT token for the user
String token = JwtUtil.generateToken(userService.getUserById(resetCode.getUserId()).getEmail());

// Clear the reset code after generating the token
resetCodeRepository.deleteByUserId(resetCode.getUserId());

return ResponseEntity.ok(token);
}

private String generateResetCode(String userId) {
// Check if a reset code exists for the user
ResetCode existingResetCode = resetCodeRepository.findByUserId(userId);

// If a reset code exists, delete it
if (existingResetCode != null) {
resetCodeRepository.delete(existingResetCode);
}
String code = UUID.randomUUID().toString().replace("-", "").substring(0, 6).toUpperCase();

ResetCode resetCode = new ResetCode(code, userId, new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000));
resetCodeRepository.save(resetCode);

return code;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,6 @@ public ResponseEntity<List<User>> getUsers(GetAllUsersFilterRequestDto filter) {
return ResponseEntity.ok(users);
}

@GetMapping("/deneme")
public ResponseEntity<User> deneme(
@RequestParam(value = "email", required = true) final String email){
User users = userService.getUserByEmail(email);
return ResponseEntity.ok((users));
}

@DeleteMapping("/delete")
public ResponseEntity<Boolean> deleteUser(@RequestParam(value = "id", required = true) final String id) {
Boolean deleteResult = userService.deleteUserById(id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
@Getter
public class VerifyResetCodeRequestDto {

private String resetCode;
private String resetCode;

private String userEmail;
private String userEmail;

}
72 changes: 37 additions & 35 deletions app/backend/src/main/java/com/app/gamereview/model/ResetCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,51 +8,53 @@
@Document(collection = "resetCodes")
public class ResetCode {

@Id
private String id;
@Id
private String id;

public String getId() {
return id;
}
public String getId() {
return id;
}

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

public String getCode() {
return code;
}
public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}
public void setCode(String code) {
this.code = code;
}

public String getUserId() {
return userId;
}
public String getUserId() {
return userId;
}

public void setUser(String userId) {
this.userId = userId;
}
public void setUser(String userId) {
this.userId = userId;
}

public Date getExpirationDate() {
return expirationDate;
}
public Date getExpirationDate() {
return expirationDate;
}

public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}

private String code;
@Indexed(unique = true) // Ensures a unique constraint on userId field
private String userId; // ID of the associated user
private Date expirationDate;
private String code;

public ResetCode(String code, String userId, Date expirationDate) {
@Indexed(unique = true) // Ensures a unique constraint on userId field
private String userId; // ID of the associated user

this.code = code;
this.userId = userId;
this.expirationDate = expirationDate;
}
private Date expirationDate;

public ResetCode(String code, String userId, Date expirationDate) {

this.code = code;
this.userId = userId;
this.expirationDate = expirationDate;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
import java.util.Optional;

public interface ResetCodeRepository extends MongoRepository<ResetCode, String> {
ResetCode findByUserId(String userId);
Optional<ResetCode> findByCode(String code);
void deleteByUserId(String userId);

ResetCode findByUserId(String userId);

Optional<ResetCode> findByCode(String code);

void deleteByUserId(String userId);

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public interface UserRepository extends MongoRepository<User, String> {

Optional<User> findByEmailAndIsDeletedFalse(String email);

@Query("{ 'email' : ?0 }")
Optional<User> findByEmail(String email);
@Query("{ 'email' : ?0 }")
Optional<User> findByEmail(String email);

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,19 @@

@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;

public void sendEmail(String toEmail,
String subject,
String body
) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("[email protected]");
message.setTo(toEmail);
message.setText(body);
message.setSubject(subject);
mailSender.send(message);
System.out.println("Mail Send...");
@Autowired
private JavaMailSender mailSender;

public void sendEmail(String toEmail, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("[email protected]");
message.setTo(toEmail);
message.setText(body);
message.setSubject(subject);
mailSender.send(message);
System.out.println("Mail Send...");

}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ public Boolean deleteUserById(String id) {
return false;
}

public User getUserByEmail(String email) {
Optional<User> getResult = userRepository.findByEmail(email);
public User getUserByEmail(String email) {
Optional<User> getResult = userRepository.findByEmail(email);

return getResult.orElse(null);
}
return getResult.orElse(null);
}

}

0 comments on commit e193588

Please sign in to comment.