Skip to content

Commit

Permalink
refactor : clean up code
Browse files Browse the repository at this point in the history
- final 클래스 및 변수
  • Loading branch information
JiwonKKang committed Nov 1, 2024
1 parent 0672f8a commit 8f3c34f
Show file tree
Hide file tree
Showing 83 changed files with 207 additions and 210 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,27 @@ public class AlertApi implements AlertApiDocs {

private final AlertService alertService;

@Override
@PostMapping("/methods")
public Response<Void> appendAlertMethod(AppendAlertMethodRequest request) {
alertService.appendMethod(request.toAlertInfo());
return Response.success();
}

@Override
@GetMapping("/methods")
public Response<List<AlertMethod>> getAllAlertMethods(Long projectId) {
return Response.success(alertService.readAllMethods(ProjectId.from(projectId)));
}

@Override
@PatchMapping("/methods/{alertMethodId}/deactivate")
public Response<Void> deactivateAlertMethod(@PathVariable Long alertMethodId) {
alertService.deactivateMethod(AlertMethodId.from(alertMethodId));
return Response.success();
}

@Override
@PatchMapping("/methods/{alertMethodId}/activate")
public Response<Void> activateAlertMethod(@PathVariable Long alertMethodId) {
alertService.activateMethod(AlertMethodId.from(alertMethodId));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,18 @@ public class AuthApi implements AuthApiDocs {

private final AuthService authService;

@Override
@PostMapping("/sign-up")
public Response<UserResponse> signup(@RequestBody SignUpRequest request) {
User signUpUser = authService.signUp(request.toUserProfile(), request.password());
final User signUpUser = authService.signUp(request.toUserProfile(), request.password());
return Response.success(UserResponse.from(signUpUser));
}

@Override
@PostMapping("/login")
public ResponseEntity<Void> login(@RequestBody LoginRequest request) {
Tokens tokens = authService.login(request.toLoginInfo());
HttpHeaders tokenHeaders = TokenUtils.createTokenHeaders(tokens);
final Tokens tokens = authService.login(request.toLoginInfo());
final HttpHeaders tokenHeaders = TokenUtils.createTokenHeaders(tokens);
return ResponseEntity.ok().headers(tokenHeaders).build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import com.univ.tracedin.common.exception.WebException;
import com.univ.tracedin.domain.auth.exception.AuthErrorCode;

public class AuthenticationException extends WebException {
public final class AuthenticationException extends WebException {

public static final AuthenticationException EXCEPTION = new AuthenticationException();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import com.univ.tracedin.common.exception.WebException;
import com.univ.tracedin.domain.auth.exception.AuthErrorCode;

public class ExpiredTokenException extends WebException {
public final class ExpiredTokenException extends WebException {

public static final ExpiredTokenException EXCEPTION = new ExpiredTokenException();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import com.univ.tracedin.common.exception.WebException;
import com.univ.tracedin.domain.auth.exception.AuthErrorCode;

public class InvalidTokenException extends WebException {
public final class InvalidTokenException extends WebException {

public static final InvalidTokenException EXCEPTION = new InvalidTokenException();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import com.univ.tracedin.common.exception.WebException;
import com.univ.tracedin.domain.auth.exception.AuthErrorCode;

public class NoPermissionException extends WebException {
public final class NoPermissionException extends WebException {

public static final NoPermissionException EXCEPTION = new NoPermissionException();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

import jakarta.servlet.http.HttpServletRequest;

Expand All @@ -27,6 +28,8 @@
@RequiredArgsConstructor
public class LogAspect {

private static final Pattern PATTERN = Pattern.compile("\\.");

@Pointcut(
"execution(* com.univ.tracedin.domain..*(..)) || execution(* com.univ.tracedin.infra..*(..)) && !execution(* com.univ.tracedin.common..*(..))")
public void all() {}
Expand All @@ -37,29 +40,29 @@ public void controller() {}

@Around("all()")
public Object logging(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
final long start = System.currentTimeMillis();
try {
return joinPoint.proceed();
} finally {
long end = System.currentTimeMillis();
long timeinMs = end - start;
final long end = System.currentTimeMillis();
final long timeinMs = end - start;
log.info("{} | time = {}ms", joinPoint.getSignature(), timeinMs);
}
}

@Around("controller()")
public Object loggingBefore(ProceedingJoinPoint joinPoint) throws Throwable {
HttpServletRequest request =
final HttpServletRequest request =
((ServletRequestAttributes)
Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
.getRequest();

String controllerName = joinPoint.getSignature().getDeclaringType().getName();
String methodName = joinPoint.getSignature().getName();
Map<String, Object> params = new HashMap<>();
final String controllerName = joinPoint.getSignature().getDeclaringType().getName();
final String methodName = joinPoint.getSignature().getName();
final Map<String, Object> params = new HashMap<>();

try {
String decodedURI = URLDecoder.decode(request.getRequestURI(), "UTF-8");
final String decodedURI = URLDecoder.decode(request.getRequestURI(), "UTF-8");

params.put("controller", controllerName);
params.put("method", methodName);
Expand All @@ -75,17 +78,15 @@ public Object loggingBefore(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("method: {}.{}", params.get("controller"), params.get("method"));
log.info("params: {}", params.get("params"));

Object result = joinPoint.proceed();

return result;
return joinPoint.proceed();
}

private static JSONObject getParams(HttpServletRequest request) throws JSONException {
JSONObject jsonObject = new JSONObject();
Enumeration<String> params = request.getParameterNames();
final JSONObject jsonObject = new JSONObject();
final Enumeration<String> params = request.getParameterNames();
while (params.hasMoreElements()) {
String param = params.nextElement();
String replaceParam = param.replaceAll("\\.", "-");
final String param = params.nextElement();
final String replaceParam = PATTERN.matcher(param).replaceAll("-");
jsonObject.put(replaceParam, request.getParameter(param));
}
return jsonObject;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class ModuleConfig {

@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return objectMapper;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
@RestControllerAdvice
public class GlobalControllerAdvice {

@ExceptionHandler(value = CustomException.class)
@ExceptionHandler(CustomException.class)
public ResponseEntity<?> customError(CustomException e, HttpServletRequest request) {
return ResponseEntity.status(e.getStatus())
.body(
Expand All @@ -26,7 +26,7 @@ public ResponseEntity<?> customError(CustomException e, HttpServletRequest reque
e.getMessage()));
}

@ExceptionHandler(value = Exception.class)
@ExceptionHandler(Exception.class)
public ResponseEntity<?> error(Exception e, HttpServletRequest request) {
log.error("error", e);
return ResponseEntity.status(500)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public void commence(
com.univ.tracedin.api.auth.exception.AuthenticationException.EXCEPTION);
}

private boolean isExceptionInSecurityFilter(HttpServletRequest request) {
private static boolean isExceptionInSecurityFilter(HttpServletRequest request) {
return request.getAttribute("exception") != null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,18 @@ protected void doFilterInternal(
throws ServletException, IOException {

try {
Optional<String> refreshToken = JwtTokenizer.extractRefreshToken(request);
final Optional<String> refreshToken = JwtTokenizer.extractRefreshToken(request);

if (refreshToken.isPresent()) {
UserPrincipal principal = JwtTokenizer.extractPrincipal(refreshToken.get());
final UserPrincipal principal = JwtTokenizer.extractPrincipal(refreshToken.get());
validateRefreshToken(principal, refreshToken.get());
reIssueToken(principal, response);
return;
}

JwtTokenizer.extractAccessToken(request)
.map(JwtTokenizer::extractPrincipal)
.ifPresent(this::saveAuthentication);
.ifPresent(JwtAuthenticationFilter::saveAuthentication);

} catch (Exception e) {
log.error(e.toString());
Expand All @@ -60,28 +60,28 @@ protected void doFilterInternal(
}

public void validateRefreshToken(UserPrincipal principal, String givenRefreshToken) {
RefreshToken validRefreshToken = tokenCache.get(principal.userId());
final RefreshToken validRefreshToken = tokenCache.get(principal.userId());
if (validRefreshToken.notEquals(givenRefreshToken)) {
throw InvalidTokenException.EXCEPTION;
}
}

private void reIssueToken(UserPrincipal principal, HttpServletResponse response) {
String reIssuedAccessToken = JwtTokenizer.generateAccessToken(principal);
String reIssuedRefreshToken = JwtTokenizer.generateRefreshToken(principal);
final String reIssuedAccessToken = JwtTokenizer.generateAccessToken(principal);
final String reIssuedRefreshToken = JwtTokenizer.generateRefreshToken(principal);
tokenCache.cache(RefreshToken.of(principal.userId(), reIssuedRefreshToken));
JwtTokenizer.setInHeader(response, reIssuedAccessToken, reIssuedRefreshToken);
response.setStatus(HttpServletResponse.SC_CREATED);
}

private void saveAuthentication(UserPrincipal principal) {
UsernamePasswordAuthenticationToken authentication =
private static void saveAuthentication(UserPrincipal principal) {
final UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(principal, null, getAuthorities(principal));
SecurityContextHolder.getContext().setAuthentication(authentication);
}

private List<GrantedAuthority> getAuthorities(UserPrincipal principal) {
List<GrantedAuthority> authorities = new ArrayList<>();
private static List<GrantedAuthority> getAuthorities(UserPrincipal principal) {
final List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_" + principal.role().name()));
return authorities;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
public class JwtTokenizer implements TokenGenerator {

public static String generateAccessToken(UserPrincipal principal) {
Key key = getKeyFromSecretKey(SECRET_KEY);
final Key key = getKeyFromSecretKey(secretKey);

return Jwts.builder()
.setSubject(String.valueOf(principal.userId()))
Expand All @@ -43,7 +43,7 @@ public static String generateAccessToken(UserPrincipal principal) {
}

public static String generateRefreshToken(UserPrincipal principal) {
Key key = getKeyFromSecretKey(SECRET_KEY);
final Key key = getKeyFromSecretKey(secretKey);

return Jwts.builder()
.setSubject(String.valueOf(principal.userId()))
Expand All @@ -54,45 +54,45 @@ public static String generateRefreshToken(UserPrincipal principal) {

public static void setInHeader(
HttpServletResponse response, String accessToken, String refreshToken) {
response.setHeader(ACCESS_TOKEN_HEADER, accessToken);
response.setHeader(REFRESH_TOKEN_HEADER, refreshToken);
response.setHeader(accessTokenHeader, accessToken);
response.setHeader(refreshTokenHeader, refreshToken);
}

public static Key getKeyFromSecretKey(String secretKey) {
byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
final byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
return Keys.hmacShaKeyFor(keyBytes);
}

public static Date getTokenExpiration() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, ACCESS_TOKEN_EXPIRATION);
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, accessTokenExpiration);
return calendar.getTime();
}

public static Optional<String> extractAccessToken(HttpServletRequest request) {
return Optional.ofNullable(request.getHeader(ACCESS_TOKEN_HEADER))
.filter(accessToken -> accessToken.startsWith(BEARER))
.map(accessToken -> accessToken.replace(BEARER, ""));
return Optional.ofNullable(request.getHeader(accessTokenHeader))
.filter(accessToken -> accessToken.startsWith(bearer))
.map(accessToken -> accessToken.replace(bearer, ""));
}

public static Optional<String> extractRefreshToken(HttpServletRequest request) {
return Optional.ofNullable(request.getHeader(REFRESH_TOKEN_HEADER))
.filter(refreshToken -> refreshToken.startsWith(BEARER))
.map(refreshToken -> refreshToken.replace(BEARER, ""));
return Optional.ofNullable(request.getHeader(refreshTokenHeader))
.filter(refreshToken -> refreshToken.startsWith(bearer))
.map(refreshToken -> refreshToken.replace(bearer, ""));
}

public static UserPrincipal extractPrincipal(String token) {
try {
// JWT 파싱 및 유효성 검사
Claims claims =
final Claims claims =
Jwts.parserBuilder()
.setSigningKey(getKeyFromSecretKey(SECRET_KEY))
.setSigningKey(getKeyFromSecretKey(secretKey))
.build()
.parseClaimsJws(token)
.getBody();

long userId = Long.parseLong(claims.getSubject());
UserRole role = UserRole.valueOf(claims.get("role", String.class));
final long userId = Long.parseLong(claims.getSubject());
final UserRole role = UserRole.valueOf(claims.get("role", String.class));
return UserPrincipal.of(UserId.from(userId), role);

} catch (ExpiredJwtException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,6 @@ public class SecurityConstants {
public static String[] getPermittedURIs() {
return Stream.of(SWAGGER_URIS, SYSTEM_URIS).flatMap(Stream::of).toArray(String[]::new);
}

private SecurityConstants() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,24 @@
@Component
public class SecurityProperties {

public static String SECRET_KEY;
public static int ACCESS_TOKEN_EXPIRATION;
public static String ACCESS_TOKEN_HEADER = AUTHORIZATION;
public static String REFRESH_TOKEN_HEADER;
public static String BEARER = "Bearer ";
public static String secretKey;
public static int accessTokenExpiration;
public static String accessTokenHeader = AUTHORIZATION;
public static String refreshTokenHeader;
public static String bearer = "Bearer ";

@Value("${jwt.secret-key}")
public void setSecretKey(String secretKey) {
SecurityProperties.SECRET_KEY = secretKey;
SecurityProperties.secretKey = secretKey;
}

@Value("${jwt.access-token.expiration}")
public void setAccessTokenExpiration(int accessTokenExpiration) {
SecurityProperties.ACCESS_TOKEN_EXPIRATION = accessTokenExpiration;
SecurityProperties.accessTokenExpiration = accessTokenExpiration;
}

@Value("${jwt.refresh-token.header}")
public void setRefreshToken(String refreshToken) {
SecurityProperties.REFRESH_TOKEN_HEADER = refreshToken;
SecurityProperties.refreshTokenHeader = refreshToken;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class SseConnector<T> {
private final SseEmitterRepository sseEmitterRepository;

public SseEmitter connect(T key) {
SseEmitter emitter = new SseEmitter(TIMEOUT);
final SseEmitter emitter = new SseEmitter(TIMEOUT);
sseEmitterRepository.save(key, emitter);
emitter.onTimeout(() -> sseEmitterRepository.remove(key));
emitter.onCompletion(() -> sseEmitterRepository.remove(key));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
@RequiredArgsConstructor
public class SseSender implements EventSender {

private final String METRICS_POSTFIX = " - metrics";
private static final String METRICS_POSTFIX = " - metrics";
private final SseEmitterRepository sseEmitterRepository;

@Override
Expand Down
Loading

0 comments on commit 8f3c34f

Please sign in to comment.