package com.qiaoba.auth.filter;

import cn.hutool.core.util.StrUtil;
import com.qiaoba.api.auth.entity.dto.OnlineUserDto;
import com.qiaoba.api.auth.utils.TokenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
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.Objects;

/**
 * 鉴权核心过滤器
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023-05-28 15:31:55
 */
@RequiredArgsConstructor
@Slf4j
@Configuration
public class SecurityContextHolderFilter extends OncePerRequestFilter {


    private final UserDetailsService userDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        log.debug("Start run SecurityContextHolderFilter, Uri: {}", request.getRequestURI());

        String token = TokenUtil.getToken(request,true);
        if (StrUtil.isNotBlank(token)) {
            OnlineUserDto userDto = TokenUtil.getUsernameAndDeviceSn(token);
            UserDetails userDetails = userDetailsService.loadUserByUsername(userDto.getUsername());
            // 更新 SecurityContextHolder Authentication, 为了保证 SecurityContext 上下文中 userDetails 是最新的
            if (Objects.nonNull(userDetails) && Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);
    }
}
