|
3 | 3 | import com.example.backend.user.dto.UserRequestDto; |
4 | 4 | import com.example.backend.user.dto.UserResponseDto; |
5 | 5 | import com.example.backend.user.service.UserService; |
| 6 | +import jakarta.servlet.http.HttpSession; |
| 7 | +import org.springframework.http.ResponseEntity; |
6 | 8 | import org.springframework.web.bind.annotation.*; |
7 | 9 |
|
| 10 | +import java.util.Collections; |
| 11 | + |
8 | 12 | @RestController |
9 | 13 | @RequestMapping("/api/v1") |
10 | 14 | public class UserController { |
11 | 15 |
|
12 | 16 | private final UserService userService; |
13 | 17 |
|
14 | | - // userService를 주입받아서 사용 |
15 | 18 | public UserController(UserService userService) { |
16 | 19 | this.userService = userService; |
17 | 20 | } |
18 | 21 |
|
19 | 22 | @PostMapping("/auth") |
20 | | - // RequestBody의 데이터를 UserRequestDto 객체로 변환해서 받음 |
21 | | - public UserResponseDto authenticate(@RequestBody UserRequestDto requestDto) { |
22 | | - // 메서드 수행 결과 반환 |
23 | | - return userService.authenticate(requestDto); |
| 23 | + public ResponseEntity<?> authenticate(@RequestBody UserRequestDto requestDto, HttpSession session) { |
| 24 | + try { |
| 25 | + UserResponseDto userResponse = userService.authenticate(requestDto); |
| 26 | + |
| 27 | + // 세션에 사용자 정보 저장 |
| 28 | + session.setAttribute("user", userResponse); |
| 29 | + |
| 30 | + return ResponseEntity.ok(userResponse); // 200 OK |
| 31 | + } catch (IllegalArgumentException e) { // 400 Bad Request |
| 32 | + return ResponseEntity.status(400) |
| 33 | + .body(Collections.singletonMap("message", e.getMessage())); |
| 34 | + } catch (Exception e) { // 서버 에러 |
| 35 | + return ResponseEntity.status(500) |
| 36 | + .body(Collections.singletonMap("message", "내부 서버 오류가 발생했습니다.")); |
| 37 | + } |
24 | 38 | } |
| 39 | + |
| 40 | + |
| 41 | + // 세션에 저장된 로그인 정보 확인 |
| 42 | + @GetMapping("/session") |
| 43 | + public ResponseEntity<?> getSessionUser(HttpSession session) { |
| 44 | + try { |
| 45 | + // 세션에서 사용자 정보 가져오기 |
| 46 | + UserResponseDto user = (UserResponseDto) session.getAttribute("user"); |
| 47 | + |
| 48 | + if (user == null) { |
| 49 | + // 사용자 정보가 없으면 404 상태 코드 반환 |
| 50 | + return ResponseEntity.status(404) |
| 51 | + .body(Collections.singletonMap("message", "사용자가 존재하지 않습니다.")); |
| 52 | + } |
| 53 | + return ResponseEntity.ok(user); |
| 54 | + } catch (Exception e) { |
| 55 | + // 기타 예외 처리 시 500 상태 코드 반환 (서버 에러) |
| 56 | + return ResponseEntity.status(500) |
| 57 | + .body(Collections.singletonMap("message", "내부 서버 오류가 발생했습니다.")); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + |
25 | 62 | } |
0 commit comments