package com.enterprise.manage.core.secure.process;

import com.enterprise.manage.core.secure.domain.SecureUserService;
import com.enterprise.manage.core.secure.domain.SecurityConstant;
import com.enterprise.manage.modules.system.domain.po.User;
import com.enterprise.manage.modules.system.service.ITokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义jwt身份验证过滤器处理类
 *
 * OncePerRequestFilter是Spring Boot里面的一个过滤器抽象类，其同样在Spring Security里面被广泛用到
 * 这个过滤器抽象类通常被用于继承实现并在每次请求时只执行一次过滤.
 *
 * @author PeiZhi Guo
 * 2022-4-13 16:43
 */
@Component
public class SecurityJwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private ITokenService sysTokenService;

    @Resource
    private SecureUserService secureUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(SecurityConstant.TOKEN_KEY);
        if (StringUtils.isNotBlank(token)) {
            User user = sysTokenService.querySysUserByAccessToken(token);
            if (user != null) {
                user = checkLoginTime(user);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,
                        null, null);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 检查登录时间是否超时
     */
    private User checkLoginTime(User user) {
        long expireTime = user.getExpireTime();
        if (expireTime - System.currentTimeMillis() <= SecurityConstant.MINUTES_10) {
            String token = user.getToken();
            user = (User) secureUserService.loadUserByUsername(user.getUsername());
            user.setToken(token);
            sysTokenService.refreshCacheToken(user);
        }
        return user;
    }
}
