package com.qiaoba.auth.filters;

import com.qiaoba.api.auth.service.AuthConfigApiService;
import com.qiaoba.auth.constants.SecurityConstant;
import com.qiaoba.auth.entity.dto.OnlineUserDto;
import com.qiaoba.auth.properties.AuthConfigProperties;
import com.qiaoba.auth.service.OnlineUserService;
import com.qiaoba.auth.utils.TokenUtil;
import com.qiaoba.common.redis.service.RedisService;
import com.qiaoba.common.web.utils.ResponseUtil;
import com.qiaoba.common.web.utils.UriUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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
public class AuthenticationCoreFilter extends OncePerRequestFilter {

    private final RedisService redisService;
    private final UserDetailsService userDetailsService;
    private final OnlineUserService onlineUserService;
    private final AuthConfigProperties authConfigProperties;
    private final AuthConfigApiService authConfigApiService;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        log.debug("Start run AuthenticationCoreFilter, Uri: {}", request.getRequestURI());
        // 白名单 放行
        for (String uri : authConfigProperties.getWhitelist()) {
            if (UriUtil.match(uri, request.getRequestURI())) {
                chain.doFilter(request, response);
                return;
            }
        }

        String authToken = TokenUtil.getToken(request, false);

        OnlineUserDto onlineUserDto = TokenUtil.getUsernameAndDeviceSn(authToken);
        String username = onlineUserDto.getUsername();
        String deviceSn = onlineUserDto.getDeviceSn();
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        // 不允许同时在线
        if (!authConfigApiService.checkAllowBothOnline()) {
            if (redisService.hasKey(SecurityConstant.LOGGED_USER_REDIS_KEY + username)) {
                if (!onlineUserService.checkIsLastLogged(username, deviceSn)) {
                    onlineUserService.deleteOne(username, deviceSn, true);
                    ResponseUtil.errorAuth(response, 4012, "被挤下线");
                    return;
                }
            } else {
                ResponseUtil.errorAuth(response, 4011, "登陆过期");
                return;
            }
        }
        // 允许同时在线
        else {
            if (Objects.isNull(userDetails)) {
                ResponseUtil.errorAuth(response, 4011, "登陆过期");
                return;
            }
        }

        // 更新 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);
    }
}
