-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4 from DDD-Community/POLABO-38
feat: 하루 요청 100개 제한
- Loading branch information
Showing
18 changed files
with
474 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
50 changes: 50 additions & 0 deletions
50
src/main/kotlin/com/ddd/sonnypolabobe/global/config/SecurityConfig.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package com.ddd.sonnypolabobe.global.config | ||
|
||
import org.springframework.context.annotation.Bean | ||
import org.springframework.context.annotation.Configuration | ||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity | ||
import org.springframework.security.web.SecurityFilterChain | ||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher | ||
import org.springframework.security.web.util.matcher.RequestMatcher | ||
import org.springframework.web.cors.CorsConfiguration | ||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource | ||
|
||
@Configuration | ||
@EnableMethodSecurity | ||
class SecurityConfig() { | ||
|
||
@Bean | ||
fun filterChain(http: HttpSecurity): SecurityFilterChain { | ||
return http | ||
.cors { | ||
it.configurationSource(corsConfigurationSource()) | ||
} | ||
.csrf{ | ||
it.disable() | ||
} | ||
.httpBasic { | ||
it.disable() | ||
} | ||
.formLogin { it.disable() } | ||
.authorizeHttpRequests { | ||
it.anyRequest().permitAll() | ||
} | ||
.build() | ||
} | ||
|
||
fun corsConfigurationSource(): UrlBasedCorsConfigurationSource { | ||
val configuration = CorsConfiguration() | ||
configuration.allowedOrigins = listOf("http://localhost:3000") // Allow all origins | ||
configuration.allowedMethods = | ||
listOf("GET", "POST", "PUT", "DELETE", "OPTIONS") // Allow common methods | ||
configuration.allowedHeaders = listOf("*") // Allow all headers | ||
configuration.allowCredentials = true // Allow credentials | ||
val source = UrlBasedCorsConfigurationSource() | ||
source.registerCorsConfiguration( | ||
"/**", | ||
configuration | ||
) // Apply configuration to all endpoints | ||
return source | ||
} | ||
} |
16 changes: 16 additions & 0 deletions
16
src/main/kotlin/com/ddd/sonnypolabobe/global/config/WebConfig.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package com.ddd.sonnypolabobe.global.config | ||
|
||
import com.ddd.sonnypolabobe.global.security.RateLimitingInterceptor | ||
import org.springframework.context.annotation.Configuration | ||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry | ||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer | ||
|
||
@Configuration | ||
class WebConfig(private val rateLimitingInterceptor: RateLimitingInterceptor) : WebMvcConfigurer { | ||
|
||
override fun addInterceptors(registry: InterceptorRegistry) { | ||
registry.addInterceptor(rateLimitingInterceptor) | ||
.addPathPatterns("/api/v1/boards") | ||
} | ||
|
||
} |
20 changes: 18 additions & 2 deletions
20
src/main/kotlin/com/ddd/sonnypolabobe/global/exception/GlobalExceptionHandler.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
124 changes: 124 additions & 0 deletions
124
src/main/kotlin/com/ddd/sonnypolabobe/global/security/LoggingFilter.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
package com.ddd.sonnypolabobe.global.security | ||
|
||
import com.ddd.sonnypolabobe.global.util.DiscordApiClient | ||
import com.ddd.sonnypolabobe.global.util.HttpLog | ||
import com.ddd.sonnypolabobe.logger | ||
import jakarta.servlet.FilterChain | ||
import jakarta.servlet.ServletRequest | ||
import jakarta.servlet.ServletResponse | ||
import jakarta.servlet.http.HttpServletRequest | ||
import jakarta.servlet.http.HttpServletResponse | ||
import org.springframework.stereotype.Component | ||
import org.springframework.web.filter.GenericFilterBean | ||
import org.springframework.web.util.ContentCachingRequestWrapper | ||
import org.springframework.web.util.ContentCachingResponseWrapper | ||
import org.springframework.web.util.WebUtils | ||
import java.io.UnsupportedEncodingException | ||
import java.util.* | ||
|
||
@Component | ||
class LoggingFilter( | ||
private val discordApiClient: DiscordApiClient | ||
) : GenericFilterBean() { | ||
private val excludedUrls = setOf("/actuator", "/swagger-ui") | ||
|
||
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) { | ||
val requestWrapper: ContentCachingRequestWrapper = | ||
ContentCachingRequestWrapper(request as HttpServletRequest) | ||
val responseWrapper: ContentCachingResponseWrapper = | ||
ContentCachingResponseWrapper(response as HttpServletResponse) | ||
if (excludeLogging(request.requestURI)) { | ||
chain.doFilter(request, response) | ||
} else { | ||
val startedAt = System.currentTimeMillis() | ||
chain.doFilter(requestWrapper, responseWrapper) | ||
val endedAt = System.currentTimeMillis() | ||
|
||
logger().info( | ||
"\n" + | ||
"[REQUEST] ${request.method} - ${request.requestURI} ${responseWrapper.status} - ${(endedAt - startedAt) / 10000.0} \n" + | ||
"Headers : ${getHeaders(request)} \n" + | ||
"Parameters : ${getRequestParams(request)} \n" + | ||
"Request body : ${getRequestBody(requestWrapper)} \n" + | ||
"Response body : ${getResponseBody(responseWrapper)}" | ||
) | ||
|
||
if(responseWrapper.status >= 400) { | ||
this.discordApiClient.sendErrorLog( | ||
HttpLog( | ||
request.method, | ||
request.requestURI, | ||
responseWrapper.status, | ||
(endedAt - startedAt) / 10000.0, | ||
getHeaders(request), | ||
getRequestParams(request), | ||
getRequestBody(requestWrapper), | ||
getResponseBody(responseWrapper) | ||
) | ||
) | ||
} | ||
} | ||
} | ||
|
||
private fun excludeLogging(requestURI: String): Boolean { | ||
return excludedUrls.contains(requestURI) | ||
} | ||
|
||
private fun getResponseBody(response: ContentCachingResponseWrapper): String { | ||
var payload: String? = null | ||
response.characterEncoding = "utf-8" | ||
val wrapper = | ||
WebUtils.getNativeResponse(response, ContentCachingResponseWrapper::class.java) | ||
if (wrapper != null) { | ||
val buf = wrapper.contentAsByteArray | ||
if (buf.isNotEmpty()) { | ||
payload = String(buf, 0, buf.size, charset(wrapper.characterEncoding)) | ||
wrapper.copyBodyToResponse() | ||
} | ||
} | ||
return payload ?: " - " | ||
} | ||
|
||
private fun getRequestBody(request: ContentCachingRequestWrapper): String { | ||
request.characterEncoding = "utf-8" | ||
val wrapper = WebUtils.getNativeRequest<ContentCachingRequestWrapper>( | ||
request, | ||
ContentCachingRequestWrapper::class.java | ||
) | ||
if (wrapper != null) { | ||
val buf = wrapper.contentAsByteArray | ||
if (buf.isNotEmpty()) { | ||
return try { | ||
String(buf, 0, buf.size, charset(wrapper.characterEncoding)) | ||
} catch (e: UnsupportedEncodingException) { | ||
" - " | ||
} | ||
} | ||
} | ||
return " - " | ||
} | ||
|
||
private fun getRequestParams(request: HttpServletRequest): Map<String, String> { | ||
val parameterMap: MutableMap<String, String> = HashMap() | ||
request.characterEncoding = "utf-8" | ||
val parameterArray: Enumeration<*> = request.parameterNames | ||
|
||
while (parameterArray.hasMoreElements()) { | ||
val parameterName = parameterArray.nextElement() as String | ||
parameterMap[parameterName] = request.getParameter(parameterName) | ||
} | ||
|
||
return parameterMap | ||
} | ||
|
||
private fun getHeaders(request: HttpServletRequest): Map<String, String> { | ||
val headerMap: MutableMap<String, String> = HashMap() | ||
|
||
val headerArray: Enumeration<*> = request.headerNames | ||
while (headerArray.hasMoreElements()) { | ||
val headerName = headerArray.nextElement() as String | ||
headerMap[headerName] = request.getHeader(headerName) | ||
} | ||
return headerMap | ||
} | ||
} |
24 changes: 24 additions & 0 deletions
24
src/main/kotlin/com/ddd/sonnypolabobe/global/security/RateLimitingInterceptor.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
package com.ddd.sonnypolabobe.global.security | ||
|
||
import jakarta.servlet.http.HttpServletRequest | ||
import jakarta.servlet.http.HttpServletResponse | ||
import org.springframework.http.HttpStatus | ||
import org.springframework.stereotype.Component | ||
import org.springframework.web.servlet.HandlerInterceptor | ||
|
||
@Component | ||
class RateLimitingInterceptor(private val rateLimitingService: RateLimitingService) : | ||
HandlerInterceptor { | ||
|
||
override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean { | ||
// 특정 URL 패턴을 필터링합니다. | ||
if (request.requestURI == "/api/v1/boards" && request.method == "POST") { | ||
if (!rateLimitingService.incrementRequestCount()) { | ||
response.status = HttpStatus.TOO_MANY_REQUESTS.value() | ||
response.writer.write("Daily request limit exceeded") | ||
return false | ||
} | ||
} | ||
return true | ||
} | ||
} |
35 changes: 35 additions & 0 deletions
35
src/main/kotlin/com/ddd/sonnypolabobe/global/security/RateLimitingService.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package com.ddd.sonnypolabobe.global.security | ||
|
||
import com.ddd.sonnypolabobe.logger | ||
import org.springframework.beans.factory.annotation.Value | ||
import org.springframework.scheduling.annotation.Scheduled | ||
import org.springframework.stereotype.Service | ||
import java.util.concurrent.ConcurrentHashMap | ||
|
||
@Service | ||
class RateLimitingService( | ||
@Value("\${limit.count}") | ||
private val limit: Int | ||
) { | ||
|
||
private val requestCounts = ConcurrentHashMap<String, Int>() | ||
private val LIMIT = limit | ||
private val REQUEST_KEY = "api_request_count" | ||
|
||
fun incrementRequestCount(): Boolean { | ||
val currentCount = requestCounts.getOrDefault(REQUEST_KEY, 0) | ||
|
||
if (currentCount >= LIMIT) { | ||
return false | ||
} | ||
|
||
requestCounts[REQUEST_KEY] = currentCount + 1 | ||
logger().info("Request count: ${requestCounts[REQUEST_KEY]}") | ||
return true | ||
} | ||
|
||
@Scheduled(cron = "0 0 0 * * *", zone = "Asia/Seoul") | ||
fun resetRequestCount() { | ||
requestCounts.clear() | ||
} | ||
} |
Oops, something went wrong.