/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ifish.Interceptor;

import com.ifish.enums.ResultEnum;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 *
 * @author Administrator
 */
public class SecurityValidateInterceptor extends HandlerInterceptorAdapter {

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

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

    //不需要验证的url
    private static List<String> urlList = new ArrayList<String>();

    //添加不需要验证url
    static {
        urlList.add("/user/");
        urlList.add("/updateUser/");
        urlList.add("/pageList/");
        urlList.add("/information/v3/findCommentsByUeditorId.do");
        urlList.add("/information/v3/saveComment.do");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //开发模式
        if (!devModel) {

            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getServletPath();
            //部分url不需要拦截器进行验证
            for (String string : urlList) {
                if (url.contains(string)) {
                    return true;
                }
            }

            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;
    }

}
