Skip to content
Snippets Groups Projects
Commit 3b154135 authored by Zink Hannah's avatar Zink Hannah
Browse files

exception handling if email is invalid or already exists

parent 4e2c212d
No related branches found
No related tags found
1 merge request!29final login and registration process
import {NavLink} from "react-router-dom";
import {deleteCookie} from "../jwt/Cookies.ts";
function Footer() {
const handleLogout = () => {
deleteCookie('Jwt');
};
return (
<nav>
<ul>
<div className="navLinks">
<li>
<NavLink to="/home" onClick={handleLogout}>
Ausloggen</NavLink>
</li>
</div>
</ul>
</nav>
);
}
export default Footer();
\ No newline at end of file
......@@ -16,7 +16,6 @@ function Login() {
await handleLogin();
};
const handleLogin = async () => {
try {
const res = await fetch("http://localhost:8080/api/v1/auth/authenticate",{
method:"POST",
body:JSON.stringify({email:email,password:password}),
......@@ -38,14 +37,18 @@ function Login() {
navigate('/');
} else {
window.alert(`Fehler bei der Anmeldung: ${res.status} - ${res.statusText}`);
const errorBody = await res.json();
if (res.status === 400 && errorBody.error === 'InvalidEmailException') {
window.alert("Fehler bei der Anmeldung: Ungültige E-Mail-Adresse.");
console.error('Fehler bei der Anmeldung: Ungültige E-Mail-Adresse.');
} else {
window.alert(`Fehler bei der Anmeldung: ${res.status} - ${res.statusText}`);
console.error('Fehler bei der Anmeldung:', res.status, res.statusText);
}
navigate('/login');
console.error('Fehler bei der Anmeldung:', res.status, res.statusText);
}
} catch (error:any) {
console.error('Fehler bei der Anmeldung:', error.message);
}
}
};
return (
......
......@@ -44,17 +44,17 @@ function Register() {
e.preventDefault(); //verhindert, dass die Seite neu geladen wird, wenn das Formular abgeschickt wird
if (!isValidEmail(email)) {
openErrorModal('Ungültige E-Mail-Adresse');
openErrorModal('Ungültige E-Mail-Adresse. Frontend');
return;
}
if (!isValidName(firstname) || !isValidName(lastname)) {
openErrorModal('Vorname und Nachname dürfen nicht leer sein');
openErrorModal('Vorname und Nachname dürfen nicht leer sein. Frontend');
return;
}
if (!isValidPassword(password)) {
openErrorModal('Das Passwort muss mindestens 4 Zeichen lang sein');
openErrorModal('Das Passwort muss mindestens 4 Zeichen lang sein. Frontend');
return;
}
await handleRegister();
......@@ -64,31 +64,45 @@ function Register() {
console.log("handle register")
try {
const requestBody = {
firstname:firstname,
lastname:lastname,
email:email,
password:password
firstname: firstname,
lastname: lastname,
email: email,
password: password
};
console.log(requestBody)
const res = await fetch("http://localhost:8080/api/v1/auth/register", {
method:"POST",
method: "POST",
headers: {
"Content-Type": "application/json"
},
body:JSON.stringify(requestBody
)}
body: JSON.stringify(requestBody)
}
)
const {token} = await res.json();
console.log("Jwt Token not decoded"+token);
const decodedToken = jwtDecode(token);
// @ts-ignore
const expirationDate = new Date(decodedToken.exp * 1000); //*1000 Anzahl der Sekunden seit 1.1.1970 darstellt - JS arbeitet jedoch normalerweise mit Millisekunden
setCookie("Jwt",token, expirationDate);
console.log("Jwt decoded " + decodedToken);
navigate('/');
} catch (error:any) {
console.error('Fehler bei der Anmeldung:', error.message);
console.dir(error)
if (res.ok) {
const {token} = await res.json();
console.log("Jwt Token not decoded" + token);
const decodedToken = jwtDecode(token);
// @ts-ignore
const expirationDate = new Date(decodedToken.exp * 1000); //*1000 Anzahl der Sekunden seit 1.1.1970 darstellt - JS arbeitet jedoch normalerweise mit Millisekunden
setCookie("Jwt", token, expirationDate);
console.log("Jwt decoded " + decodedToken);
navigate('/');
} else {
const errorBody = await res.json();
if (res.status === 400 && errorBody.error === 'InvalidEmailException') {
window.alert("Fehler bei der Anmeldung: Ungültige E-Mail-Adresse.");
console.error('Fehler bei der Anmeldung: Ungültige E-Mail-Adresse.');
} else if (res.status === 409 && errorBody.error === 'DataIntegrityViolationException') {
window.alert("Fehler bei der Anmeldung: E-Mail-Adresse bereits vorhanden.");
console.error('Fehler bei der Anmeldung: E-Mail-Adresse bereits vorhanden.');
} else {
window.alert(`Fehler bei der Anmeldung: ${res.status} - ${res.statusText}`);
console.error('Fehler bei der Anmeldung:', res.status, res.statusText);
}
}
} catch (e) {
}
};
......
package hdm.mi.growbros.auth;
import hdm.mi.growbros.exceptions.InvalidDataException;
import hdm.mi.growbros.exceptions.InvalidEmailException;
import hdm.mi.growbros.models.user.Role;
import hdm.mi.growbros.models.user.User;
import hdm.mi.growbros.models.user.UserRepository;
......@@ -9,6 +11,8 @@ import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
@RequiredArgsConstructor
......@@ -24,6 +28,19 @@ public class AuthenticationService {
* @return
*/
public AuthenticationResponse register(RegisterRequest request) {
if (!isValidEmail(request.getEmail())) {
throw new InvalidEmailException("Ungültige E-Mail-Adresse. Backend");
}
if (request.getFirstname().length() < 4 ) {
throw new InvalidDataException("Vorname muss mindestens 4 Zeichen lang sein. Backend");
}
if (request.getLastname().length() < 4) {
throw new InvalidDataException("Nachname muss mindestens 4 Zeichen lang sein. Backend");
}
var user = User.builder()
.firstname(request.getFirstname())
.lastname(request.getLastname())
......@@ -53,4 +70,12 @@ public class AuthenticationService {
.token(jwtToken)
.build();
}
private boolean isValidEmail(String email) {
String emailRegex = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}$";
Pattern pattern = Pattern.compile(emailRegex);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
}
package hdm.mi.growbros.exceptions;
public class InvalidDataException extends RuntimeException{
public InvalidDataException(String message) {
super(message);
}
}
package hdm.mi.growbros.exceptions;
public class InvalidEmailException extends RuntimeException{
public InvalidEmailException(String message) {
super(message);
}
}
......@@ -17,7 +17,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
@RequiredArgsConstructor
public class ApplicationConfig {
private final UserRepository repository;
@Bean //Schnittstelle die verwendet wird, um Benutzerdetails zu laden
@Bean
public UserDetailsService userDetailsService() {
return username -> repository.findByEmail(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment