package com.apobates.forum.trident.controller.helper;

import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.apobates.forum.member.storage.OnlineMemberStorage;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.utils.Commons;

public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private OnlineMemberStorage onlineMemberStorage;
	private final static Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
		logger.info("[AI]EXE Sequence: 3");
		// 处理成内部的地址
		String localRequestUri = request.getRequestURI();
		String localRedirectUri = Commons.getNativeURL(localRequestUri, onlineMemberStorage.getMetaConfig().getSite(), "/");
		localRedirectUri = "/member/login?from=" + URLEncoder.encode(localRedirectUri, "utf-8");
		
		MemberSessionBean mbean = onlineMemberStorage.getInstance(request, "AuthenticationInterceptor").orElse(null);
		if (null==mbean || !mbean.isOnline()) {
			response.sendRedirect(request.getContextPath() + localRedirectUri);
			return false;
		}
		return true;
	}
}
