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(3)
public class MailCodeFilter 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 username = request.getParameter("username");
            Object mailCode = LocalCache.get(CacheConstants.MAIL_CODE_KEY + username);

            // 校验服务端验证码
            if (mailCode==null || "".equals(mailCode)){
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.setContentType("text/html;charset=UTF-8");
                response.setStatus(401);
                response.getWriter().write("邮箱口令无效,需要重新获取！");
                return;
            }
            // 页面录入的邮箱口令
            String mailbox = request.getParameter("mailbox");

            // 校验页面验证码
            if (StringUtils.isEmpty(mailbox)) {
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.setContentType("text/html;charset=UTF-8");
                response.setStatus(401);
                response.getWriter().write("非法访问,邮箱口令错误！");
                return;
            }
            if (mailbox.length()!=6){
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.setContentType("text/html;charset=UTF-8");
                response.setStatus(401);
                response.getWriter().write("需要6位邮箱口令！");
                return;
            }
            if (!String.valueOf(mailCode).toLowerCase().equals(mailbox.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);
    }
}
