package com.fr.plugin;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.AbstractEmbedRequestFilterProvider;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.transform.ExecuteFunctionRecord;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

@FunctionRecorder
public class MyEmbedRequestFilter extends AbstractEmbedRequestFilterProvider {
    @Override
    @ExecuteFunctionRecord
    public void filter(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
          //如果没有登录。。。
        if (!isLogin(httpServletRequest)){
              //第一步获取token
              String my_token = httpServletRequest.getParameter("my_token");
              //第二步判断是否为空，如果不为空。。
              if (StringUtils.isNotBlank(my_token)){
                  try{
                     String userName = new String(Base64.getUrlDecoder().decode(my_token));
                      UserService userService = UserService.getInstance();
                      //第三步检查用户是否存在
                     User user = userService.getUserByUserName(userName);
                     //如果用户存在就去登录
                     if (user != null){
                         //第四步登录并设置Token到请求中
                         String token = LoginService.getInstance().login(httpServletRequest,httpServletResponse,userName);
                        //存到cookie或session里的变量都是FINE_AUTH_TOKEN_NAME
                         httpServletRequest.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,token);
                     }
                      FineLoggerFactory.getLogger().info("通过拦截器登录成功!",userName);
                  }catch (Exception e){
                      e.printStackTrace();
                  }
              }
          }
    }
    private boolean isLogin(HttpServletRequest request){
        return LoginService.getInstance().isLogged(request);
    }
}
