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

feat : 유저, 돌봄유저 카운트 구현 #40

Merged
merged 2 commits into from
Aug 12, 2023
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
15 changes: 14 additions & 1 deletion src/main/java/dev/umc/healody/family/FamilyApiController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import dev.umc.healody.common.SuccessStatus;
import dev.umc.healody.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor
Expand All @@ -29,7 +32,17 @@ public SuccessResponse<Long> addFamily(@RequestBody FamilyRequestDTO familyDTORe

@DeleteMapping
public SuccessResponse<Void> delete(@RequestBody FamilyRequestDTO familyDTORequest){
boolean result = familyService.delete(familyDTORequest.getUserId(), familyDTORequest.getHomeId());
boolean result = familyService.delete(getCurrentUserId(), familyDTORequest.getHomeId());
return new SuccessResponse<>(SuccessStatus.SUCCESS);
}

private Long getCurrentUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if ((authentication != null) && (authentication.getPrincipal() instanceof UserDetails)) {
String userName = authentication.getName();
Long userId = userService.findUserIdByPhone(userName);
return userId;
}
return null; // 인증된 사용자가 없을 경우 null 반환
}
}
1 change: 1 addition & 0 deletions src/main/java/dev/umc/healody/family/FamilyService.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public Long create(FamilyRequestDTO requestDTO){
}

Family family = requestDTO.toEntity(user, home);
home.setUser_cnt(home.getUser_cnt() + 1);
Family save = familyRepository.save(family);
return save.getId();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public Long create(CareUserRequestDTO requestDTO){
}

CareUser careUser = requestDTO.toEntity(optionalHome.get());
home.setCaring_cnt(home.getCaring_cnt() + 1);
CareUser save = careUserRepository.save(careUser);

