From 9522584b04e8e436a7b29c7edd080ea84876caa4 Mon Sep 17 00:00:00 2001 From: Dario Date: Sun, 3 Mar 2024 20:22:31 +0100 Subject: [PATCH 1/3] chore: sql script --- api/db/init.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 api/db/init.sql diff --git a/api/db/init.sql b/api/db/init.sql new file mode 100644 index 00000000..5f805d03 --- /dev/null +++ b/api/db/init.sql @@ -0,0 +1 @@ +INSERT INTO roles (id, name) VALUES (1, 'user') ON CONFLICT (id) DO NOTHING; \ No newline at end of file From e7384680593775f7779c5f70e60463e2e04989a3 Mon Sep 17 00:00:00 2001 From: Dario Date: Tue, 5 Mar 2024 16:13:44 +0100 Subject: [PATCH 2/3] Revert "chore: sql script" This reverts commit 9522584b04e8e436a7b29c7edd080ea84876caa4. --- api/db/init.sql | 1 - 1 file changed, 1 deletion(-) delete mode 100644 api/db/init.sql diff --git a/api/db/init.sql b/api/db/init.sql deleted file mode 100644 index 5f805d03..00000000 --- a/api/db/init.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO roles (id, name) VALUES (1, 'user') ON CONFLICT (id) DO NOTHING; \ No newline at end of file From 54b9f66fb2621b8d304e83a809dfeb84d95c6447 Mon Sep 17 00:00:00 2001 From: Dario Date: Tue, 5 Mar 2024 16:26:51 +0100 Subject: [PATCH 3/3] refactor!: user roles as string --- .../lab/en2b/quizapi/auth/AuthService.java | 2 +- .../quizapi/auth/config/UserDetailsImpl.java | 5 +-- .../lab/en2b/quizapi/commons/user/User.java | 13 +------ .../quizapi/commons/user/UserService.java | 8 ++--- .../en2b/quizapi/commons/user/role/Role.java | 34 ------------------- .../commons/user/role/RoleRepository.java | 12 ------- .../en2b/quizapi/auth/AuthServiceTest.java | 11 ++---- 7 files changed, 7 insertions(+), 78 deletions(-) delete mode 100644 api/src/main/java/lab/en2b/quizapi/commons/user/role/Role.java delete mode 100644 api/src/main/java/lab/en2b/quizapi/commons/user/role/RoleRepository.java diff --git a/api/src/main/java/lab/en2b/quizapi/auth/AuthService.java b/api/src/main/java/lab/en2b/quizapi/auth/AuthService.java index 704149b9..a0b6b507 100644 --- a/api/src/main/java/lab/en2b/quizapi/auth/AuthService.java +++ b/api/src/main/java/lab/en2b/quizapi/auth/AuthService.java @@ -52,7 +52,7 @@ public ResponseEntity login(LoginDto loginRequest){ * @return a response containing a message */ public ResponseEntity register(RegisterDto registerRequest) { - userService.createUser(registerRequest,Set.of("user")); + userService.createUser(registerRequest,"user"); return ResponseEntity.ok("User registered successfully!"); } diff --git a/api/src/main/java/lab/en2b/quizapi/auth/config/UserDetailsImpl.java b/api/src/main/java/lab/en2b/quizapi/auth/config/UserDetailsImpl.java index 10460e1a..ae68bccf 100644 --- a/api/src/main/java/lab/en2b/quizapi/auth/config/UserDetailsImpl.java +++ b/api/src/main/java/lab/en2b/quizapi/auth/config/UserDetailsImpl.java @@ -2,7 +2,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import lab.en2b.quizapi.commons.user.User; -import lab.en2b.quizapi.commons.user.role.Role; import lombok.AllArgsConstructor; import lombok.Getter; import org.springframework.security.core.GrantedAuthority; @@ -26,9 +25,7 @@ public class UserDetailsImpl implements UserDetails { private Collection authorities; public static UserDetailsImpl build(User user) { List authorities = new ArrayList<>(); - for(Role role : user.getRoles()){ - authorities.add(new SimpleGrantedAuthority(role.getName())); - } + authorities.add(new SimpleGrantedAuthority(user.getRole())); return new UserDetailsImpl(user.getId(),user.getUsername() , user.getEmail(), user.getPassword(), authorities); } @Override diff --git a/api/src/main/java/lab/en2b/quizapi/commons/user/User.java b/api/src/main/java/lab/en2b/quizapi/commons/user/User.java index 56d64935..593572bd 100644 --- a/api/src/main/java/lab/en2b/quizapi/commons/user/User.java +++ b/api/src/main/java/lab/en2b/quizapi/commons/user/User.java @@ -1,6 +1,5 @@ package lab.en2b.quizapi.commons.user; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.persistence.*; import jakarta.validation.constraints.Email; @@ -8,11 +7,9 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import lab.en2b.quizapi.commons.exceptions.TokenRefreshException; -import lab.en2b.quizapi.commons.user.role.Role; import lombok.*; import java.time.Instant; -import java.util.Set; @Entity @Table( name = "users", @@ -56,16 +53,8 @@ public class User { private Instant refreshExpiration; @NotNull - @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name="users_roles", - joinColumns= - @JoinColumn(name="user_id", referencedColumnName="id"), - inverseJoinColumns= - @JoinColumn(name="role_id", referencedColumnName="id") - ) - @JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "permissions"}) @JsonProperty("role") - private Set roles; + private String role; public String obtainRefreshIfValid() { if(getRefreshExpiration() == null || getRefreshExpiration().compareTo(Instant.now()) < 0){ diff --git a/api/src/main/java/lab/en2b/quizapi/commons/user/UserService.java b/api/src/main/java/lab/en2b/quizapi/commons/user/UserService.java index 43ede68f..3c1bcf42 100644 --- a/api/src/main/java/lab/en2b/quizapi/commons/user/UserService.java +++ b/api/src/main/java/lab/en2b/quizapi/commons/user/UserService.java @@ -3,7 +3,6 @@ import lab.en2b.quizapi.auth.config.UserDetailsImpl; import lab.en2b.quizapi.auth.dtos.RegisterDto; import lab.en2b.quizapi.commons.exceptions.InvalidAuthenticationException; -import lab.en2b.quizapi.commons.user.role.RoleRepository; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.userdetails.UserDetails; @@ -14,22 +13,19 @@ import java.time.Instant; import java.util.Optional; -import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class UserService implements UserDetailsService { private final UserRepository userRepository; - private final RoleRepository roleRepository; @Value("${REFRESH_TOKEN_DURATION_MS}") private long REFRESH_TOKEN_DURATION_MS; @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { return UserDetailsImpl.build(userRepository.findByEmail(email).orElseThrow(() -> new InvalidAuthenticationException("Invalid email or password provided!"))); } - public void createUser(RegisterDto registerRequest, Set roleNames){ + public void createUser(RegisterDto registerRequest, String roleName){ if (userRepository.existsByEmail(registerRequest.getEmail()) || userRepository.existsByUsername(registerRequest.getUsername())) { throw new IllegalArgumentException("Error: email is already in use!"); } @@ -38,7 +34,7 @@ public void createUser(RegisterDto registerRequest, Set roleNames){ .username(registerRequest.getUsername()) .email(registerRequest.getEmail()) .password(new BCryptPasswordEncoder().encode(registerRequest.getPassword())) - .roles(roleNames.stream().map( roleName -> roleRepository.findByName(roleName).orElseThrow()).collect(Collectors.toSet())) + .role(roleName) .build()); } diff --git a/api/src/main/java/lab/en2b/quizapi/commons/user/role/Role.java b/api/src/main/java/lab/en2b/quizapi/commons/user/role/Role.java deleted file mode 100644 index 8e828ff1..00000000 --- a/api/src/main/java/lab/en2b/quizapi/commons/user/role/Role.java +++ /dev/null @@ -1,34 +0,0 @@ -package lab.en2b.quizapi.commons.user.role; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import jakarta.persistence.*; -import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.Size; -import lab.en2b.quizapi.commons.user.User; -import lombok.*; - -import java.util.Set; - -@Entity -@Table(name = "roles") -@NoArgsConstructor -@RequiredArgsConstructor -@AllArgsConstructor -@Setter -@Getter -@Builder -public class Role { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Setter(AccessLevel.NONE) - private Long id; - - @NonNull - @NotBlank - @Size(max=255) - private String name; - - @ManyToMany(mappedBy ="roles") - @JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "roles"}) - private Set users; -} diff --git a/api/src/main/java/lab/en2b/quizapi/commons/user/role/RoleRepository.java b/api/src/main/java/lab/en2b/quizapi/commons/user/role/RoleRepository.java deleted file mode 100644 index 84c7a7a2..00000000 --- a/api/src/main/java/lab/en2b/quizapi/commons/user/role/RoleRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package lab.en2b.quizapi.commons.user.role; - - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.Optional; - -@Repository -public interface RoleRepository extends JpaRepository { - Optional findByName(String roleName); -} diff --git a/api/src/test/java/lab/en2b/quizapi/auth/AuthServiceTest.java b/api/src/test/java/lab/en2b/quizapi/auth/AuthServiceTest.java index 37af25a6..b6bd1c29 100644 --- a/api/src/test/java/lab/en2b/quizapi/auth/AuthServiceTest.java +++ b/api/src/test/java/lab/en2b/quizapi/auth/AuthServiceTest.java @@ -7,8 +7,6 @@ import lab.en2b.quizapi.commons.user.User; import lab.en2b.quizapi.commons.user.UserRepository; import lab.en2b.quizapi.commons.user.UserService; -import lab.en2b.quizapi.commons.user.role.Role; -import lab.en2b.quizapi.commons.user.role.RoleRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -20,11 +18,9 @@ import org.springframework.security.core.Authentication; import org.springframework.test.context.junit.jupiter.SpringExtension; -import javax.swing.text.html.Option; import java.time.Instant; import java.util.List; import java.util.Optional; -import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; @@ -40,21 +36,19 @@ public class AuthServiceTest { @Mock UserRepository userRepository; @Mock - RoleRepository roleRepository; - @Mock AuthenticationManager authenticationManager; @Mock JwtUtils jwtUtils; User defaultUser; @BeforeEach void setUp() { - this.userService = new UserService(userRepository,roleRepository); + this.userService = new UserService(userRepository); this.authService = new AuthService(authenticationManager,userService,jwtUtils); this.defaultUser = User.builder() .id(1L) .email("test@email.com") .username("test") - .roles(Set.of(new Role("user"))) + .role("user") .password("password") .refreshToken("token") .refreshExpiration(Instant.ofEpochSecond(TimeUtil.computeStartOfNextSecond(System.currentTimeMillis()+ 1000))) @@ -89,7 +83,6 @@ void testRegister(){ when(userRepository.existsByEmail(any())).thenReturn(false); when(userRepository.existsByUsername(any())).thenReturn(false); when(userRepository.save(any())).thenAnswer(i -> i.getArguments()[0]); - when(roleRepository.findByName(any())).thenReturn(Optional.of(new Role("user"))); ResponseEntity actual = authService.register(new RegisterDto("test","username","password"));