Skip to content

Commit

Permalink
Forgot password done
Browse files Browse the repository at this point in the history
  • Loading branch information
AlistairMRoss committed Oct 15, 2023
1 parent 0274633 commit 5550331
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 54 deletions.
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
package com.fragile.infosafe.primary.controller;

import com.fragile.infosafe.primary.requests.PasswordResetRequest;
import com.fragile.infosafe.primary.service.EncryptionService;
import com.fragile.infosafe.primary.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.crypto.EncryptedPrivateKeyInfo;

@RestController
@RequestMapping("api/forgot")
@RequiredArgsConstructor
@Slf4j
public class ForgotPasswordController {
private final UserService userService;
private EncryptionService encryptionService;

@PostMapping("/request-reset")
public ResponseEntity<String> requestPasswordReset(@RequestBody PasswordResetRequest request) {
try {
if (userService.checkEmailExists(request.getEmail())){
log.info("in here");
userService.generateAndSaveOtp(request.getEmail());
return ResponseEntity.ok("Password reset instructions sent to your email.");
} else {
Expand All @@ -41,16 +48,16 @@ public ResponseEntity<String> resetPassword(@RequestBody PasswordResetRequest re
}
}

// @PostMapping("/verify-otp")
// public ResponseEntity<String> verifyOTP(@RequestBody PasswordResetRequest request) {
// try {
// if (userService.verifyOTP(request.getEmail(), request.getOtp())) {
// return ResponseEntity.ok("OTP is valid.");
// } else {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid OTP.");
// }
// } catch (Exception e) {
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred.");
// }
// }
@PostMapping("/verify-otp")
public ResponseEntity<String> verifyOTP(@RequestBody PasswordResetRequest request) {
try {
if (userService.verifyOTP(request.getEmail(), request.getOtp())) {
return ResponseEntity.ok("OTP is valid.");
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid OTP.");
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public User updateUser(User user) {
}

public Optional<User> getUserByEmail(String email) {
return repository.findByEmail(email);
return repository.findByEmail(encryptionService.encryptString(email));
}


Expand All @@ -67,11 +67,11 @@ public void assignRoleToUser(int userId, Role role) {
}

public boolean checkEmailExists(String email) {
return repository.existsByEmail(email);
return repository.existsByEmail(encryptionService.encryptString(email));
}

public void resetPassword(String email, String newPassword) {
Optional<User> userOptional = repository.findByEmail(email);
Optional<User> userOptional = repository.findByEmail(encryptionService.encryptString(email));
if (userOptional.isPresent()) {
User user = userOptional.get();
user.setPassword(passwordEncoder.encode(newPassword));
Expand All @@ -83,13 +83,15 @@ public void resetPassword(String email, String newPassword) {
}

public void generateAndSaveOtp(String email) {
Optional<User> userOptional = repository.findByEmail(email);
Optional<User> userOptional = repository.findByEmail(encryptionService.encryptString(email));
if (userOptional.isPresent()) {
User user = userOptional.get();
String otp = generateRandomOTP();
user.setOtp(otp);
repository.save(user);
emailService.sendEmail(user.getEmail(), "Forgot Password", "Your OTP is:\n" + otp);
emailService.sendEmail(email, "Forgot Password", "Your OTP is:\n" + otp);
}else{
log.info("Broke here" + email);
}
}

Expand All @@ -101,7 +103,7 @@ private String generateRandomOTP() {
}

public boolean verifyOTP(String email, String otp) {
Optional<User> userOptional = repository.findByEmail(email);
Optional<User> userOptional = repository.findByEmail(encryptionService.encryptString(email));
if (userOptional.isPresent()) {
User user = userOptional.get();
return user.getOtp().equals(otp);
Expand Down
110 changes: 74 additions & 36 deletions frontend/infosafe_frontend/src/components/ForgotPassword.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,53 +5,89 @@ export const ForgotPassword = () => {
const [email, setEmail] = useState("");
const [otp, setOtp] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [isOtpVerified, setIsOtpVerified] = useState(false);
const handleClick = (e) => {
emailState()
e.preventDefault();
const forgot = {email, otp, newPassword};
emailState();

const forgot = {
email: email
};
fetch("http://localhost:8080/api/forgot/request-reset", {
method: "POST",
body: JSON.stringify(forgot),
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + sessionStorage.getItem("accessToken")
},
body: JSON.stringify(forgot)
}).then((response) => {
if (response.ok) {
console.log("Email sent");
// need to add success message
} else {
response.text().then((errorMessage) => {
// error message here
console.error(errorMessage);
});
"Content-Type": "application/json"
}
})
.then((response) => {
if (response.ok) {
console.log("Email sent");
} else {
response.text().then((errorMessage) => {
console.error(errorMessage);
});
}
})
.catch((error) => {
console.error(error);
});
}

const verifyOtp = () => {
const otpData = { email: email, otp: otp };
fetch("http://localhost:8080/api/forgot/verify-otp", {
method: "POST",
body: JSON.stringify(otpData),
headers: {
"Content-Type": "application/json"
}
})
.then((response) => {
if (response.ok) {
console.log("OTP verified");
setIsOtpVerified(true);
document.getElementById("otpPanel").style.display = "none";
document.getElementById("passwordPanel").style.display = "inline";
} else {
response.text().then((errorMessage) => {
console.error(errorMessage);
console.log("OTP not valid");
});
}
})
.catch((error) => {
console.error(error);
console.log("OTP verification failed");
});
}

const handleSecondClick = (e) => {
const forgot = {email, otp, newPassword};
fetch("http://http://localhost:8080/api/forgot/reset-password", {
e.preventDefault();

if (newPassword !== confirmPassword) {
console.log("Passwords do not match.");
return;
}
const forgot = { email: email, otp: otp, newPassword: newPassword };
fetch("http://localhost:8080/api/forgot/reset-password", {
method: "POST",
body: JSON.stringify(forgot),
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + sessionStorage.getItem("accessToken")
},
body: JSON.stringify(forgot)
}).then((response) => {
if (response.ok) {
console.log("Password changed");
// need to add success message
} else {
response.text().then((errorMessage) => {
// error message here
console.error(errorMessage);
});
"Content-Type": "application/json"
}
})
.then((response) => {
if (response.ok) {
console.log("Password changed");
window.location.href = "/";
} else {
response.text().then((errorMessage) => {
console.error(errorMessage);
});
}
})
.catch((error) => {
console.error(error);
});
Expand All @@ -61,8 +97,7 @@ export const ForgotPassword = () => {
document.getElementById("otpPanel").style.display = "inline";
}
const otpState = () => {
document.getElementById("otpPanel").style.display = "none";
document.getElementById("passwordPanel").style.display = "inline";
verifyOtp()
}

const handleEmailChange = (event) => {
Expand All @@ -77,12 +112,16 @@ export const ForgotPassword = () => {
setNewPassword(event.target.value);
};

const handleConfirmPasswordChange = (event) => {
setConfirmPassword(event.target.value);
}

return (
<div className='background'>
<div className='inputPanel'>
<div className='emailPanel' id='emailPanel'>
<p className="emailTitle">Enter your E-Mail:</p>
<input type='text' value={email} onChange={handleEmailChange} className="forgotEmail"/>
<input type='email' value={email} onChange={handleEmailChange} className="forgotEmail"/>
<button className='submit' onClick={handleClick}>
Submit
</button>
Expand All @@ -96,17 +135,16 @@ export const ForgotPassword = () => {
</div>
<div className='passwordPanel' id='passwordPanel'>
<p className="passTitle">Enter new password:</p>
<input type='text' value={newPassword} onChange={handleNewPasswordChange} className="forgotPass"/>
<input type='password' value={newPassword} onChange={handleNewPasswordChange} className="forgotPass"/>
<p className="rePassTitle">Re-enter new password:</p>
<input type='text' className="forgotRePass"/>
<input type='password' value={confirmPassword} onChange={handleConfirmPasswordChange} className="forgotRePass"/>
<button className='submit' onClick={handleSecondClick}>
Submit
</button>
</div>
</div>
</div>
);

}

export default ForgotPassword;

0 comments on commit 5550331

Please sign in to comment.