package com.ytpm.interceptor;


import com.ytpm.dao.RiskUserMapper;
import com.ytpm.risk.view.RiskAccessView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@Component
public class OpenApiInterceptor implements HandlerInterceptor {

    @Resource
    private RiskUserMapper riskUserMapper;

    /**
     * 拦截客户端请求判断token为非授权访问则打回
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.error("拦截客户端请求："+request.getRequestURI());
        String token = request.getParameter("access_secret");
        String appId = request.getParameter("app_id");
        RiskAccessView accessView = riskUserMapper.selectByAppId(appId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(Objects.isNull(accessView) || !encoder.matches(token, accessView.getAccessSecret())){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Unauthorized");
            return false;
        }
        return true;
    }
}
