Skip to content

Commit

Permalink
fix: post, postService 병합 충돌 해결
Browse files Browse the repository at this point in the history
  • Loading branch information
firefox1234123 committed Aug 1, 2024
2 parents c3fea5e + da5809d commit e09a908
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 45 deletions.
Original file line number Diff line number Diff line change
@@ -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";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -90,7 +90,9 @@ public Authentication getAuthentication(String token) {

User user = userRepository.findByLoginId(claims.getSubject()).orElseThrow();

return new UsernamePasswordAuthenticationToken(user.getLoginId(), "");
List<GrantedAuthority> authorities = List.of(new SimpleGrantedAuthority(user.getRole().toString()));
return new UsernamePasswordAuthenticationToken(user.getLoginId(),
"", authorities);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ public PostController(PostService postService) {

// 글 저장
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> postSave(@RequestPart("post") PostSaveReqDto postSaveReqDto, @RequestPart("imgUrl") MultipartFile imgUrl, Principal principal) throws IOException {
public ResponseEntity<String> 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);
}
Expand Down Expand Up @@ -77,15 +80,19 @@ public ResponseEntity<PostListResDto> postFindByUserId(@PathVariable("userId") L

// 글 수정
@PatchMapping("/{postId}")
public ResponseEntity<String> postUpdate(@PathVariable("postId") Long postId, @RequestPart("post") PostUpdateReqDto postUpdateReqDto, @RequestPart("imgUrl") MultipartFile imgUrl) throws IOException {
postService.postUpdate(postId, postUpdateReqDto, imgUrl);
public ResponseEntity<String> 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<String> postDelete(@PathVariable("postId") Long postId) throws IOException {
postService.postDelete(postId);
public ResponseEntity<String> postDelete(@PathVariable("postId") Long postId, Principal principal) throws IOException {
postService.postDelete(postId, principal);
return new ResponseEntity<>("Successful Post Delete", HttpStatus.OK);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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()));
Expand All @@ -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)
Expand All @@ -78,6 +63,7 @@ public void postSave(PostSaveReqDto postSaveReqDto, MultipartFile multipartFile,
.category(category)
.mood(mood)
.imgUrl(imgUrl)
.user(user)
.build();

postRepository.save(post);
Expand Down Expand Up @@ -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()));
Expand All @@ -175,24 +168,29 @@ 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<String> imgUrl = Optional.ofNullable(post.getImgUrl());

imgUrl.ifPresentOrElse(
url -> {
try {
s3Service.delete(url, "post");
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("이미지 삭제 중 오류 발생", e);
throw new IllegalArgumentException("이미지 삭제 중 오류 발 생", e);
}
postRepository.delete(post);
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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; // 사진
Expand All @@ -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;
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,12 @@ public class User {
private List<Post> posts = new ArrayList<>();

@Builder
public User(String loginId, String password, String nickname, Role role, List<Survey> 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) {
Expand Down
10 changes: 10 additions & 0 deletions src/main/resources/templates/user.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>userHello</title>
</head>
<body>
/users 했을 때 들어오게 되는 페이지
</body>
</html>

0 comments on commit e09a908

Please sign in to comment.