[REFACTOR] Extracted user-related operations into a dedicated UserService and updated controller methods to use it

main
bjkim 9 months ago
parent 26842fe040
commit ea3f7d02b6

@ -8,6 +8,7 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import kr.re.etri.autoflow.service.AuthService; import kr.re.etri.autoflow.service.AuthService;
import kr.re.etri.autoflow.service.UserService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
@ -60,6 +61,7 @@ public class AuthController {
RefreshTokenService refreshTokenService; RefreshTokenService refreshTokenService;
private final AuthService authService; private final AuthService authService;
private final UserService userService;
@Operation(summary = "로그인", description = "사용자 인증 후 JWT 및 리프레시 토큰 쿠키를 반환합니다.") @Operation(summary = "로그인", description = "사용자 인증 후 JWT 및 리프레시 토큰 쿠키를 반환합니다.")
@ApiResponses({ @ApiResponses({
@ -173,39 +175,18 @@ public class AuthController {
public ResponseEntity<UserInfoResponse> getUserById( public ResponseEntity<UserInfoResponse> getUserById(
@Parameter(description = "사용자 ID", example = "1") @PathVariable Long id) { @Parameter(description = "사용자 ID", example = "1") @PathVariable Long id) {
return userRepository.findById(id) return userService.getUserById(id)
.map(user -> new UserInfoResponse(
user.getId(),
user.getUsername(),
user.getEmail(),
user.getRoles().stream()
.map(role -> role.getName().name())
.toList()
))
.map(ResponseEntity::ok) .map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build()); .orElse(ResponseEntity.notFound().build());
} }
@Operation(summary = "전체 사용자 조회", description = "등록된 모든 사용자 목록을 조회합니다.") @Operation(summary = "전체 사용자 조회", description = "등록된 모든 사용자 목록을 조회합니다.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "사용자 목록 조회 성공")
})
@GetMapping("/users") @GetMapping("/users")
public ResponseEntity<List<UserInfoResponse>> getAllUsers() { public ResponseEntity<List<UserInfoResponse>> getAllUsers() {
List<UserInfoResponse> users = userRepository.findAll().stream() return ResponseEntity.ok(userService.getAllUsers());
.map(user -> new UserInfoResponse(
user.getId(),
user.getUsername(),
user.getEmail(),
user.getRoles().stream()
.map(role -> role.getName().name())
.toList()
))
.toList();
return ResponseEntity.ok(users);
} }
@Operation(summary = "사용자 수정", description = "사용자 정보를 수정합니다.") @Operation(summary = "사용자 수정", description = "사용자 정보를 수정합니다.")
@ApiResponses({ @ApiResponses({
@ApiResponse(responseCode = "200", description = "사용자 수정 성공"), @ApiResponse(responseCode = "200", description = "사용자 수정 성공"),

@ -5,9 +5,10 @@ import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import kr.re.etri.autoflow.entity.ProjectPermission; import kr.re.etri.autoflow.entity.ProjectPermission;
import kr.re.etri.autoflow.entity.UserProjectMapEntity; import kr.re.etri.autoflow.payload.response.UserProjectResponse;
import kr.re.etri.autoflow.payload.request.UserPermissionRequest; import kr.re.etri.autoflow.payload.request.UserPermissionRequest;
import kr.re.etri.autoflow.service.ProjectPermissionService; import kr.re.etri.autoflow.service.ProjectPermissionService;
import kr.re.etri.autoflow.service.UserService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -22,6 +23,7 @@ import java.util.Set;
public class ProjectPermissionController { public class ProjectPermissionController {
private final ProjectPermissionService projectPermissionService; private final ProjectPermissionService projectPermissionService;
private final UserService userService;
//private final AuthService authService; //private final AuthService authService;
@Operation(summary = "프로젝트에 사용자 권한 추가") @Operation(summary = "프로젝트에 사용자 권한 추가")
@ -35,14 +37,14 @@ public class ProjectPermissionController {
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }
@Operation(summary = "사용자 프로젝트 조회", description = "특정 사용자가 속한 모든 프로젝트와 권한을 조회합니다.") // @Operation(summary = "사용자 프로젝트 조회", description = "특정 사용자가 속한 모든 프로젝트와 권한을 조회합니다.")
@GetMapping("/user/{userId}/projects") // @GetMapping("/user/{userId}/projects")
public ResponseEntity<List<UserProjectMapEntity>> getUserProjects( // public ResponseEntity<List<UserProjectMapEntity>> getUserProjects(
@Parameter(description = "유저 ID") @PathVariable Long userId // @Parameter(description = "유저 ID") @PathVariable Long userId
) { // ) {
List<UserProjectMapEntity> projects = projectPermissionService.getUserProjects(userId); // List<UserProjectMapEntity> projects = projectPermissionService.getUserProjects(userId);
return ResponseEntity.ok(projects); // return ResponseEntity.ok(projects);
} // }
@Operation(summary = "사용자 권한 조회") @Operation(summary = "사용자 권한 조회")
@GetMapping("/{projectId}/users/{userId}/permissions") @GetMapping("/{projectId}/users/{userId}/permissions")
@ -57,6 +59,15 @@ public class ProjectPermissionController {
return ResponseEntity.ok(permissions); return ResponseEntity.ok(permissions);
} }
@Operation(summary = "사용자 프로젝트 조회")
@GetMapping("/users/{userId}/projects")
public ResponseEntity<List<UserProjectResponse>> getUserProjects(
@Parameter(name = "userId", description = "사용자 ID", example = "100", required = true)
@PathVariable Long userId) {
List<UserProjectResponse> projects = userService.getUserProjects(userId);
return ResponseEntity.ok(projects);
}
@Operation(summary = "사용자 권한 수정") @Operation(summary = "사용자 권한 수정")
@PutMapping("/{projectId}/users/{userId}/permissions") @PutMapping("/{projectId}/users/{userId}/permissions")
public ResponseEntity<?> updateUserPermissions( public ResponseEntity<?> updateUserPermissions(

@ -0,0 +1,17 @@
package kr.re.etri.autoflow.payload.response;
import kr.re.etri.autoflow.entity.ProjectPermission;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.Set;
@Getter
@Setter
@AllArgsConstructor
public class UserProjectResponse {
private Long projectId;
private String projectName;
private Set<ProjectPermission> permissions;
}

@ -3,6 +3,7 @@ package kr.re.etri.autoflow.repository;
import kr.re.etri.autoflow.entity.ProjectEntity; import kr.re.etri.autoflow.entity.ProjectEntity;
import kr.re.etri.autoflow.entity.UserProjectMapEntity; import kr.re.etri.autoflow.entity.UserProjectMapEntity;
import kr.re.etri.autoflow.models.User; import kr.re.etri.autoflow.models.User;
import kr.re.etri.autoflow.payload.response.UserInfoResponse;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
@ -14,7 +15,5 @@ public interface UserProjectMapRepository extends JpaRepository<UserProjectMapEn
List<UserProjectMapEntity> findAllByProject(ProjectEntity project); List<UserProjectMapEntity> findAllByProject(ProjectEntity project);
List<UserProjectMapEntity> findAllByUser(User user); List<UserProjectMapEntity> findAllByUserId(Long userId);
boolean existsByProjectAndUser(ProjectEntity project, User user);
} }

@ -12,7 +12,6 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.Set; import java.util.Set;
@Service @Service
@ -50,12 +49,6 @@ public class ProjectPermissionService {
.orElse(Collections.emptySet()); .orElse(Collections.emptySet());
} }
@Transactional(readOnly = true)
public List<UserProjectMapEntity> getUserProjects(Long userId) {
User user = getUser(userId);
return userProjectMapRepository.findAllByUser(user);
}
public void updateUserPermissions(Long projectId, Long userId, Set<ProjectPermission> newPermissions) { public void updateUserPermissions(Long projectId, Long userId, Set<ProjectPermission> newPermissions) {
ProjectEntity project = getProject(projectId); ProjectEntity project = getProject(projectId);
User user = getUser(userId); User user = getUser(userId);

@ -0,0 +1,61 @@
package kr.re.etri.autoflow.service;
import kr.re.etri.autoflow.payload.response.UserProjectResponse;
import kr.re.etri.autoflow.payload.response.UserInfoResponse;
import kr.re.etri.autoflow.repository.UserProjectMapRepository;
import kr.re.etri.autoflow.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final UserProjectMapRepository userProjectMapRepository;
/**
* ID
*/
public Optional<UserInfoResponse> getUserById(Long id) {
return userRepository.findById(id)
.map(user -> new UserInfoResponse(
user.getId(),
user.getUsername(),
user.getEmail(),
user.getRoles().stream()
.map(role -> role.getName().name())
.toList()
));
}
/**
*
*/
public List<UserInfoResponse> getAllUsers() {
return userRepository.findAll().stream()
.map(user -> new UserInfoResponse(
user.getId(),
user.getUsername(),
user.getEmail(),
user.getRoles().stream()
.map(role -> role.getName().name())
.toList()
))
.toList();
}
public List<UserProjectResponse> getUserProjects(Long userId) {
return userProjectMapRepository.findAllByUserId(userId).stream()
.map(mapping -> new UserProjectResponse(
mapping.getProject().getId(),
mapping.getProject().getPrjNm(),
mapping.getPermissions()
))
.collect(Collectors.toList());
}
}

@ -12,3 +12,7 @@ INSERT INTO tb_role (id, name)
SELECT 3, 'ROLE_ADMIN' SELECT 3, 'ROLE_ADMIN'
WHERE NOT EXISTS (SELECT 1 FROM tb_role WHERE id = 3); WHERE NOT EXISTS (SELECT 1 FROM tb_role WHERE id = 3);
INSERT INTO autoflow.tb_user (id, username, email, password) VALUES (1, 'admin', 'admin123@naver.com', '$2a$10$Nqkjg2IpDoTzrbHEgZGiceSOBXy1f6jI7AC/JIIuaLOLs.3FcODdm');
INSERT INTO autoflow.tb_user (id, username, email, password) VALUES (2, 'test', 'test@naver.com', '$2a$10$LJ/Ln/tP976l/z6RO3o1AuT/BQDHEHO7D7wA.YFIHbdGDI3B5avju');
INSERT INTO autoflow.tb_user (id, username, email, password) VALUES (3, 'testuser', 'test@example.com', '$2a$10$iSpdIsx17F7qrHLhkRAtWe79QqZYUmKWkyAJsp1FwIXQV.Jb6e6ym');
INSERT INTO autoflow.tb_user (id, username, email, password) VALUES (4, 'cuuva', 'cuuva@cuuva.com', '$2a$10$bVqcCLeCATq8GIO29H53qep3ALXA.qtXZrtVqXpXcik1vDrsSFZwC');

Loading…
Cancel
Save