From fa7dd1e3c45c2457c58af9caffe4db6bfbfc387f Mon Sep 17 00:00:00 2001 From: Mika Bomm Date: Sun, 8 Sep 2024 10:18:37 +0200 Subject: [PATCH] extract password hashing to external service PasswordService.java --- .../docusphere/service/PasswordService.java | 22 +++++++++++++++++++ .../mixel/docusphere/service/UserService.java | 9 ++++---- 2 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 server/src/main/java/com/mixel/docusphere/service/PasswordService.java diff --git a/server/src/main/java/com/mixel/docusphere/service/PasswordService.java b/server/src/main/java/com/mixel/docusphere/service/PasswordService.java new file mode 100644 index 0000000..645a989 --- /dev/null +++ b/server/src/main/java/com/mixel/docusphere/service/PasswordService.java @@ -0,0 +1,22 @@ +package com.mixel.docusphere.service; + +import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; +import org.springframework.stereotype.Service; + +@Service +public class PasswordService { + + private final Argon2PasswordEncoder passwordEncoder; + + public PasswordService() { + this.passwordEncoder = new Argon2PasswordEncoder(16, 32, 1, 4096, 3); + } + + public String hashPassword(String password) { + return passwordEncoder.encode(password); + } + + public boolean checkPassword(String rawPassword, String encodedPassword) { + return passwordEncoder.matches(rawPassword, encodedPassword); + } +} diff --git a/server/src/main/java/com/mixel/docusphere/service/UserService.java b/server/src/main/java/com/mixel/docusphere/service/UserService.java index 1241d80..8c51ebc 100644 --- a/server/src/main/java/com/mixel/docusphere/service/UserService.java +++ b/server/src/main/java/com/mixel/docusphere/service/UserService.java @@ -18,12 +18,13 @@ public class UserService { private final UserRepository userRepository; - private final Argon2PasswordEncoder passwordEncoder; + private final PasswordService passwordService; // Constructor - public UserService(UserRepository userRepository) { - this.passwordEncoder = new Argon2PasswordEncoder(16, 32, 1, 4096, 3); + + public UserService(UserRepository userRepository, PasswordService passwordService) { this.userRepository = userRepository; + this.passwordService = passwordService; } public List findAll() { @@ -59,7 +60,7 @@ public class UserService { private void isPasswordAlreadySet(UserRequestDTO userRequestDTO, User user) { if (userRequestDTO.getPassword() != null && !userRequestDTO.getPassword().isEmpty()) { - user.setPasswordHash(passwordEncoder.encode(userRequestDTO.getPassword())); + user.setPasswordHash(passwordService.hashPassword(userRequestDTO.getPassword())); } }