package com.jiayue.ssi.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.util.LocalCache;

import lombok.RequiredArgsConstructor;

/**
* 验证码过滤器
*
* @author xsl
* @since 2023/02/20
*/
@RequiredArgsConstructor
@Order(2)
public class VerifyCodeFilter extends OncePerRequestFilter {
    private String defaultFilterProcessUrl = "/user/login";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
            // 验证码验证
            String requestCaptcha = request.getParameter("code");
            String verifyuuid = request.getParameter("verifyuuid");
            Object uuidObj = LocalCache.get(CacheConstants.CAPTCHA_CODE_KEY + verifyuuid);
            // 校验服务端验证码
            if (uuidObj==null || "".equals(uuidObj)){
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.setContentType("text/html;charset=UTF-8");
                response.setStatus(401);
                response.getWriter().write("验证码无效,需要重新获取！");
                return;
            }
            // 校验页面验证码
            if (StringUtils.isEmpty(requestCaptcha)) {
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.setContentType("text/html;charset=UTF-8");
                response.setStatus(401);
                response.getWriter().write("非法访问,验证码错误！");
                return;
            }
            if (requestCaptcha.length()!=4){
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.setContentType("text/html;charset=UTF-8");
                response.setStatus(401);
                response.getWriter().write("需要4位验证码！");
                return;
            }
            if (!String.valueOf(uuidObj).toLowerCase().equals(requestCaptcha.toLowerCase())) {
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.setContentType("text/html;charset=UTF-8");
                response.setStatus(401);
                response.getWriter().write("验证码错误！");
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
