From 4a85a55290b8a87bb8bad1e9f3c6fd1c620b4dc9 Mon Sep 17 00:00:00 2001 From: Bartha Maxime <231026@umons.ac.be> Date: Wed, 6 Mar 2024 17:38:09 +0100 Subject: [PATCH] added Token and User Services --- .../herisson/Clyde/Services/TokenService.java | 36 +++++++++++++++++++ .../herisson/Clyde/Services/UserService.java | 36 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 backend/src/main/java/ovh/herisson/Clyde/Services/TokenService.java create mode 100644 backend/src/main/java/ovh/herisson/Clyde/Services/UserService.java diff --git a/backend/src/main/java/ovh/herisson/Clyde/Services/TokenService.java b/backend/src/main/java/ovh/herisson/Clyde/Services/TokenService.java new file mode 100644 index 0000000..b427735 --- /dev/null +++ b/backend/src/main/java/ovh/herisson/Clyde/Services/TokenService.java @@ -0,0 +1,36 @@ +package ovh.herisson.Clyde.Services; + +import org.springframework.stereotype.Service; +import ovh.herisson.Clyde.Repositories.TokenRepository; +import ovh.herisson.Clyde.Tables.Token; +import ovh.herisson.Clyde.Tables.User; + +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.Date; + +@Service +public class TokenService { + + TokenRepository tokenRepo; + + public TokenService(TokenRepository tokenRepo){ + this.tokenRepo = tokenRepo; + } + + + public String generateNewToken(){ + byte[] bytes = new byte[64]; + new SecureRandom().nextBytes(bytes); + String token = new String(bytes, StandardCharsets.US_ASCII); + System.out.println(token); + return token; + } + + + //todo potentiellement return bool pour savoir si token bien add + public void saveToken(String token, User user, Date expirationDate){ + tokenRepo.save(new Token(user,token)); + } + +} \ No newline at end of file diff --git a/backend/src/main/java/ovh/herisson/Clyde/Services/UserService.java b/backend/src/main/java/ovh/herisson/Clyde/Services/UserService.java new file mode 100644 index 0000000..b2c080d --- /dev/null +++ b/backend/src/main/java/ovh/herisson/Clyde/Services/UserService.java @@ -0,0 +1,36 @@ +package ovh.herisson.Clyde.Services; + +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; +import ovh.herisson.Clyde.Repositories.UserRepository; +import ovh.herisson.Clyde.Tables.User; + +@Service +public class UserService { + + private final UserRepository userRepo; + private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + + + public UserService(UserRepository userRepo){ + this.userRepo = userRepo; + } + + + public User getUser(String identifier){ + if (identifier == null) return null; + try { + int id = Integer.parseInt(identifier); + return userRepo.findById(id); + } + catch (NumberFormatException nfe){ + return userRepo.findByEmail(identifier); + } + } + + + public boolean checkPassword(User user, String tryingPassword){ + return passwordEncoder.matches(tryingPassword, user.getPassword()); + } + +}