Skip to content

Commit 43f5670

Browse files
committed
feat: user login using session #29
1 parent 04f4058 commit 43f5670

File tree

1 file changed

+42
-5
lines changed

1 file changed

+42
-5
lines changed

backend/src/main/java/com/example/backend/user/controller/UserController.java

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,60 @@
33
import com.example.backend.user.dto.UserRequestDto;
44
import com.example.backend.user.dto.UserResponseDto;
55
import com.example.backend.user.service.UserService;
6+
import jakarta.servlet.http.HttpSession;
7+
import org.springframework.http.ResponseEntity;
68
import org.springframework.web.bind.annotation.*;
79

10+
import java.util.Collections;
11+
812
@RestController
913
@RequestMapping("/api/v1")
1014
public class UserController {
1115

1216
private final UserService userService;
1317

14-
// userService를 주입받아서 사용
1518
public UserController(UserService userService) {
1619
this.userService = userService;
1720
}
1821

1922
@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+
}
2438
}
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+
2562
}

0 commit comments

Comments
 (0)