package dp.kotul.starter.filter

import dp.kotul.jwt.JwtParser
import io.jsonwebtoken.JwtException
import org.slf4j.LoggerFactory
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

const val AUTHORIZATION_HEADER = "Authorization"

enum class RequestAttr(val key: String) {
    USER("USER_FROM_JWT")
}

class AuthorizationInterceptor(private val jwtParser: JwtParser) : HandlerInterceptor {

    private val log = LoggerFactory.getLogger(AuthorizationInterceptor::class.java)

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        if (request.getHeader(AUTHORIZATION_HEADER).isNullOrEmpty()) {
            throw JwtException("No authorization header")
        }

        val user = jwtParser.verifyAndGetUser(request.getHeader(AUTHORIZATION_HEADER))
        request.setAttribute(RequestAttr.USER.key, user)
        log.info("Found valid user in JWT token, usrId=${user.usrId}, comId=${user.comId}")
        return true
    }
}
