Commit 43a35ff0 authored by Ghitha Dinan's avatar Ghitha Dinan

add sso token

parent 6ceb4c7e
package id.co.sangkuriang.inovasi.daerah.master.interceptor
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import id.co.sangkuriang.inovasi.daerah.master.model.response.ReturnData
import id.co.sangkuriang.inovasi.daerah.master.utility.getUsersLogin
import org.slf4j.LoggerFactory
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.util.ContentCachingRequestWrapper
import org.springframework.web.util.ContentCachingResponseWrapper
import java.time.Duration
import java.time.Instant
import java.util.*
import javax.servlet.Filter
import javax.servlet.FilterChain
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@Suppress("UNCHECKED_CAST")
@Component
@Order(2)
class LogInterceptor : Filter {
override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) {
val time = Instant.now()
val req = ContentCachingRequestWrapper(request as HttpServletRequest)
val res = response as HttpServletResponse
val responseCacheWrapperObject = ContentCachingResponseWrapper(res)
chain?.doFilter(req, responseCacheWrapperObject)
val responseArray = responseCacheWrapperObject.contentAsByteArray.toString(Charsets.UTF_8)
responseCacheWrapperObject.copyBodyToResponse()
writeLog(req, responseArray, response, time)
}
private fun writeLog(
httpServletRequest: ContentCachingRequestWrapper,
responseArray: String,
httpServletResponse: HttpServletResponse,
startTime: Instant
) {
var requestUri = httpServletRequest.requestURI
val requestInfo: MutableMap<String, Any> = getRequestInfo(httpServletRequest, httpServletResponse)
try {
if (httpServletRequest.method == RequestMethod.GET.toString()) {
if (requestInfo["param"] != null) {
val paramMap: Map<String, Any> = requestInfo["param"] as Map<String, Any>
requestUri += "?"
var i = 0
paramMap.forEach {
if (i > 0) {
requestUri += "&"
}
requestUri += "$it"
i++
}
requestInfo.remove("param")
}
}
var returnData: ReturnData? = null
try {
val objectMapper = ObjectMapper()
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
returnData = objectMapper.readValue(responseArray, ReturnData::class.java)
} catch (e: Exception) {
}
try {
requestInfo["userData"] = getUsersLogin() as Any
} catch (e: Exception) {
}
var success = false
returnData?.let {
requestInfo["responseData"] = it
if (returnData.success!!) {
success = true
}
} ?: kotlin.run {
requestInfo["responseData"] = responseArray
}
requestInfo["responseCode"] = httpServletResponse.status
val now = Instant.now()
requestInfo["requestTime"] = Duration.between(startTime, now).toMillis().toDouble() / 1000
val res = ObjectMapper().writeValueAsString(requestInfo)
LoggerFactory.getLogger("access.log").info(
getLogDescription(success, requestUri, httpServletRequest.method),
res.replace("\\\"", "\"")
)
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun getRequestInfo(
httpRequest: ContentCachingRequestWrapper,
httpServletResponse: HttpServletResponse
): MutableMap<String, Any> {
val requestHeaderMap = mutableMapOf<String, Any>()
val requestParamMap = mutableMapOf<String, Any>()
val responseHeaderMap = mutableMapOf<String, Any>()
try {
val requestHeaderNames: Enumeration<*> = httpRequest.headerNames
while (requestHeaderNames.hasMoreElements()) {
val headerName = requestHeaderNames.nextElement() as String
requestHeaderMap[headerName] = httpRequest.getHeader(headerName)
}
val params: Enumeration<*> = httpRequest.parameterNames
while (params.hasMoreElements()) {
val paramName = params.nextElement() as String
requestParamMap[paramName] = httpRequest.getParameter(paramName)
}
val reqBody = extractRequestBody(httpRequest)
if (reqBody != "") {
val result: HashMap<*, *>? = ObjectMapper().readValue(
reqBody,
HashMap::class.java
)
if (!result.isNullOrEmpty()) {
requestParamMap.putAll(result as MutableMap<String, Any>)
}
}
httpServletResponse.headerNames.forEach {
responseHeaderMap[it] = httpServletResponse.getHeader(it)
}
} catch (e: Exception) {
e.printStackTrace()
}
return mutableMapOf(
"requestHeader" to requestHeaderMap,
"requestParam" to requestParamMap,
"responseHeader" to responseHeaderMap
)
}
private fun extractRequestBody(request: ContentCachingRequestWrapper): String {
if ("POST".equals(request.method, ignoreCase = true) || "PUT".equals(request.method, ignoreCase = true)) {
val content = request.contentAsByteArray
return String(content, Charsets.UTF_8)
}
return ""
}
private fun getLogDescription(success: Boolean, path: String, method: String): String {
var info = "INFO"
if (!success) {
info = "ERROR"
}
return "$info - $path - $method : {}"
}
}
......@@ -7,8 +7,8 @@ import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import id.co.sangkuriang.inovasi.daerah.master.constant.*
import id.co.sangkuriang.inovasi.daerah.master.helpers.RequestHelpers
import id.co.sangkuriang.inovasi.daerah.master.model.jwt.UserJwtSso
import id.co.sangkuriang.inovasi.daerah.master.model.response.ReturnData
import id.co.sangkuriang.inovasi.daerah.master.pojo.Users
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.util.ContentCachingRequestWrapper
......@@ -97,8 +97,8 @@ class TokenInterceptor : Filter {
val objectMapper = ObjectMapper()
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
val users: Users =
objectMapper.readValue(objectMapper.writeValueAsString(reqAuthDetail.data), Users::class.java)
val users: UserJwtSso =
objectMapper.readValue(objectMapper.writeValueAsString(reqAuthDetail.data), UserJwtSso::class.java)
var audience = "user-admin"
if (users.roleId == ROLE_USER_ID) {
......
package id.co.sangkuriang.inovasi.daerah.master.model.jwt
import id.co.sangkuriang.inovasi.daerah.master.pojo.Province
import id.co.sangkuriang.inovasi.daerah.master.pojo.Regency
import id.co.sangkuriang.inovasi.daerah.master.pojo.Role
data class UserJwtSso(
var id: String? = null,
var nik: String? = null,
var nip: String? = null,
var fullName: String? = null,
var image: String? = null,
var phoneNumber: String? = null,
var email: String? = null,
var roleId: String? = null,
var role: Role? = null,
var provinceId: String? = null,
var province: Province? = null,
var regencyId: String? = null,
var regency: Regency? = null,
var tokenSso: TokenSso? = null
)
data class TokenSso(
var access_token: String? = null,
var expires_in: Int? = null,
var refresh_expires_in: Int? = null,
var refresh_token: String? = null,
var token_type: String? = null,
var session_state: String? = null,
var scope: String? = null
)
......@@ -4,7 +4,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import id.co.sangkuriang.inovasi.daerah.master.constant.UPLOAD_ICON_APPLICATION_CATEGORY_DIR
import id.co.sangkuriang.inovasi.daerah.master.constant.UPLOAD_IMAGE_APPLICATION_CATEGORY_DIR
import id.co.sangkuriang.inovasi.daerah.master.pojo.Users
import id.co.sangkuriang.inovasi.daerah.master.model.jwt.UserJwtSso
import org.apache.commons.io.FileUtils
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.multipart.MultipartFile
......@@ -14,12 +14,12 @@ import java.net.MalformedURLException
import java.net.URL
import javax.servlet.http.HttpServletRequest
fun getUsersLogin(): Users? {
fun getUsersLogin(): UserJwtSso? {
return try {
val principal = SecurityContextHolder.getContext().authentication.principal as Any
val objectMapper = ObjectMapper()
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
objectMapper.readValue(principal.toString(), Users::class.java)
objectMapper.readValue(principal.toString(), UserJwtSso::class.java)
} catch (e: Exception) {
null
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment