package com.pingpang.interceptor;

import java.util.UUID;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import com.pingpang.util.IPUtil;
//import com.plumelog.core.TraceId;
 
public class LoginHandlerInterceptor implements HandlerInterceptor {
	Logger logger = LoggerFactory.getLogger(LoginHandlerInterceptor.class);

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		
//		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//	    TraceId.logTraceID.set(uuid);//设置TraceID值，不埋此点链路ID就没有
	    
		String basePath = request.getContextPath();
		String path = request.getRequestURI();
		String ip=IPUtil.getIpAddr(request);
		
		logger.info("\r\n--------------\r\nIP:{}\r\nbasePath:{}\r\npath:{}",ip,basePath,path);
		
		Object user = request.getSession().getAttribute("user");
		
		//判断是否是管理员
		boolean isAdmin=false;
		if(null!=request.getSession().getAttribute("isAdmin")) {
			isAdmin=true;
		}
		
        // 如果获取的request的session中的loginUser参数为空（未登录），就返回登录页，否则放行访问
        if (user == null) {
        	logger.info("未登录获取数据连接...");
        	//logger.info("--------------");
            // 获取request返回页面到登录页
        	response.sendRedirect(request.getContextPath()+"/");
            return false;
        } else {
            // 已登录，放行
        	//logger.info("--------------");
        	path=path.replaceFirst("^[/|\\\\]*", ""); 
        	if(path.startsWith("userController") || path.startsWith("druid")) {
        		if(!isAdmin) {
        		   logger.info(user+":非法请求，移除用户！！！");
        		   response.sendRedirect(request.getContextPath()+"/user/logOut");
                   return false;
        		}
                return isAdmin;        		
        	}
            return true;
        }
	}
}