return save.getId();
Expand Down
38 changes: 21 additions & 17 deletions src/main/java/dev/umc/healody/home/controller/HomeController.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@
import dev.umc.healody.family.FamilyService;
import dev.umc.healody.family.careuser.CareUserResponseDTO;
import dev.umc.healody.family.careuser.CareUserService;
import dev.umc.healody.home.domain.Home;
import dev.umc.healody.home.dto.HomeDto;
import dev.umc.healody.home.service.HomeService;
import dev.umc.healody.user.service.CustomUserDetailsService;
import jakarta.servlet.http.HttpServletRequest;
import dev.umc.healody.user.entity.User;
import dev.umc.healody.user.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.*;
Expand All @@ -34,14 +36,11 @@ public class HomeController {

@PostMapping("/home") //집 추가 POST
public ResponseEntity<HomeDto> createHome(@RequestBody HomeDto homeDto, HttpServletRequest request){
Long adminId = homeService.getCurrentUserId(request);
Long adminId = getCurrentUserId();
HomeDto newHome = homeService.createHome(homeDto, adminId);
familyService.create(FamilyRequestDTO.builder().userId(adminId).homeId(newHome.homeId).build());
return ResponseEntity.status(HttpStatus.CREATED).body(newHome);
}
//집을 만들며 그 안에 가족을 넣기, 그리고 user_cnt 관리
//돌봄계정 careuser_cnt 관리
//가족구성원의 할일 목표 등등 정보 조회하기
@GetMapping("/home/{userId}") // 집 조회 GET
public ResponseEntity<Map<String, Map<String, List<String>>>> viewMyFamily(@PathVariable Long userId) {
List<FamilyResponseDTO> familyList = familyService.searchFamily(userId);
Expand All @@ -57,19 +56,15 @@ public ResponseEntity<Map<String, Map<String, List<String>>>> viewMyFamily(@Path

@DeleteMapping("/home/{homeId}") //집 삭제 DELETE
public ResponseEntity<String> deleteHome(@PathVariable Long homeId, HttpServletRequest request){
HomeDto currentHome = homeService.getHomeInfo(homeId);
if (homeService.isAdmin(request, currentHome)) {
homeService.deleteHome(homeId);
return ResponseEntity.status(HttpStatus.OK).body("집이 삭제되었습니다.");
}else {
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("관리자 권한이 없습니다.");
}
Long currentUserId = getCurrentUserId();
homeService.deleteHome(homeId, currentUserId);
return ResponseEntity.ok().body("집이 삭제되었습니다.");
}
@PatchMapping("/home/{homeId}") //집 수정 PATCH
public ResponseEntity<HomeDto> updateHome(@PathVariable Long homeId, @RequestBody HomeDto homeDto, HttpServletRequest request){
HomeDto currentHome = homeService.getHomeInfo(homeId);
if (homeService.isAdmin(request, currentHome)) {
HomeDto updatedHome = homeService.updateHome(homeId, homeDto);
Long currentUserId = getCurrentUserId();
HomeDto updatedHome = homeService.updateHome(homeId, homeDto, currentUserId);
if (updatedHome != null) {
return ResponseEntity.ok(updatedHome);
}else {
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(homeDto);
Expand Down Expand Up @@ -101,4 +96,13 @@ private Map<String, List<String>> getFamilyInfo(Long homeId, Long userId) {
infoMap.put("care-user", careUserInfoList);
return infoMap;
}
private Long getCurrentUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if ((authentication != null) && (authentication.getPrincipal() instanceof UserDetails)) {
String userName = authentication.getName();
Long userId = userService.findUserIdByPhone(userName);
return userId;
}
return null; // 인증된 사용자가 없을 경우 null 반환
}
}
9 changes: 5 additions & 4 deletions src/main/java/dev/umc/healody/home/domain/Home.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,17 @@ public class Home{
@Column(nullable = false)
private Long user_cnt = 1L;

@Column(nullable = true)
private Long caring_cnt;
@Column(nullable = false)
private Long caring_cnt = 0L;

@Column(nullable = true)
@Column(nullable = false)
private Long admin;

@Builder
public Home(String name, Long homeId){
public Home(String name, Long homeId, Long admin){
this.name = name;
this.homeId = homeId;
this.admin = admin;
}

}
2 changes: 1 addition & 1 deletion src/main/java/dev/umc/healody/home/dto/HomeDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ public class HomeDto {


public Home toEntity(){
return Home.builder().name(name).homeId(homeId).build();
return Home.builder().name(name).homeId(homeId).admin(admin).build();
}
}
44 changes: 18 additions & 26 deletions src/main/java/dev/umc/healody/home/service/HomeService.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import jakarta.servlet.http.HttpSession;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
Expand All @@ -25,6 +26,7 @@ public HomeDto createHome(HomeDto homeDto, Long userId) {
return HomeDto.builder()
.homeId(save.getHomeId())
.name(save.getName())
.admin(userId)
.build();
}
public HomeDto getHomeInfo(Long HomeId){
Expand All @@ -39,41 +41,31 @@ public HomeDto getHomeInfo(Long HomeId){
return null;
}
@Transactional
public HomeDto updateHome(Long home_id, HomeDto homeDto) {
public HomeDto updateHome(Long home_id, HomeDto homeDto, Long currentUserId) {
Optional<Home> home = homeRepository.findHomeByHomeId(home_id);
if(home.isPresent()){
if (!home.get().getAdmin().equals(currentUserId)) {
throw new AccessDeniedException("권한이 없습니다.");
}
home.get().setName(homeDto.getName());
homeRepository.save(home.get());
HomeDto updatedHome = new HomeDto(home_id, homeDto.getName(), homeDto.getAdmin());
return updatedHome;
return HomeDto.builder()
.homeId(home_id)
.name(homeDto.getName())
.build();
}
return null;
}
@Transactional
public void deleteHome(Long home_id) {
try {
Optional<Home> home = homeRepository.findHomeByHomeId(home_id);
home.ifPresent(value -> homeRepository.delete(value));
} catch (Exception e){
throw new RuntimeException(e);
}
}
public Long getCurrentUserId(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session != null) {
Object userIdObj = session.getAttribute("userId");
if (userIdObj instanceof Long) {
return (Long) userIdObj;
public void deleteHome(Long home_id, Long currentUserId) {
Optional<Home> home = homeRepository.findHomeByHomeId(home_id);
if (home.isPresent()) {
// 현재 사용자가 집의 관리자인지 확인
if (!home.get().getAdmin().equals(currentUserId)) {
throw new AccessDeniedException("권한이 없습니다.");
}
}
return null; // 세션에 인증된 사용자 id가 없을 경우 null 반환
}

public boolean isAdmin(HttpServletRequest request, HomeDto homeDto){
Long adminId = getCurrentUserId(request);
if(adminId.equals(homeDto.admin)){return true;}
else{return false;}
homeRepository.delete(home.get());
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
@Component("userDetailsService")
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

private final UserRepository userRepository;

@Override
Expand All @@ -28,8 +29,6 @@ public UserDetails loadUserByUsername(final String phone) {
.map(user -> createUser(phone, user))
.orElseThrow(() -> new UsernameNotFoundException(phone + " -> 데이터베이스에서 찾을 수 없습니다."));
}


private org.springframework.security.core.userdetails.User createUser(String phone, User user) {
if (!user.isActivated()) {
throw new RuntimeException(phone + " -> 활성화되어 있지 않습니다.");
Expand All @@ -39,8 +38,10 @@ private org.springframework.security.core.userdetails.User createUser(String pho
.map(authority -> new SimpleGrantedAuthority(authority.getAuthorityName()))
.collect(Collectors.toList());

return new org.springframework.security.core.userdetails.User(user.getPhone(),
return new org.springframework.security.core.userdetails.User(
user.getPhone(),
user.getPassword(),
grantedAuthorities);
grantedAuthorities
);
}
}