Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removed Roles table and included it as a String column in the User table #85

Merged
merged 4 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion api/src/main/java/lab/en2b/quizapi/auth/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public ResponseEntity<JwtResponseDto> 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!");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -26,9 +25,7 @@ public class UserDetailsImpl implements UserDetails {
private Collection<? extends GrantedAuthority> authorities;
public static UserDetailsImpl build(User user) {
List<GrantedAuthority> 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
Expand Down
13 changes: 1 addition & 12 deletions api/src/main/java/lab/en2b/quizapi/commons/user/User.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
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;
import jakarta.validation.constraints.NotBlank;
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",
Expand Down Expand Up @@ -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<Role> roles;
private String role;

public String obtainRefreshIfValid() {
if(getRefreshExpiration() == null || getRefreshExpiration().compareTo(Instant.now()) < 0){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<String> 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!");
}
Expand All @@ -38,7 +34,7 @@ public void createUser(RegisterDto registerRequest, Set<String> 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());
}

Expand Down
34 changes: 0 additions & 34 deletions api/src/main/java/lab/en2b/quizapi/commons/user/role/Role.java

This file was deleted.

This file was deleted.

11 changes: 2 additions & 9 deletions api/src/test/java/lab/en2b/quizapi/auth/AuthServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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("[email protected]")
.username("test")
.roles(Set.of(new Role("user")))
.role("user")
.password("password")
.refreshToken("token")
.refreshExpiration(Instant.ofEpochSecond(TimeUtil.computeStartOfNextSecond(System.currentTimeMillis()+ 1000)))
Expand Down Expand Up @@ -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"));

Expand Down