Merge pull request #145 from TeamBNBN/BE/userinfo

feat: refresh token 예외처리
This commit is contained in:
Jungmin 2024-07-30 17:36:10 +09:00 committed by GitHub
commit 94ff99ad14
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 156 additions and 51 deletions

View File

@ -3,6 +3,8 @@ package com.edufocus.edufocus.user.controller;
import com.edufocus.edufocus.user.model.entity.InfoDto; import com.edufocus.edufocus.user.model.entity.InfoDto;
import com.edufocus.edufocus.user.model.entity.PasswordDto; import com.edufocus.edufocus.user.model.entity.PasswordDto;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.User;
import com.edufocus.edufocus.user.model.exception.ExpriedTokenException;
import com.edufocus.edufocus.user.model.exception.UnAuthorizedException;
import com.edufocus.edufocus.user.model.service.UserService; 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;
@ -258,7 +260,15 @@ public class UserController {
} }
@ExceptionHandler(ExpriedTokenException.class)
public ResponseEntity<?> handleExpiredTokenException(){
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler(UnAuthorizedException.class)
public ResponseEntity<?> handleUnauthorizedException(){
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}

View File

@ -0,0 +1,11 @@
package com.edufocus.edufocus.user.model.exception;
public class ExpriedTokenException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ExpriedTokenException() {
super("계정 권한이 유효하지 않습니다.\n다시 로그인을 하세요.");
}
}

View File

@ -0,0 +1,27 @@
package com.edufocus.edufocus.user.model.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UnAuthorizedException.class)
public ResponseEntity<String> handleUnAuthorizedException(UnAuthorizedException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ExpriedTokenException.class)
public ResponseEntity<String> handleInvalidTokenException(ExpriedTokenException e) {
// 로그 남기기 (선택 사항)
// log.error("Invalid token", e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED);
}
}

View File

@ -0,0 +1,7 @@
package com.edufocus.edufocus.user.model.exception;
public class InvalidTokenException extends RuntimeException {
public InvalidTokenException() {
super("Token is invalid");
}
}

View File

@ -4,6 +4,8 @@ import java.nio.charset.StandardCharsets;
import java.util.Date; import java.util.Date;
import java.util.Map; 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.UnAuthorizedException; import com.edufocus.edufocus.user.model.exception.UnAuthorizedException;
import io.jsonwebtoken.*; import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -58,11 +60,19 @@ public class JWTUtil {
.parseClaimsJws(token); .parseClaimsJws(token);
log.debug("claims: {}", claims); log.debug("claims: {}", claims);
return true; return true;
} catch (MalformedJwtException | UnsupportedJwtException | IllegalArgumentException | SignatureException | ExpiredJwtException e) { } catch (MalformedJwtException | UnsupportedJwtException | IllegalArgumentException | SignatureException e) {
log.error("Token validation error: {}", e.getMessage()); log.error("Token validation error: {}", e.getMessage());
return false; return false;
} catch (Exception e) { }
catch ( ExpiredJwtException e)
{
throw new ExpriedTokenException();
}
catch (Exception e) {
System.out.println(token); System.out.println(token);
System.out.println(e.getMessage());
log.error("Unexpected error while validating token: {}", e.getMessage()); log.error("Unexpected error while validating token: {}", e.getMessage());
return false; return false;
} }
@ -77,7 +87,13 @@ public class JWTUtil {
Map<String, Object> value = claims.getBody(); Map<String, Object> value = claims.getBody();
log.info("value : {}", value); log.info("value : {}", value);
return (String) value.get("id"); return (String) value.get("id");
} catch (Exception e) { }catch ( ExpiredJwtException e)
{
System.out.println("expired token");
throw new ExpriedTokenException();
}
catch (Exception e) {
log.error("Failed to get user ID from token: {}", e.getMessage()); log.error("Failed to get user ID from token: {}", e.getMessage());
throw new UnAuthorizedException(); throw new UnAuthorizedException();
} }

View File

