content: package net.alex9849.cocktailpi.config.security;
  
  import jakarta.servlet.FilterChain;
  import jakarta.servlet.ServletException;
  import jakarta.servlet.http.HttpServletRequest;
  import jakarta.servlet.http.HttpServletResponse;
  import net.alex9849.cocktailpi.config.JwtUtils;
  import net.alex9849.cocktailpi.model.user.User;
  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.web.filter.OncePerRequestFilter;
  
  import java.io.IOException;
  
  public class AuthTokenFilter extends OncePerRequestFilter {
      @Autowired
      private JwtUtils jwtUtils;
  
      @Autowired
      private UserDetailsServiceImpl userDetailsService;
  
      private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
  
      @Override
      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
              throws ServletException, IOException {
          try {
              String jwt = jwtUtils.parseJwt(request.getHeader("Authorization"));
              if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
                  long userId = jwtUtils.getUserIdFromJwtToken(jwt);
  
                  User user = userDetailsService.loadUserById(userId);
                  UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                          user, null, user.getAuthorities());
                  authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
  
                  SecurityContextHolder.getContext().setAuthentication(authentication);
              }
          } catch (Exception e) {
              logger.error("Cannot set user authentication: {}", e);
          }
  
          filterChain.doFilter(request, response);
      }
  }
  