package com.qs.mp.framework.security.filter;

import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.common.enums.ChannelStatusEnum;
import com.qs.mp.common.enums.UserIdentityEnum;
import com.qs.mp.common.exception.ServiceException;
import com.qs.mp.common.utils.StringUtils;
import com.qs.mp.core.domain.LoginUser;
import com.qs.mp.framework.security.handle.HostHolder;
import com.qs.mp.framework.web.service.TokenService;
import com.qs.mp.utils.SecurityUtils;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
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.security.authentication.UsernamePasswordAuthenticationToken;
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;

/**
 * token过滤器 验证token有效性
 *
 * @author ygp
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IChannelService channelService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        // 票赢天下小程序请求，判断账号的状态
        if (null != loginUser && loginUser.getIdentity() == UserIdentityEnum.CHANNEL) {
            Channel channel = channelService.getById(loginUser.getChannelId());
            if (null == channel || channel.getStatus() == ChannelStatusEnum.OFF) {
                tokenService.delLoginUser(request);
                loginUser = null;
            }
        }
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(loginUser);
            hostHolder.setUser(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } else {
            hostHolder.setUser(null);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        hostHolder.clear();
        super.destroy();
    }
}
