package ru.yandex.direct.web.entity.security.service

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import ru.yandex.direct.core.security.DirectAuthentication
import ru.yandex.direct.web.core.model.WebErrorResponse
import ru.yandex.direct.web.core.model.WebResponse
import ru.yandex.direct.web.core.security.csrf.CsrfValidator
import ru.yandex.direct.web.entity.security.model.CsrfTokenResponse

@Service
class WebSecurityService @Autowired constructor(
        private val csrfValidator: CsrfValidator
) {

    fun getCsrfToken(auth: DirectAuthentication): WebResponse {
        val uid = auth.operator?.uid
        return if (uid != null) {
            val csrfToken = csrfValidator.createCsrfToken(uid)
            CsrfTokenResponse(csrfToken)
        } else {
            WebErrorResponse(HttpStatus.UNAUTHORIZED.value(), "Authorization error")
        }
    }

}
