diff --git a/src/main/java/net/skhu/likelion12thteam03be/UserCheckController.java b/src/main/java/net/skhu/likelion12thteam03be/UserCheckController.java new file mode 100644 index 0000000..73d903c --- /dev/null +++ b/src/main/java/net/skhu/likelion12thteam03be/UserCheckController.java @@ -0,0 +1,16 @@ +package net.skhu.likelion12thteam03be; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/users") +public class UserCheckController { + @GetMapping + public String userHi (Model model) { + return "user.html"; + } +} diff --git a/src/main/java/net/skhu/likelion12thteam03be/global/config/SecurityConfig.java b/src/main/java/net/skhu/likelion12thteam03be/global/config/SecurityConfig.java index aa2897e..59870de 100644 --- a/src/main/java/net/skhu/likelion12thteam03be/global/config/SecurityConfig.java +++ b/src/main/java/net/skhu/likelion12thteam03be/global/config/SecurityConfig.java @@ -31,10 +31,11 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .logout(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authorize -> authorize - .requestMatchers(HttpMethod.POST, "/users/**").permitAll() + .requestMatchers("/users/**").permitAll() .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() .requestMatchers("/", "/profile").permitAll() - .anyRequest().authenticated() +// .anyRequest().authenticated() + .anyRequest().permitAll() ) .addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class) .sessionManagement(sessionManagement -> sessionManagement diff --git a/src/main/java/net/skhu/likelion12thteam03be/global/jwt/TokenProvider.java b/src/main/java/net/skhu/likelion12thteam03be/global/jwt/TokenProvider.java index e28ff52..5056644 100644 --- a/src/main/java/net/skhu/likelion12thteam03be/global/jwt/TokenProvider.java +++ b/src/main/java/net/skhu/likelion12thteam03be/global/jwt/TokenProvider.java @@ -14,10 +14,13 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Component; import java.security.Key; import java.util.Date; +import java.util.List; @Slf4j @RequiredArgsConstructor @@ -32,14 +35,11 @@ public class TokenProvider { private String secret; private Key key; -/* @PostConstruct + @PostConstruct public void init() { + this.secret = secret.replace('+', '-').replace('/', '_'); byte[] key = Decoders.BASE64URL.decode(secret); this.key = Keys.hmacShaKeyFor(key); - }*/ - @PostConstruct - public void init() { - this.key = Keys.secretKeyFor(SignatureAlgorithm.HS512); } public String generateToken(String loginId) { // loginId @@ -90,7 +90,9 @@ public Authentication getAuthentication(String token) { User user = userRepository.findByLoginId(claims.getSubject()).orElseThrow(); - return new UsernamePasswordAuthenticationToken(user.getLoginId(), ""); + List authorities = List.of(new SimpleGrantedAuthority(user.getRole().toString())); + return new UsernamePasswordAuthenticationToken(user.getLoginId(), + "", authorities); } } diff --git a/src/main/java/net/skhu/likelion12thteam03be/post/api/dto/PostController.java b/src/main/java/net/skhu/likelion12thteam03be/post/api/dto/PostController.java index 492b017..1dd0c8f 100644 --- a/src/main/java/net/skhu/likelion12thteam03be/post/api/dto/PostController.java +++ b/src/main/java/net/skhu/likelion12thteam03be/post/api/dto/PostController.java @@ -25,7 +25,10 @@ public PostController(PostService postService) { // 글 저장 @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity postSave(@RequestPart("post") PostSaveReqDto postSaveReqDto, @RequestPart("imgUrl") MultipartFile imgUrl, Principal principal) throws IOException { + public ResponseEntity postSave( + @RequestPart("post") PostSaveReqDto postSaveReqDto, + @RequestPart("imgUrl") MultipartFile imgUrl, + Principal principal) throws IOException { postService.postSave(postSaveReqDto, imgUrl, principal); return new ResponseEntity<>("Successful Post Save", HttpStatus.CREATED); } @@ -77,15 +80,19 @@ public ResponseEntity postFindByUserId(@PathVariable("userId") L // 글 수정 @PatchMapping("/{postId}") - public ResponseEntity postUpdate(@PathVariable("postId") Long postId, @RequestPart("post") PostUpdateReqDto postUpdateReqDto, @RequestPart("imgUrl") MultipartFile imgUrl) throws IOException { - postService.postUpdate(postId, postUpdateReqDto, imgUrl); + public ResponseEntity postUpdate( + @PathVariable("postId") Long postId, + @RequestPart("post") PostUpdateReqDto postUpdateReqDto, + @RequestPart("imgUrl") MultipartFile imgUrl, + Principal principal) throws IOException { + postService.postUpdate(postId, postUpdateReqDto, imgUrl, principal); return new ResponseEntity<>("Successful Post Update", HttpStatus.OK); } // 글 삭제 @DeleteMapping("/{postId}") - public ResponseEntity postDelete(@PathVariable("postId") Long postId) throws IOException { - postService.postDelete(postId); + public ResponseEntity postDelete(@PathVariable("postId") Long postId, Principal principal) throws IOException { + postService.postDelete(postId, principal); return new ResponseEntity<>("Successful Post Delete", HttpStatus.OK); } } \ No newline at end of file diff --git a/src/main/java/net/skhu/likelion12thteam03be/post/application/PostService.java b/src/main/java/net/skhu/likelion12thteam03be/post/application/PostService.java index 0c3dd1c..bd844f5 100644 --- a/src/main/java/net/skhu/likelion12thteam03be/post/application/PostService.java +++ b/src/main/java/net/skhu/likelion12thteam03be/post/application/PostService.java @@ -16,8 +16,6 @@ import net.skhu.likelion12thteam03be.s3.S3Service; import net.skhu.likelion12thteam03be.user.domain.User; import net.skhu.likelion12thteam03be.user.domain.repository.UserRepository; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; @@ -40,24 +38,12 @@ public class PostService { @Transactional public void postSave(PostSaveReqDto postSaveReqDto, MultipartFile multipartFile, Principal principal) throws IOException { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null || !authentication.isAuthenticated()) { - throw new IllegalArgumentException("인증되지 않은 사용자입니다."); - } - String loginId = authentication.getName(); - System.out.println("In PostService : loginId = " + loginId); String imgUrl = s3Service.upload(multipartFile, "post"); -/* System.out.println("---------------------------"); - System.out.println(principal.getName()); - System.out.println("---------------------------");*/ -// String LoginId = principal.getName(); -// Long id = Long.parseLong(principal.getName()); - - /*User user = userRepository.findById(id) - .orElseThrow(() -> new IllegalArgumentException("해당 사용자가 존재하지 않습니다. id = " + id));*/ + String loginId = principal.getName(); User user = userRepository.findByLoginId(loginId) - .orElseThrow(() -> new IllegalArgumentException("해당 사용자가 존재하지 않습니다. LoginId = " + loginId)); + .orElseThrow(() -> new IllegalArgumentException("User not found with id = " + loginId)); + Location location = locationRepository.findById(postSaveReqDto.locationId()) .orElseThrow(() -> new IllegalArgumentException("해당 위치가 존재하지 않습니다. locationId = " + postSaveReqDto.locationId())); @@ -69,7 +55,6 @@ public void postSave(PostSaveReqDto postSaveReqDto, MultipartFile multipartFile, .orElseThrow(() -> new IllegalArgumentException("해당 분위기가 존재하지 않습니다. moodId = " + postSaveReqDto.moodId())); Post post = Post.builder() - .user(user) .title(postSaveReqDto.title()) .content(postSaveReqDto.content()) .location(location) @@ -78,6 +63,7 @@ public void postSave(PostSaveReqDto postSaveReqDto, MultipartFile multipartFile, .category(category) .mood(mood) .imgUrl(imgUrl) + .user(user) .build(); postRepository.save(post); @@ -158,13 +144,20 @@ public PostListResDto postFindByUserId(Long userId) { // 글 수정 @Transactional - public void postUpdate(Long postId, PostUpdateReqDto postUpdateReqDto, MultipartFile multipartFile) throws IOException { + public void postUpdate(Long postId, PostUpdateReqDto postUpdateReqDto, MultipartFile multipartFile, Principal principal) throws IOException { Post post = postRepository.findById(postId).orElseThrow( () -> new IllegalArgumentException("해당 글을 수정할 수 없습니다. postId = " + postId) ); + String loginId = principal.getName(); + User currentUser = userRepository.findByLoginId(loginId) + .orElseThrow(() -> new IllegalArgumentException("현재 사용자 정보를 찾을 수 없습니다. username = " + loginId)); + if (!post.getUser().getLoginId().equals(currentUser.getLoginId())) { + throw new SecurityException("이 글을 수정할 권한이 없습니다."); + } + Location location = locationRepository.findById(postUpdateReqDto.locationId()) - .orElseThrow(() -> new IllegalArgumentException("해당 위치가 존재하지 않습니다. locationId = " + postUpdateReqDto.locationId())); + .orElseThrow(() -> new IllegalArgumentException("해당 위치가 존재하지 않습니다. locationId = " + postUpdateReqDto.locationId())); Category category = categoryRepository.findById(postUpdateReqDto.categoryId()) .orElseThrow(() -> new IllegalArgumentException("해당 카테고리가 존재하지 않습니다. categoryId = " + postUpdateReqDto.categoryId())); @@ -175,16 +168,21 @@ public void postUpdate(Long postId, PostUpdateReqDto postUpdateReqDto, Multipart String imgUrl = s3Service.upload(multipartFile, "post"); post.update(location, category, postUpdateReqDto, mood, imgUrl); - PostInfoResDto.from(post); + postRepository.save(post); } // 글 삭제 @Transactional - public void postDelete(Long postId) throws IOException { + public void postDelete(Long postId, Principal principal) throws IOException { Post post = postRepository.findById(postId).orElseThrow( () -> new IllegalArgumentException("해당 글을 삭제할 수 없습니다. postId = " + postId) ); - + String loginId = principal.getName(); + User currentUser = userRepository.findByLoginId(loginId) + .orElseThrow(()-> new IllegalArgumentException("현재 사용자 정보를 찾을 수 없습니다. username = " + loginId)); + if (!post.getUser().getLoginId().equals(currentUser.getLoginId())) { + throw new SecurityException("이 글을 삭제할 권한이 없습니다."); + } Optional imgUrl = Optional.ofNullable(post.getImgUrl()); imgUrl.ifPresentOrElse( @@ -192,7 +190,7 @@ public void postDelete(Long postId) throws IOException { try { s3Service.delete(url, "post"); } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("이미지 삭제 중 오류 발생", e); + throw new IllegalArgumentException("이미지 삭제 중 오류 발 생", e); } postRepository.delete(post); }, diff --git a/src/main/java/net/skhu/likelion12thteam03be/post/domain/Post.java b/src/main/java/net/skhu/likelion12thteam03be/post/domain/Post.java index 068a2b6..6f4915c 100644 --- a/src/main/java/net/skhu/likelion12thteam03be/post/domain/Post.java +++ b/src/main/java/net/skhu/likelion12thteam03be/post/domain/Post.java @@ -18,25 +18,25 @@ public class Post extends Time { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "post_id") + @Column(name = "postId") private Long postId; private String title; // 제목 private String content; // 내용 @ManyToOne - @JoinColumn(name = "location_id") + @JoinColumn(name = "locationId") private Location location; // 거래 장소 private Integer time; // 거래 시간 private Integer price; // 가격 @ManyToOne - @JoinColumn(name = "category_id") + @JoinColumn(name = "categoryId") private Category category; @ManyToOne - @JoinColumn(name = "mood_id") + @JoinColumn(name = "moodId") private Mood mood; // 감정 키워드 private String imgUrl; // 사진 @@ -46,8 +46,7 @@ public class Post extends Time { private User user; @Builder - public Post(User user, String title, String content, Location location, Integer time, Integer price, Category category, Mood mood, String imgUrl) { - this.user = user; + public Post(String title, String content, Location location, Integer time, Integer price, Category category, Mood mood, String imgUrl, User user) { this.title = title; this.content = content; this.location = location; @@ -56,6 +55,7 @@ public Post(User user, String title, String content, Location location, Integer this.category = category; this.mood = mood; this.imgUrl = imgUrl; + this.user = user; } public void update(Location location, Category category, PostUpdateReqDto postUpdateReqDto, Mood mood, String imgUrl) { diff --git a/src/main/java/net/skhu/likelion12thteam03be/user/domain/User.java b/src/main/java/net/skhu/likelion12thteam03be/user/domain/User.java index 0bc2153..863973e 100644 --- a/src/main/java/net/skhu/likelion12thteam03be/user/domain/User.java +++ b/src/main/java/net/skhu/likelion12thteam03be/user/domain/User.java @@ -41,13 +41,12 @@ public class User { private List posts = new ArrayList<>(); @Builder - public User(String loginId, String password, String nickname, Role role, List surveys) { + public User(String loginId, String password, String nickname, Role role) { validateNickname(nickname); this.loginId = loginId; this.password = password; this.nickname = nickname; this.role = role; - this.surveys = surveys; } private void validateNickname(String nickname) { diff --git a/src/main/resources/templates/user.html b/src/main/resources/templates/user.html new file mode 100644 index 0000000..2bc99e3 --- /dev/null +++ b/src/main/resources/templates/user.html @@ -0,0 +1,10 @@ + + + + + userHello + + +/users 했을 때 들어오게 되는 페이지 + + \ No newline at end of file