package com.uas.platform.b2b.filter;

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

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.service.EnterpriseService;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.util.AgentUtils;
import com.uas.platform.core.util.encry.HmacUtils;

/**
 * 对需要签名认证的请求进行拦截认证
 * 
 * @author yingp
 *
 */
@SuppressWarnings("deprecation")
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;

	@Autowired
	private UserService userService;

	@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) {
			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
					User user = userService.findUserByUserUU(enterprise.getEnAdminuu());
					if (user != null) {
						user.setEnterprise(enterprise);
						user.setIp(AgentUtils.getIp(request));
						SystemSession.setUser(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();
	}

}
