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 03566ed..9e1ebe5 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 @@ -4,6 +4,8 @@ import com.edufocus.edufocus.user.model.entity.InfoDto; import com.edufocus.edufocus.user.model.entity.PasswordDto; import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.exception.ExpriedTokenException; +import com.edufocus.edufocus.user.model.exception.InvalidTokenException; +import com.edufocus.edufocus.user.model.exception.RefreshTokenExpiredException; import com.edufocus.edufocus.user.model.exception.UnAuthorizedException; import com.edufocus.edufocus.user.model.service.UserService; import com.edufocus.edufocus.user.util.JWTUtil; @@ -122,35 +124,6 @@ public class UserController { return new ResponseEntity<>(resultMap, status); } - @Operation(summary = "회원인증", description = "회원 정보를 담은 Token 을 반환한다.") - @GetMapping("/auth/{userId}") - public ResponseEntity> getInfo( - @PathVariable("userId") @Parameter(description = "인증할 회원의 아이디.", required = true) Long userId, - HttpServletRequest request) { - String id = String.valueOf(userId); - - - 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); - } @PostMapping("/logout") public ResponseEntity removeToken(HttpServletRequest request) { @@ -166,7 +139,7 @@ public class UserController { } catch (Exception e) { log.error("로그아웃 실패 : {}", e); resultMap.put("message", e.getMessage()); - status = HttpStatus.INTERNAL_SERVER_ERROR; + status = HttpStatus.UNAUTHORIZED; } return new ResponseEntity>(resultMap, status); } @@ -175,14 +148,8 @@ public class UserController { @PostMapping("/refresh") public ResponseEntity refreshToken(HttpServletRequest request,HttpServletResponse response) throws Exception { - - - Map resultMap = new HashMap<>(); - HttpStatus status = HttpStatus.ACCEPTED; - Cookie[] cookies = request.getCookies(); String token = null; - if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("refresh-token")) { @@ -191,41 +158,36 @@ public class UserController { } } } + + try{ + jwtUtil.checkToken(token); + }catch (Exception e){ + throw new InvalidTokenException(); + } + Long userId = Long.parseLong(jwtUtil.getUserId(token)); - if (jwtUtil.checkToken(token)) { - - - if (token.equals(userService.getRefreshToken(userId))) { - - String accessToken = jwtUtil.createAccessToken(String.valueOf(userId)); - String refreshToken = jwtUtil.createRefreshToken(String.valueOf(userId)); - - log.debug("token : {}", accessToken); - log.debug("정상적으로 access token 재발급!!!"); - resultMap.put("access-token", accessToken); - - - - 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; - - } - } else { - log.debug("refresh token 도 사용 불가!!!!!!!"); - status = HttpStatus.UNAUTHORIZED; + if (!token.equals(userService.getRefreshToken(userId))) { + throw new InvalidTokenException(); } - return new ResponseEntity>(resultMap, status); + + + String accessToken = jwtUtil.createAccessToken(String.valueOf(userId)); + String refreshToken = jwtUtil.createRefreshToken(String.valueOf(userId)); + + + Map resultMap = new HashMap<>(); + resultMap.put("access-token", accessToken); + + userService.saveRefreshToken(userId,refreshToken); + + Cookie refreshCookie = new Cookie("refresh-token", refreshToken); + refreshCookie.setPath("/"); + refreshCookie.setHttpOnly(true); + refreshCookie.setSecure(true); + response.addCookie(refreshCookie); + + return new ResponseEntity>(resultMap, HttpStatus.CREATED); } @Operation(summary = "회원 정보 조회", description = "토큰을 이용하여 회원 정보를 조회한다.") @@ -268,4 +230,4 @@ public class UserController { -} +} \ No newline at end of file diff --git a/backend/src/main/java/com/edufocus/edufocus/user/intercepter/JWTInterceptor.java b/backend/src/main/java/com/edufocus/edufocus/user/intercepter/JWTInterceptor.java index fc741dc..c1c6003 100644 --- a/backend/src/main/java/com/edufocus/edufocus/user/intercepter/JWTInterceptor.java +++ b/backend/src/main/java/com/edufocus/edufocus/user/intercepter/JWTInterceptor.java @@ -24,17 +24,11 @@ public class JWTInterceptor implements HandlerInterceptor { } @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){ final String token = request.getHeader(HEADER_AUTH); - if (token != null && jwtUtil.checkToken(token)) { - log.info("토큰 사용 가능 : {}", token); - return true; - } else { - log.info("토큰 사용 불가능 : {}", token); - throw new UnAuthorizedException(); - } + jwtUtil.checkToken(token); + return true; } } \ No newline at end of file diff --git a/backend/src/main/java/com/edufocus/edufocus/user/model/exception/GlobalExceptionHandler.java b/backend/src/main/java/com/edufocus/edufocus/user/model/exception/GlobalExceptionHandler.java index 63355d3..21c3a22 100644 --- a/backend/src/main/java/com/edufocus/edufocus/user/model/exception/GlobalExceptionHandler.java +++ b/backend/src/main/java/com/edufocus/edufocus/user/model/exception/GlobalExceptionHandler.java @@ -9,17 +9,14 @@ import org.springframework.web.bind.annotation.ExceptionHandler; public class GlobalExceptionHandler { @ExceptionHandler(InvalidTokenException.class) - public ResponseEntity handleUnAuthorizedException(InvalidTokenException e) { - - - + public ResponseEntity handleInvalidTokenException(InvalidTokenException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } - + // @ExceptionHandler(ExpriedTokenException.class) - public ResponseEntity handleInvalidTokenException(ExpriedTokenException e) { - + public ResponseEntity handleExpiredTokenException(ExpriedTokenException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED); } -} + +} \ No newline at end of file diff --git a/backend/src/main/java/com/edufocus/edufocus/user/model/exception/RefreshTokenExpiredException.java b/backend/src/main/java/com/edufocus/edufocus/user/model/exception/RefreshTokenExpiredException.java new file mode 100644 index 0000000..8a1dd14 --- /dev/null +++ b/backend/src/main/java/com/edufocus/edufocus/user/model/exception/RefreshTokenExpiredException.java @@ -0,0 +1,9 @@ +package com.edufocus.edufocus.user.model.exception; + +public class RefreshTokenExpiredException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public RefreshTokenExpiredException() { + super("REFRESH TOKEN 만료\n다시 로그인을 하세요."); + } +} 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 a5e4964..e7d4f8c 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 @@ -6,6 +6,7 @@ import java.util.Map; import com.edufocus.edufocus.user.model.exception.ExpriedTokenException; import com.edufocus.edufocus.user.model.exception.InvalidTokenException; +import com.edufocus.edufocus.user.model.exception.RefreshTokenExpiredException; import com.edufocus.edufocus.user.model.exception.UnAuthorizedException; import io.jsonwebtoken.*; import org.springframework.beans.factory.annotation.Value; @@ -54,30 +55,21 @@ public class JWTUtil { public boolean checkToken(String token) { try { - Jws claims = Jwts.parserBuilder() - .setSigningKey(generateKey()) - .build() - .parseClaimsJws(token); - log.debug("claims: {}", claims); - return true; - } catch (MalformedJwtException | UnsupportedJwtException | IllegalArgumentException | SignatureException e) { - log.error("Token validation error: {}", e.getMessage()); - - return false; - } - catch ( ExpiredJwtException e) - { - throw new ExpriedTokenException(); - - } - catch (Exception e) { - System.out.println(token); - System.out.println(e.getMessage()); - log.error("Unexpected error while validating token: {}", e.getMessage()); + Jws claims = Jwts.parserBuilder() + .setSigningKey(generateKey()) + .build() + .parseClaimsJws(token); + log.debug("claims: {}", claims); + return true; + } + catch (ExpriedTokenException e) { + throw new ExpriedTokenException(); + }catch (Exception e){ throw new InvalidTokenException(); } } + public String getUserId(String authorization) { try { Jws claims = Jwts.parserBuilder() @@ -98,4 +90,4 @@ public class JWTUtil { throw new InvalidTokenException(); } } -} +} \ No newline at end of file diff --git a/backend/src/main/java/com/edufocus/edufocus/video/controller/Controller.java b/backend/src/main/java/com/edufocus/edufocus/video/controller/Controller.java index 363f9f1..a94758e 100644 --- a/backend/src/main/java/com/edufocus/edufocus/video/controller/Controller.java +++ b/backend/src/main/java/com/edufocus/edufocus/video/controller/Controller.java @@ -108,18 +108,21 @@ public class Controller { Random random = new Random(); System.out.println(); - int randomNumber = 100 + random.nextInt(9000); + int randomNumber = 10000 + random.nextInt(80000); String randStr = String.valueOf(randomNumber); + String roomName = lecture.getTitle(); + String participantName = userService.getUserName(userId); + System.out.println(participantName); + + AccessToken token = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET); + if(findUser.getRole()==UserRole.ADMIN ){//&& lecture.isOnline() ) { - String roomName = lecture.getTitle(); - String participantName = userService.getUserName(userId); - AccessToken token = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET); IdentityData identityData = new IdentityData(participantName, "강사"); String jsonIdentity = serializeIdentityData(identityData); @@ -141,13 +144,7 @@ public class Controller { { - String roomName = lecture.getTitle(); - String participantName = userService.getUserName(userId); - System.out.println(participantName); - - AccessToken token = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET); - - IdentityData identityData = new IdentityData(participantName, "강사"); + IdentityData identityData = new IdentityData(participantName, "학생"); String jsonIdentity = serializeIdentityData(identityData); diff --git a/backend/src/main/resources/application.properties b/backend/src/main/resources/application.properties index 58d6582..0f03472 100644 --- a/backend/src/main/resources/application.properties +++ b/backend/src/main/resources/application.properties @@ -16,10 +16,12 @@ livekit.api.secret=${LIVEKIT_API_SECRET:secret} jwt.salt=${SALT} # Access Token ?? ?? (??? ??) -jwt.access-token.expiretime=3600000 +#jwt.access-token.expiretime=3600000 +jwt.access-token.expiretime=3000 # Refresh Token ?? ?? (??? ??) -jwt.refresh-token.expiretime=86400000 +jwt.refresh-token.expiretime=50400000 +#jwt.refresh-token.expiretime=4000 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=${DATA_SOURCE_URL} spring.datasource.username=${USER_NAME}