package com.ruoyi.common.auth.filter;

import com.ruoyi.common.auth.entity.OauthClientDetails;
import com.ruoyi.common.auth.service.OauthClientDetailsService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.SignResultCodeEnum;
import com.ruoyi.common.core.enums.SignatureRes;
import com.ruoyi.common.core.utils.FebsUtil;
import com.ruoyi.common.core.utils.ServletUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.ruoyi.common.security.utils.SignatureUtils.*;

/**
 * 对外提供服务签名校验
 * 
 * @author gx
 */
@WebFilter(urlPatterns = "/api/*")
@RequiredArgsConstructor
public class ValidSignFilter extends OncePerRequestFilter
{

    private final OauthClientDetailsService oauthClientDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        OauthClientDetails client = oauthClientDetailsService.findById(ServletUtils.getHeader(CLIENT_ID));
        if(client == null) {
            FebsUtil.makeJsonResponse(response, HttpServletResponse.SC_OK,
                    R.fail(SignResultCodeEnum.MISSING_CLIENT_SECRET.getValue(), SignResultCodeEnum.MISSING_CLIENT_SECRET.getText()));
            return;
        }
        SignatureRes checked = checkInterfaceSignature(client.getOriginSecret());
        SignResultCodeEnum checkedEnum = checked.getSignResultCodeEnum();
        if(SignResultCodeEnum.SUCCESS.equals(checkedEnum)) {
            setSignHeader(checked.getResSignature(), checked.getTimestamp());
            chain.doFilter(request, response);
        } else {
            FebsUtil.makeJsonResponse(response, HttpServletResponse.SC_OK, R.fail(checkedEnum.getValue(), checkedEnum.getText()));
        }
    }
}
