package com.ruoyi.framework.security.filter;

import java.io.IOException;
import java.util.Collection;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginWxUser;
import com.ruoyi.framework.web.service.WxTokenService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
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 com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private WxTokenService wxTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 微信端访问
        if (request.getRequestURI().contains(Constants.WX_URI)) {
            log.info("微信端请求访问请求:{}", request.getRequestURI());
            LoginWxUser loginWxUser = wxTokenService.getLoginAppUser(request);
            if (StringUtils.isNotNull(loginWxUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                wxTokenService.verifyToken(loginWxUser);
                auth(loginWxUser, loginWxUser.getAuthorities(), request);
            }
        } else {
            log.info("后台服务访问请求：{}", request.getRequestURI());
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyToken(loginUser);
                auth(loginUser, loginUser.getAuthorities(), request);
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * 验证token
     *
     * @param obj         登录信息
     * @param authorities 已授予的权限集合
     * @param request     网络请求
     */
    private void auth(Object obj, Collection<? extends GrantedAuthority> authorities, HttpServletRequest request) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(obj, null, authorities);
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}
