package com.uas.finance.filter;

import com.uas.finance.service.EnterpriseService;
import com.uas.finance.model.Enterprise;
import com.uas.finance.util.AgentUtils;
import com.uas.finance.util.HmacUtils;
import com.uas.finance.util.SystemSession;
import com.uas.sso.entity.UserAccount;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * 对需要签名认证的请求进行拦截认证
 */
@SuppressWarnings("deprecation")
@Component
public class AccessSignatureInterceptor extends HandlerInterceptorAdapter {

	private final static String idParam = "access_id";
	private final static String signatureParam = "_signature";

	private static final Logger logger = Logger.getLogger(AccessSignatureInterceptor.class);

	@Autowired
	private EnterpriseService enterpriseService;


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String id = request.getParameter(idParam);
		String sign = request.getParameter(signatureParam);
		if (id != null && sign != null) {
			UserAccount user = (UserAccount) request.getSession().getAttribute("userAccount");

			Enterprise enterprise = enterpriseService.findByEnuu(Long.parseLong(id));
			if (enterprise != null && enterprise.getAccessSecret() != null) {
				String urlMessage = request.getRequestURL() + "?"
						+ request.getQueryString().substring(0, request.getQueryString().indexOf(signatureParam) - 1);
				if (sign.equals(HmacUtils.encode(urlMessage, enterprise.getAccessSecret()))) {
                    //写入用户信息
					SystemSession.setUserAccount(user);
                    return true;
				}
				logger.error(String.format("FORBIDDEN FROM %s@%s, REQUEST: %s, SIGNATURE: %s", AgentUtils.getIp(request), id, urlMessage,
						sign));
			}
		}
		response.setStatus(HttpStatus.FORBIDDEN.value());
		return false;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
		SystemSession.clear();
	}

}
