content: package com.activecourses.upwork.config.security.jwt;
  
  import java.io.IOException;
  
  import com.activecourses.upwork.config.security.CustomUserDetailsService;
  import jakarta.servlet.FilterChain;
  import jakarta.servlet.ServletException;
  import jakarta.servlet.http.HttpServletRequest;
  import jakarta.servlet.http.HttpServletResponse;
  
  import lombok.NonNull;
  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.core.userdetails.UserDetails;
  import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
  import org.springframework.web.filter.OncePerRequestFilter;
  
  public class AuthTokenFilter extends OncePerRequestFilter {
      @Autowired
      private JwtService jwtService;
  
      @Autowired
      private CustomUserDetailsService userDetailsService;
  
      private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
  
      @Override
      protected void doFilterInternal(@NonNull HttpServletRequest request,
                                      @NonNull HttpServletResponse response,
                                      @NonNull FilterChain filterChain)
              throws ServletException, IOException {
  
          try {
              String jwt = jwtService.getJwtFromCookies(request);
              if (jwt != null && jwtService.validateJwtToken(jwt)) {
                  String username = jwtService.getUserNameFromJwtToken(jwt);
  
                  UserDetails userDetails = userDetailsService.loadUserByUsername(username);
  
                  UsernamePasswordAuthenticationToken authentication =
                          new UsernamePasswordAuthenticationToken(userDetails,
                                  null,
                                  userDetails.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);
      }
  }