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

improvement of error message for user when login data is incorrect

parent 18c3b853
No related branches found
No related tags found
1 merge request!29final login and registration process
import {useLocation} from "react-router-dom";
import {SetStateAction, useEffect} from "react";
export function setCookie(name: string, value: any, expirationDate: Date) {
let expires = "expires=" + expirationDate;
document.cookie = `${name}=${value}; ${expires}`
export function setCookie(name: string, value: any, expirationDate: Date, path: string) {
let expires = expirationDate.toUTCString();
document.cookie = `${name}=${value};expires=${expires};path=${path};`
}
export function getCookie(name: string | any[]) {
......
......@@ -16,6 +16,7 @@ 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}),
......@@ -23,33 +24,32 @@ function Login() {
"Content-Type": "application/json",
},
});
if (res.ok) { //delete old cookie and set new one with new expiration date
console.log(res)
if (res.status === 200) { //delete old cookie and set new one with new expiration date
const { token } = await res.json();
console.log(token);
deleteJwtCookie();
const decodedToken = jwtDecode(token);
console.log(decodedToken);
// @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);
document.cookie = `Jwt=${token};expires=${new Date(expirationDate).toUTCString()};path=/;`;
setCookie("Jwt",token, expirationDate,"/");
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 {
window.alert(`Fehler bei der Anmeldung: ${res.status} - ${res.statusText}`);
console.error('Fehler bei der Anmeldung:', res.status, res.statusText);
// @ts-ignore
const reader = res.body.getReader();
const { value, done } = await reader.read();
if (!done) {
const text = new TextDecoder().decode(value);
window.alert(text)
console.error(text);
}
navigate('/login');
}
};
} catch (e: any) {
console.log(e.status);
}
}
return (
<main>
......
......@@ -73,10 +73,11 @@ function Register() {
const {token} = await res.json();
console.log("Jwt Token not decoded" + token);
const decodedToken = jwtDecode(token);
console.log("Jwt decoded " + decodedToken);
// @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);
setCookie("Jwt", token, expirationDate,"/");
navigate('/');
} else {
// @ts-ignore
......
package hdm.mi.growbros.auth;
import hdm.mi.growbros.exceptions.EmailAlreadyExistsException;
import hdm.mi.growbros.exceptions.InvalidDataException;
import hdm.mi.growbros.exceptions.InvalidEmailException;
import hdm.mi.growbros.exceptions.*;
import hdm.mi.growbros.models.user.Role;
import hdm.mi.growbros.models.user.User;
import hdm.mi.growbros.repositories.UserRepository;
......@@ -11,10 +9,13 @@ import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.NoSuchElementException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
......@@ -35,15 +36,15 @@ public class AuthenticationService {
public AuthenticationResponse register(RegisterRequest request) {
if (!isValidEmail(request.getEmail())) {
throw new InvalidEmailException(HttpStatus.BAD_REQUEST, "Ungültige E-Mail-Adresse. Backend");
throw new InvalidEmailException("Ungültige E-Mail-Adresse.");
}
if (request.getFirstname().isEmpty()) {
throw new InvalidDataException(HttpStatus.BAD_REQUEST, "Vorname fehlt. Backend");
throw new InvalidDataException("Vorname fehlt.");
}
if (request.getLastname().isEmpty()) {
throw new InvalidDataException(HttpStatus.BAD_REQUEST, "Nachname fehlt. Backend");
throw new InvalidDataException("Nachname fehlt.");
}
try {
var user = User.builder()
......@@ -64,24 +65,27 @@ public class AuthenticationService {
}
public AuthenticationResponse authenticate(AuthenticationRequest request) {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.getEmail(),
request.getPassword()
)
);
var user = repository.findByEmail(request.getEmail()) //wenn der Nutzername und Passwort korrekt sind wird ein Token generiert
.orElseThrow(); // = Methode von Optional -> wird auf das Optionale angewendet, das durch repository.findByEmail zurückgegeben wird
// Wenn Benutzer gefunden -> das Optional mit dem Benutzer-Objekt gefüllt. Andernfalls wird eine NoSuchElementException ausgelöst.
var jwtToken = jwtService.generateToken(user);
return AuthenticationResponse.builder()
.token(jwtToken)
.build();
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.getEmail(),
request.getPassword()
)
);
var user = repository.findByEmail(request.getEmail()) //wenn der Nutzername und Passwort korrekt sind wird ein Token generiert
.orElseThrow(); // = Methode von Optional -> wird auf das Optionale angewendet, das durch repository.findByEmail zurückgegeben wird
// Wenn Benutzer gefunden -> das Optional mit dem Benutzer-Objekt gefüllt. Andernfalls wird eine NoSuchElementException ausgelöst.
var jwtToken = jwtService.generateToken(user);
return AuthenticationResponse.builder()
.token(jwtToken)
.build();
} catch (NoSuchElementException e) {
throw new UserNotFoundException("Benutzer mit Email:" + request.getEmail() + " nicht gefunden.");
} catch (BadCredentialsException e) {
throw new UserNotFoundException("Anmeldedaten sind nicht korrekt.");
}
}
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);
......
......@@ -4,6 +4,6 @@ import org.springframework.http.HttpStatus;
public class EmailAlreadyExistsException extends GrowBrosException{
public EmailAlreadyExistsException(HttpStatus httpStatus, String message) {
super(httpStatus, message);
super(HttpStatus.BAD_REQUEST, message);
}
}
......@@ -3,8 +3,8 @@ package hdm.mi.growbros.exceptions;
import org.springframework.http.HttpStatus;
public class InvalidDataException extends GrowBrosException{
public InvalidDataException(HttpStatus httpStatus, String message) {
super(httpStatus, message);
public InvalidDataException(String message) {
super(HttpStatus.BAD_REQUEST, message);
}
}
......@@ -3,7 +3,7 @@ package hdm.mi.growbros.exceptions;
import org.springframework.http.HttpStatus;
public class InvalidEmailException extends GrowBrosException{
public InvalidEmailException(HttpStatus httpStatus,String message) {
super(httpStatus, message);
public InvalidEmailException(String message) {
super(HttpStatus.BAD_REQUEST, message);
}
}
package hdm.mi.growbros.exceptions;
import org.springframework.http.HttpStatus;
public class UserNotFoundException extends GrowBrosException{
public UserNotFoundException (String message) {
super(HttpStatus.BAD_REQUEST,message);
}
}
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