package com.zksy.framework.security.moblie;

import com.zksy.common.core.domain.model.LoginUser;
import com.zksy.common.core.redis.RedisCache;
import com.zksy.common.utils.SecurityUtils;
import com.zksy.common.utils.StringUtils;
import com.zksy.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author ：BIN.LI
 * @date ：2022/4/27 11:35
 * @description：
 */
@Component
public class MobileAuthenticationFilter extends OncePerRequestFilter {
    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
    private int expireTime = 24 * 60;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        LoginUser loginUser = tokenService.getLoginUser4Mobile(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            tokenService.verifyToken(loginUser);
            MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(loginUser, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        return token;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                LoginUser user = redisCache.getCacheObject(token);
                user.setToken(token);
                return user;
            } catch (Exception e) {
            }
        }
        return null;
    }

    /**
     * 刷新令牌有效期
     *
     * @param 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        redisCache.setCacheObject(loginUser.getToken(), loginUser, expireTime, TimeUnit.MINUTES);
    }
}
