Merge pull request #47 from TeamBNBN/BE/user

feat: login
This commit is contained in:
김기창 2024-07-18 16:34:51 +09:00 committed by GitHub
commit 7b7b48cd1b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 66 additions and 10 deletions

View File

@ -22,6 +22,8 @@ public class LectureController {
@PostMapping @PostMapping
public ResponseEntity<?> createLecture (@RequestBody long userId, LectureRegist lectureRegist) { public ResponseEntity<?> createLecture (@RequestBody long userId, LectureRegist lectureRegist) {
System.out.println("@@@@@@@@@@@@@@@@@@>>>>>>>>>>>>>>>>>>>>>> "+userId); System.out.println("@@@@@@@@@@@@@@@@@@>>>>>>>>>>>>>>>>>>>>>> "+userId);
// 여기서 id 로직
lectureService.createLecture(userId, lectureRegist); lectureService.createLecture(userId, lectureRegist);
return new ResponseEntity<>(HttpStatus.CREATED); return new ResponseEntity<>(HttpStatus.CREATED);
} }

View File

@ -5,7 +5,9 @@ import com.edufocus.edufocus.user.model.service.UserService;
import com.edufocus.edufocus.user.util.JWTUtil; import com.edufocus.edufocus.user.util.JWTUtil;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -48,7 +50,7 @@ public class UserController {
@Operation(summary = "로그인", description = "아이디와 비밀번호를 이용하여 로그인 처리.") @Operation(summary = "로그인", description = "아이디와 비밀번호를 이용하여 로그인 처리.")
@PostMapping("/login") @PostMapping("/login")
public ResponseEntity<Map<String, Object>> login( public ResponseEntity<Map<String, Object>> login(
@RequestBody @Parameter(description = "로그인 시 필요한 회원정보(아이디, 비밀번호).", required = true) User user) { @RequestBody @Parameter(description = "로그인 시 필요한 회원정보(아이디, 비밀번호).", required = true) User user, HttpServletResponse response) {
Map<String, Object> resultMap = new HashMap<>(); Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED; HttpStatus status = HttpStatus.ACCEPTED;
try { try {
@ -63,8 +65,18 @@ public class UserController {
// JSON 으로 token 전달. // JSON 으로 token 전달.
System.out.println(accessToken); System.out.println(accessToken);
resultMap.put("access-token", accessToken); resultMap.put("access-token", accessToken);
resultMap.put("refresh-token", refreshToken); // resultMap.put("refresh-token", refreshToken);
// 쿠키 저장
Cookie refreshCookie = new Cookie("refresh-token", refreshToken);
refreshCookie.setPath("/");
refreshCookie.setHttpOnly(true);
refreshCookie.setSecure(true); // HTTPS에서만 전송되도록 설정
// refreshCookie.setSameSite(Cookie.SameSite.NONE); // Cross-Origin 요청에 대해 모두 전송
response.addCookie(refreshCookie);
// 쿠키저장
status = HttpStatus.CREATED; status = HttpStatus.CREATED;
} else { } else {
resultMap.put("message", "아이디 또는 패스워드를 확인해 주세요."); resultMap.put("message", "아이디 또는 패스워드를 확인해 주세요.");
@ -78,7 +90,7 @@ public class UserController {
} }
@Operation(summary = "회원인증", description = "회원 정보를 담은 Token 을 반환한다.") @Operation(summary = "회원인증", description = "회원 정보를 담은 Token 을 반환한다.")
@GetMapping("/info/{userId}") @GetMapping("/auth/{userId}")
public ResponseEntity<Map<String, Object>> getInfo( public ResponseEntity<Map<String, Object>> getInfo(
@PathVariable("userId") @Parameter(description = "인증할 회원의 아이디.", required = true) Long userId, @PathVariable("userId") @Parameter(description = "인증할 회원의 아이디.", required = true) Long userId,
HttpServletRequest request) { HttpServletRequest request) {
@ -129,19 +141,62 @@ public class UserController {
@Operation(summary = "Access Token 재발급", description = "만료된 access token 을 재발급 받는다.") @Operation(summary = "Access Token 재발급", description = "만료된 access token 을 재발급 받는다.")
@PostMapping("/refresh") @PostMapping("/refresh")
public ResponseEntity<?> refreshToken(@RequestBody User user, HttpServletRequest request) public ResponseEntity<?> refreshToken(HttpServletRequest request,HttpServletResponse response)
throws Exception { throws Exception {
// System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@");
// System.out.println(user.getUserId());
Map<String, Object> resultMap = new HashMap<>(); Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED; HttpStatus status = HttpStatus.ACCEPTED;
String token = request.getHeader("refreshToken");
log.debug("token : {}, memberDto : {}", token, user); // String token = request.getHeader("refreshToken");
Cookie[] cookies = request.getCookies();
String token = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("refresh-token")) {
token = cookie.getValue();
break;
}
}
}
Long userId = Long.parseLong(jwtUtil.getUserId(token));
/// System.out.println(userId);
/// System.out.println("리프레쉬 토큰 (쿠키에서 받은거 "+token);
// log.debug("token : {}, memberDto : {}", token, user);
// System.out.println(jwtUtil.checkToken(token));
if (jwtUtil.checkToken(token)) { if (jwtUtil.checkToken(token)) {
if (token.equals(userService.getRefreshToken(user.getId()))) {
String accessToken = jwtUtil.createAccessToken(String.valueOf(user.getId())); // System.out.println(token);
// System.out.println(userService.getRefreshToken(userId));
//System.out.println("쿠키 토큰 , 디비 토큰 비교"+token.equals(userService.getRefreshToken(userId)));
if (token.equals(userService.getRefreshToken(userId))) {
System.out.println("!!");
String accessToken = jwtUtil.createAccessToken(String.valueOf(userId));
String refreshToken = jwtUtil.createRefreshToken(String.valueOf(userId));
log.debug("token : {}", accessToken); log.debug("token : {}", accessToken);
log.debug("정상적으로 access token 재발급!!!"); log.debug("정상적으로 access token 재발급!!!");
resultMap.put("access-token", accessToken); resultMap.put("access-token", accessToken);
// 바뀐 리프레시db저장
userService.saveRefreshToken(userId,refreshToken);
// 쿠키 저장
Cookie refreshCookie = new Cookie("refresh-token", refreshToken);
refreshCookie.setPath("/");
refreshCookie.setHttpOnly(true);
refreshCookie.setSecure(true); // HTTPS에서만 전송되도록 설정
// refreshCookie.setSameSite(Cookie.SameSite.NONE); // Cross-Origin 요청에 대해 모두 전송
response.addCookie(refreshCookie);
System.out.println("바뀐 리프레쉬랑 지금꺼 비교 "+ refreshToken.equals(token));
resultMap.put("access-token", accessToken);
status = HttpStatus.CREATED; status = HttpStatus.CREATED;
} }
} else { } else {
log.debug("refresh token 도 사용 불가!!!!!!!"); log.debug("refresh token 도 사용 불가!!!!!!!");
@ -151,7 +206,7 @@ public class UserController {
} }
@Operation(summary = "회원 정보 조회", description = "토큰을 이용하여 회원 정보를 조회한다.") @Operation(summary = "회원 정보 조회", description = "토큰을 이용하여 회원 정보를 조회한다.")
@GetMapping("/member") @GetMapping("/userinfo")
public ResponseEntity<Map<String, Object>> getMember(HttpServletRequest request) { public ResponseEntity<Map<String, Object>> getMember(HttpServletRequest request) {
Map<String, Object> resultMap = new HashMap<>(); Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED; HttpStatus status = HttpStatus.ACCEPTED;

View File

@ -30,7 +30,6 @@ public class User {
private String password; private String password;
@Enumerated(EnumType.STRING) // 혹은 EnumType.ORDINAL @Enumerated(EnumType.STRING) // 혹은 EnumType.ORDINAL
private UserRole role; private UserRole role;
private String refreshToken; private String refreshToken;