package com.ruoyi.framework.security.filter;

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

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.framework.security.domain.AccessLoginUser;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.ss.access.domain.AccessVO;
import com.ruoyi.ss.access.service.AccessService;
import com.ruoyi.ss.user.domain.SmUserVO;
import com.ruoyi.ss.user.service.ISmUserService;
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;
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
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private AccessService accessService;

    @Autowired
    private ISmUserService userService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        // 判断上下文是否已经存在用户信息
        if (StringUtils.isNull(SecurityUtils.getAuthentication())) {
            // 优先尝试使用token来获取用户信息
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (loginUser != null) {
                tokenService.verifyToken(loginUser);
            }
            // 若token未获取到信息，则使用accessKey来获取用户信息
            else {
                loginUser = this.getLoginUserByAccessKey(request);
            }

            // 最后判断用户是否为空，并将其写入到安全上下文
            if (loginUser != null) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }

        chain.doFilter(request, response);
    }

    private LoginUser getLoginUserByAccessKey(HttpServletRequest request) {
        String accessKey = request.getHeader(Constants.HEADER_ACCESS_KEY);
        String accessSecret = request.getHeader(Constants.HEADER_ACCESS_SECRET);
        if (StringUtils.isBlank(accessKey) || StringUtils.isBlank(accessSecret)) {
            return null;
        }
        // 从缓存中获取数据
        String redisKey = CacheConstants.ACCESS_KEY_PREFIX + accessKey;
        AccessLoginUser accessLoginUser = redisCache.getCacheObject(redisKey);

        // 缓存未命中，查询获取数据
        if (accessLoginUser == null) {
            accessLoginUser = new AccessLoginUser();

            // 获取access信息
            AccessVO access = accessService.selectByAccessKey(accessKey);
            if (access == null) {
                return null;
            }
            accessLoginUser.setAccess(access);

            // 获取用户信息
            SmUserVO user = userService.selectSmUserByUserId(accessLoginUser.getAccess().getUserId());
            if (user == null) {
                return null;
            }
            LoginUser loginUser = new LoginUser(user.getUserId(), user, permissionService.getMenuPermission(user));
            accessLoginUser.setLoginUser(loginUser);

            // 放入缓存中
            redisCache.setCacheObject(redisKey, accessLoginUser, 30, TimeUnit.MINUTES);
        }

        // 校验秘钥
        if (!SecurityUtils.matchesPassword(accessSecret, accessLoginUser.getAccess().getAccessSecret())) {
            return null;
        }

        return accessLoginUser.getLoginUser();
    }
}
