package com.ifish.interceptor;

import java.io.IOException;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ifish.enums.ResultEnum;
import com.ifish.exception.IfishException;
import com.ifish.netease.CheckSumBuilder;

/**
 * 安全校验拦截器
 *
 * @author guogw
 *
 */
public class SecurityValidateInterceptor implements HandlerInterceptor {

    public SecurityValidateInterceptor(boolean devModel) {
        this.devModel = devModel;
    }

    //appKey(ifishAppKey1)MD5
    private String ifishAppKey = "5fc7bdada110e3a6eefd3065b8d8d995";
    //appSecret(ifishAppSecret1)MD5前12位
    private String ifishAppSecret = "9596b393ab0f";
    //开发模式
    private boolean devModel = false;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //开发模式
        if (!devModel) {
            String nonce = request.getHeader("nonce");
            String appKey = request.getHeader("appKey");
            String curTime = request.getHeader("curTime");
            String checkSum = request.getHeader("checkSum");
            //校验参数完整性
            if (StringUtils.isNotBlank(checkSum) && StringUtils.isNotBlank(appKey) && StringUtils.isNotBlank(nonce) && StringUtils.isNotBlank(curTime)) {
                //校验appKey
                if (appKey.equals(ifishAppKey)) {
                    //计算md5
                    String md5Sum = CheckSumBuilder.getMD5(ifishAppSecret + nonce + curTime);
                    if (md5Sum.equals(checkSum)) {
                        return true;
                    }
                }
            }
            throw new IfishException(ResultEnum.error400);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