@ -7,6 +7,9 @@ import com.edufocus.edufocus.lecture.entity.LectureDetailResponse;
import com.edufocus.edufocus.lecture.service.LectureService; import com.edufocus.edufocus.lecture.service.LectureService;
import com.edufocus.edufocus.registration.entity.RegistrationStatus; import com.edufocus.edufocus.registration.entity.RegistrationStatus;
import com.edufocus.edufocus.registration.service.RegistrationService; import com.edufocus.edufocus.registration.service.RegistrationService;
import com.edufocus.edufocus.user.model.entity.User;
import com.edufocus.edufocus.user.model.entity.UserRole;
import com.edufocus.edufocus.user.model.repository.UserRepository;
import com.edufocus.edufocus.user.model.service.UserService; import com.edufocus.edufocus.user.model.service.UserService;
import com.edufocus.edufocus.user.util.JWTUtil; import com.edufocus.edufocus.user.util.JWTUtil;
import com.edufocus.edufocus.video.service.VideoSertvice; import com.edufocus.edufocus.video.service.VideoSertvice;
@ -33,6 +36,7 @@ public class Controller {
private final LectureService lectureService; private final LectureService lectureService;
private final VideoSertvice videoSertvice; private final VideoSertvice videoSertvice;
private final RegistrationService registrationService; private final RegistrationService registrationService;
private final UserRepository userRepository;
@Value("${livekit.api.key}") @Value("${livekit.api.key}")
private String LIVEKIT_API_KEY; private String LIVEKIT_API_KEY;
@ -70,8 +74,13 @@ public class Controller {
Long userId = Long.parseLong(jwtUtil.getUserId(userToken)); Long userId = Long.parseLong(jwtUtil.getUserId(userToken));
User findUser= userRepository.findById(userId).orElse(null);
if(findUser.getRole()==UserRole.ADMIN) {
LectureDetailResponse lecture = lectureService.findLectureById(userId, id); LectureDetailResponse lecture = lectureService.findLectureById(userId, id);
String roomName = lecture.getTitle(); String roomName = lecture.getTitle();
String participantName = userService.getUserName(userId); String participantName = userService.getUserName(userId);
@ -84,25 +93,14 @@ public class Controller {
videoSertvice.startOnline(userId, id); videoSertvice.startOnline(userId, id);
return ResponseEntity.ok(Map.of("token", token.toJwt())); return ResponseEntity.ok(Map.of("token", token.toJwt()));
} }
else if(findUser.getRole()==UserRole.STUDENT)
{
@PostMapping(value = "/joinroom/{lecture_id}")
public ResponseEntity<Map<String, String>> joinRoom(@PathVariable("lecture_id") Long id, HttpServletRequest request) throws Exception {
String userToken = request.getHeader("Authorization");
Long userId = Long.parseLong(jwtUtil.getUserId(userToken));
LectureDetailResponse lecture = lectureService.findLectureById(userId, id); LectureDetailResponse lecture = lectureService.findLectureById(userId, id);
//RegistrationStatus registrationStatus = registrationService.isOnline(userId,id);
// if(registrationStatus==RegistrationStatus.ACCEPTED)
// {
String roomName = lecture.getTitle(); String roomName = lecture.getTitle();
String participantName = userService.getUserName(userId); String participantName = userService.getUserName(userId);
@ -110,23 +108,59 @@ public class Controller {
AccessToken token = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET); AccessToken token = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET);
token.setName(participantName); token.setName(participantName);
token.setIdentity(participantName); token.setIdentity(participantName);
token.addGrants(new RoomJoin(true), new RoomName(roomName)); token.addGrants(new RoomJoin(true), new RoomName(roomName), new RoomCreate(true));
//videoSertvice.startOnline(userId,id);
videoSertvice.startOnline(userId, id);
return ResponseEntity.ok(Map.of("token", token.toJwt())); return ResponseEntity.ok(Map.of("token", token.toJwt()));
// } }
// else{
// return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of("errorMessage", "Not accepted"));
// return ResponseEntity.ok(Map.of("token", null));
// }
} }
// @PostMapping(value = "/joinroom/{lecture_id}")
// public ResponseEntity<Map<String, String>> joinRoom(@PathVariable("lecture_id") Long id, HttpServletRequest request) throws Exception {
//
//// String userToken = request.getHeader("Authorization");
////
//// Long userId = Long.parseLong(jwtUtil.getUserId(userToken));
//// LectureDetailResponse lecture= lectureService.findLectureById(userId,id);
////
////
//// //RegistrationStatus registrationStatus = registrationService.isOnline(userId,id);
////
////// if(registrationStatus==RegistrationStatus.ACCEPTED)
////// {
//// String roomName = lecture.getTitle();
//// String participantName = userService.getUserName(userId);
////
////
//// AccessToken token = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET);
//// token.setName(participantName);
//// token.setIdentity(participantName);
//// token.addGrants(new RoomJoin(true), new RoomName(roomName));
////
//// //videoSertvice.startOnline(userId,id);
////
////
////
//// return ResponseEntity.ok(Map.of("token", token.toJwt()));
////// }
////// else{
////// return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of("errorMessage", "Not accepted"));
//////
////// }
////
//
//
// }
@PostMapping(value = "/livekit/webhook", consumes = "application/webhook+json") @PostMapping(value = "/livekit/webhook", consumes = "application/webhook+json")
public ResponseEntity<String> receiveWebhook(@RequestHeader("Authorization") String authHeader, @RequestBody String body) { public ResponseEntity<String> receiveWebhook(@RequestHeader("Authorization") String authHeader, @RequestBody String body) {
WebhookReceiver webhookReceiver = new WebhookReceiver(LIVEKIT_API_KEY, LIVEKIT_API_SECRET); WebhookReceiver webhookReceiver = new WebhookReceiver(LIVEKIT_API_KEY, LIVEKIT_API_SECRET);