(add, delete) Long user_id → Authentication authentication

backend-tobuy-adddish
zhang.pengcheng 5 months ago
parent 7d173a03dc
commit 88d927c3fe
  1. 23
      backend/src/main/java/com/example/todoapp/controller/ToBuysController.java
  2. 8
      backend/src/main/java/com/example/todoapp/service/ToBuysService.java

@ -52,8 +52,10 @@ public class ToBuysController {
*/
@PostMapping("/add")
public ResponseEntity<String> addToBuys(@Valid @RequestBody ToBuysDTO dto) {
toBuysService.addToBuys(dto);
public ResponseEntity<String> addToBuys(
@Valid @RequestBody ToBuysDTO dto,
Authentication authentication) {
toBuysService.addToBuys(dto, authentication);
return ResponseEntity.ok("Item added to 'To Buys' successfully");
}
@ -66,11 +68,10 @@ public class ToBuysController {
@GetMapping("/get")
public ResponseEntity<?> getAllToBuysByUserId(Authentication authentication) {
// 認証されたユーザー名を取得
String username = authentication.getName();
// ユーザー情報を取得(例: userRepository経由)
// ユーザー情報を取得
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
@ -102,8 +103,18 @@ public class ToBuysController {
* @return 削除が成功した場合にtrueを含むレスポンス
*/
@DeleteMapping("/delete")
public ResponseEntity<Map<String, Boolean>> deleteToBuy(@RequestBody DeleteToBuyRequest request) {
int deletedCount = toBuysService.deleteToBuyByIds(request.getUser_id(), request.getTobuy_id());
public ResponseEntity<Map<String, Boolean>> deleteToBuy(
@RequestBody DeleteToBuyRequest request,
Authentication authentication) {
// 認証されたユーザー名を取得
String username = authentication.getName();
// ユーザー情報を取得
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
int deletedCount = toBuysService.deleteToBuyByIds(user.getId(), request.getTobuy_id());
Map<String, Boolean> response = new HashMap<>();

@ -18,6 +18,7 @@ import com.example.todoapp.repository.UserRepository;
import jakarta.transaction.Transactional;
import org.springframework.security.core.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -50,11 +51,12 @@ public class ToBuysService {
*
* @param toBuyDTO 追加する購入アイテムのデータDTO
*/
public void addToBuys(ToBuysDTO toBuyDTO) {
public void addToBuys(ToBuysDTO toBuyDTO, Authentication authentication) {
// ユーザー情報を取得
User user = userRepository.findById(toBuyDTO.getUser_id())
.orElseThrow(() -> new RuntimeException("ユーザーがありませ: " + toBuyDTO.getUser_id()));
String username = authentication.getName();
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new RuntimeException("ユーザーが見つかりません: " + username));
Stuffs stuffs;
if (toBuyDTO.getStuff_id() == null) {

Loading…
Cancel
Save