package com.cool.bang.core.secure.support;

import com.alibaba.fastjson.JSON;
import com.cool.bang.common.tools.servlet.ServletUtil;
import com.cool.bang.common.tools.string.StringUtil;
import com.cool.bang.common.web.response.Result;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

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

/**
 * spring security 验证码验证
 *
 * @author GuoPeiZhi
 * 2021-6-22 16:27
 */
@Component
public class SecureCaptchaSupport extends OncePerRequestFilter implements Filter {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private String defaultFilterProcessUrl = "/login";

    private String method = "POST";


    /**
     * 验 证 码 校 验 逻 辑
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (method.equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
            String key = ServletUtil.getRequest().getParameter("key");
            String captcha = ServletUtil.getRequest().getParameter("captcha");
            response.setContentType("application/json;charset=UTF-8");
            if (StringUtil.isEmpty(captcha)) {
                response.getWriter().write(JSON.toJSONString(Result.failure("验证码不能为空!")));
                return;
            }
            String redisCaptcha = redisTemplate.opsForValue().get(key);
            if (StringUtil.isEmpty(redisCaptcha)) {
                response.getWriter().write(JSON.toJSONString(Result.failure("验证码超时!")));
                return;
            }
            if (!redisCaptcha.equals(captcha.trim().toLowerCase())) {
                response.getWriter().write(JSON.toJSONString(Result.failure("验证码错误!")));
                return;
            }
        }
        chain.doFilter(request, response);
    }
}
