From f127eae148742bbcde88ba9ea7dc2183ba31bac2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EC=A0=95=EB=AF=BC?= Date: Thu, 18 Jul 2024 14:27:11 +0900 Subject: [PATCH] feat: login --- .../user/controller/UserController.java | 110 +++++++++++++++++- .../user/model/service/UserService.java | 8 +- .../user/model/service/UserServiceImpl.java | 14 +++ .../edufocus/edufocus/user/util/JWTUtil.java | 11 +- 4 files changed, 130 insertions(+), 13 deletions(-) diff --git a/backend/src/main/java/com/edufocus/edufocus/user/controller/UserController.java b/backend/src/main/java/com/edufocus/edufocus/user/controller/UserController.java index e96b6f4..9689880 100644 --- a/backend/src/main/java/com/edufocus/edufocus/user/controller/UserController.java +++ b/backend/src/main/java/com/edufocus/edufocus/user/controller/UserController.java @@ -5,15 +5,13 @@ import com.edufocus.edufocus.user.model.service.UserService; import com.edufocus.edufocus.user.util.JWTUtil; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; @@ -63,6 +61,7 @@ public class UserController { userService.saveRefreshToken(loginUser.getId(), refreshToken); // JSON 으로 token 전달. + System.out.println(accessToken); resultMap.put("access-token", accessToken); resultMap.put("refresh-token", refreshToken); @@ -78,6 +77,109 @@ public class UserController { return new ResponseEntity<>(resultMap, status); } + @Operation(summary = "회원인증", description = "회원 정보를 담은 Token 을 반환한다.") + @GetMapping("/info/{userId}") + public ResponseEntity> getInfo( + @PathVariable("userId") @Parameter(description = "인증할 회원의 아이디.", required = true) Long userId, + HttpServletRequest request) { + //logger.debug("userId : {} ", userId); + String id = String.valueOf(userId); + + System.out.println("!>>>>>>>>>>>>>>>>>>>>>>>>"); + System.out.println(id); + System.out.println(id.getClass().getName()); + Map resultMap = new HashMap<>(); + HttpStatus status = HttpStatus.ACCEPTED; + if (jwtUtil.checkToken(request.getHeader("Authorization"))) { + log.info("사용 가능한 토큰!!!"); + try { +// 로그인 사용자 정보. + User member = userService.userInfo(userId); + resultMap.put("userInfo", member); + status = HttpStatus.OK; + } catch (Exception e) { + log.error("정보조회 실패 : {}", e); + resultMap.put("message", e.getMessage()); + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } else { + System.out.println(jwtUtil.checkToken(request.getHeader("Authorization"))); + log.error("사용 불가능 토큰!!!"); + resultMap.put("message", "Unauthorized token"); + status = HttpStatus.UNAUTHORIZED; + } + return new ResponseEntity>(resultMap, status); + } + + @GetMapping("/logout/{userId}") + + public ResponseEntity removeToken(@PathVariable ("userId") @Parameter(description = "로그아웃 할 회원의 아이디.", required = true) Long userId) { + Map resultMap = new HashMap<>(); + HttpStatus status = HttpStatus.ACCEPTED; + try { + userService.deleteRefreshToken(userId); + status = HttpStatus.OK; + } catch (Exception e) { + log.error("로그아웃 실패 : {}", e); + resultMap.put("message", e.getMessage()); + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + return new ResponseEntity>(resultMap, status); + } + + @Operation(summary = "Access Token 재발급", description = "만료된 access token 을 재발급 받는다.") + @PostMapping("/refresh") + public ResponseEntity refreshToken(@RequestBody User user, HttpServletRequest request) + throws Exception { + Map resultMap = new HashMap<>(); + HttpStatus status = HttpStatus.ACCEPTED; + String token = request.getHeader("refreshToken"); + log.debug("token : {}, memberDto : {}", token, user); + if (jwtUtil.checkToken(token)) { + if (token.equals(userService.getRefreshToken(user.getId()))) { + String accessToken = jwtUtil.createAccessToken(String.valueOf(user.getId())); + log.debug("token : {}", accessToken); + log.debug("정상적으로 access token 재발급!!!"); + resultMap.put("access-token", accessToken); + status = HttpStatus.CREATED; + } + } else { + log.debug("refresh token 도 사용 불가!!!!!!!"); + status = HttpStatus.UNAUTHORIZED; + } + return new ResponseEntity>(resultMap, status); + } + + @Operation(summary = "회원 정보 조회", description = "토큰을 이용하여 회원 정보를 조회한다.") + @GetMapping("/member") + public ResponseEntity> getMember(HttpServletRequest request) { + Map resultMap = new HashMap<>(); + HttpStatus status = HttpStatus.ACCEPTED; + String token = request.getHeader("Authorization"); + + if (jwtUtil.checkToken(token)) { + String userId = jwtUtil.getUserId(token); + log.info("사용 가능한 토큰!!! userId: {}", userId); + try { + User user = userService.userInfo(Long.parseLong(userId)); + resultMap.put("userInfo", user); + status = HttpStatus.OK; + + } catch (Exception e) { + log.error("정보조회 실패 : {}", e); + resultMap.put("message", e.getMessage()); + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } else { + log.error("사용 불가능 토큰!!!"); + status = HttpStatus.UNAUTHORIZED; + } + return new ResponseEntity>(resultMap, status); + } + + + + } diff --git a/backend/src/main/java/com/edufocus/edufocus/user/model/service/UserService.java b/backend/src/main/java/com/edufocus/edufocus/user/model/service/UserService.java index cf6353d..3ba4454 100644 --- a/backend/src/main/java/com/edufocus/edufocus/user/model/service/UserService.java +++ b/backend/src/main/java/com/edufocus/edufocus/user/model/service/UserService.java @@ -5,8 +5,8 @@ import com.edufocus.edufocus.user.model.entity.User; public interface UserService { void join(User user) throws Exception; User login(User user) throws Exception; - public void saveRefreshToken(Long id, String refreshToken) throws Exception; - public String getRefreshToken(Long id) throws Exception; - public void deleteRefreshToken(Long id) throws Exception; - + void saveRefreshToken(Long id, String refreshToken) throws Exception; + String getRefreshToken(Long id) throws Exception; + void deleteRefreshToken(Long id) throws Exception; + User userInfo(Long id) throws Exception; } diff --git a/backend/src/main/java/com/edufocus/edufocus/user/model/service/UserServiceImpl.java b/backend/src/main/java/com/edufocus/edufocus/user/model/service/UserServiceImpl.java index 50bb07e..0f70838 100644 --- a/backend/src/main/java/com/edufocus/edufocus/user/model/service/UserServiceImpl.java +++ b/backend/src/main/java/com/edufocus/edufocus/user/model/service/UserServiceImpl.java @@ -28,6 +28,7 @@ public class UserServiceImpl implements UserService{ userRepository.save(user); } + public User login(User user) throws SQLException { Optional findUser = userRepository.findByUserId(user.getUserId()); @@ -59,6 +60,19 @@ public class UserServiceImpl implements UserService{ } + } + + @Override + public User userInfo(Long id) + { + try{ + return userRepository.findById(id).get(); + } + catch (Exception e) + { + throw new UserException(e.getMessage()); + } + } @Override public void saveRefreshToken(Long id, String refreshToken) throws Exception { diff --git a/backend/src/main/java/com/edufocus/edufocus/user/util/JWTUtil.java b/backend/src/main/java/com/edufocus/edufocus/user/util/JWTUtil.java index 1d0f98d..ead01db 100644 --- a/backend/src/main/java/com/edufocus/edufocus/user/util/JWTUtil.java +++ b/backend/src/main/java/com/edufocus/edufocus/user/util/JWTUtil.java @@ -5,13 +5,10 @@ import java.util.Date; import java.util.Map; import com.edufocus.edufocus.user.model.exception.UnAuthorizedException; +import io.jsonwebtoken.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jws; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; import lombok.extern.slf4j.Slf4j; @Component @@ -61,9 +58,13 @@ public class JWTUtil { .parseClaimsJws(token); log.debug("claims: {}", claims); return true; - } catch (Exception e) { + } catch (MalformedJwtException | UnsupportedJwtException | IllegalArgumentException | SignatureException | ExpiredJwtException e) { log.error("Token validation error: {}", e.getMessage()); return false; + } catch (Exception e) { + System.out.println(token); + log.error("Unexpected error while validating token: {}", e.getMessage()); + return false; } }