commit 77ad34f12ddbfd0f44ccd2fbfaefc7f774bc6bfc
Author: Petr Urban <urbanp@gapps.zcu.cz>
Date:   Mon Apr 10 01:38:32 2023 +0200

    #10228 - authentication entry point

diff --git a/src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/JwtAuthenticationFilter.java b/src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/JwtAuthenticationFilter.java
index fdd49be..7865b16 100644
--- a/src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/JwtAuthenticationFilter.java
+++ b/src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/JwtAuthenticationFilter.java
@@ -1,6 +1,5 @@
 package cz.zcu.fav.kiv.antipatterndetectionapp.v2.security;
 
-import cz.zcu.fav.kiv.antipatterndetectionapp.v2.model.User;
 import cz.zcu.fav.kiv.antipatterndetectionapp.v2.service.AuthProvider;
 import cz.zcu.fav.kiv.antipatterndetectionapp.v2.service.OAuthService;
 import cz.zcu.fav.kiv.antipatterndetectionapp.v2.service.OAuthServiceImpl;
@@ -12,6 +11,8 @@ import org.springframework.security.authentication.AuthenticationProvider;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.stereotype.Component;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.filter.OncePerRequestFilter;
@@ -23,11 +24,13 @@ import javax.servlet.http.HttpServletResponse;
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.IOException;
+import java.security.Security;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.Objects;
 
 @Component
-public class JwtAuthenticationFilter  extends OncePerRequestFilter {
+public class JwtAuthenticationFilter extends OncePerRequestFilter {
 
     private OAuthService oAuthService;
 
@@ -35,122 +38,47 @@ public class JwtAuthenticationFilter  extends OncePerRequestFilter {
         this.oAuthService = oAuthService;
     }
 
-//    @Override
-//    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
-//        System.out.println("------------------DO FILTER INTERNAL---------------------------");
-//
-//        String authorizationHeader = request.getHeader("Authorization");
-//        if(authorizationHeader == null || authorizationHeader.length() < 7) {
-//            filterChain.doFilter(request, response);
-//            return;
-//        }
-////        OAuthServiceImpl oAuthService = new OAuthServiceImpl();
-//
-//        String token = authorizationHeader.substring(7);
-//
-//        ResponseEntity<String> oAuthResponse =  oAuthService.authenticate(token);
-//        response.setContentType("application/json");
-//        response.setStatus(oAuthResponse.getStatusCodeValue());
-//
-//        BufferedWriter out = new BufferedWriter(response.getWriter());
-//        out.write(Objects.requireNonNull(oAuthResponse.getBody()));
-//        out.flush();
-//        out.close();
-//
-//        filterChain.doFilter(request, response);
-//
-//    }
-
-//    @Override
-//    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
-//            throws ServletException, IOException {
-//
-//        String authorizationHeader = request.getHeader("Authorization");
-//        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
-//            String token = authorizationHeader.substring(7);
-//            try {
-//                Authentication authentication = new UsernamePasswordAuthenticationToken(oAuthService.authenticate(token).getBody(), null);
-//                SecurityContextHolder.getContext().setAuthentication(authentication);
-//            } catch (Exception e) {
-//                SecurityContextHolder.clearContext();
-//                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT token");
-//            }
-//        }
-////        String authorizationHeader = request.getHeader("Authorization");
-////
-////        if(authorizationHeader == null || authorizationHeader.length() < 7) {
-////            filterChain.doFilter(request, response);
-////            return;
-////        }
-////
-////        RestTemplate restTemplate = new RestTemplate();
-////        HttpHeaders headers = new HttpHeaders();
-////        headers.setContentType(MediaType.APPLICATION_JSON);
-////
-////
-////        HashMap<String, String> requestBody = new HashMap<>();
-////
-////        requestBody.put("name", "userName");
-////
-////        // set the JWT token in the authorization header
-////
-////        headers.set("Authorization", authorizationHeader);
-////        requestBody.put("token", authorizationHeader.substring(7));
-////        //
-////
-////        String json = JSONBuilder.buildJson(requestBody);
-////
-////        HttpEntity<String> entity = new HttpEntity<>(json, headers);
-////        //RequestBuilder.sendRequestResponse("http://localhost:8081/authenticate",token);
-////        ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:8081/authenticate", HttpMethod.POST, entity, String.class);
-////
-////        // do something with the response body
-////
-////        if (responseEntity.getBody().contains("Invalid token")) {
-////            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT token");
-////
-////        } else {
-////            return;
-//////            Authentication authentication = new UsernamePasswordAuthenticationToken("name", null);
-//////            SecurityContextHolder.getContext().setAuthentication(authentication);
-////        }
-////
-//////        filterChain.doFilter(request, response);
-//    }
-
     @Override
     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
             throws IOException, ServletException {
 
         String authorizationHeader = request.getHeader("Authorization");
-        if (authorizationHeader == null || authorizationHeader.length() < 7) {
+        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
             chain.doFilter(request, response);
             return;
         }
-        String token = authorizationHeader.substring(7);
 
-        ResponseEntity<String> responseEntity = oAuthService.authenticate(token);
-        if (token != null && responseEntity.getBody().contains("OK")) {
-            // Token is valid, proceed with the request
-            chain.doFilter(request, response);
-        } else {
-            // Token is invalid or not present, authenticate the request with external authentication provider
-//            HttpHeaders headers = new HttpHeaders();
-//            headers.setContentType(MediaType.APPLICATION_JSON);
-//            String requestBody = "{\"token\": \"" + token + "\"}";
-//            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
-//
-//            ResponseEntity<AuthenticationResponse> authenticationResponseEntity =
-//                    restTemplate.postForEntity(AUTHENTICATION_URL, entity, AuthenticationResponse.class);
-//
-//            if (authenticationResponseEntity.getStatusCode() == HttpStatus.OK
-//                    && authenticationResponseEntity.getBody().isAuthenticated()) {
-//                // Request is authenticated, proceed with the request
-//                chain.doFilter(request, response);
-//            } else {
-                // Request is not authenticated, set response status to 401 Unauthorized
+        try {
+
+            String token = authorizationHeader.replace("Bearer ", "");
+
+            ResponseEntity<String> responseEntity = oAuthService.authenticate(token);
+            if (responseEntity.getBody().contains("OK")) {
+
+                UserDetails userDetails = User.builder()
+                        .username("jmeno")
+                        .password("")
+                        .authorities(Collections.emptyList())
+                        .build();
+
+                Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, token, userDetails.getAuthorities());
+                SecurityContextHolder.getContext().setAuthentication(auth);
+
+            }
+            else {
+                SecurityContextHolder.clearContext();
                 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
-//            }
+                response.getOutputStream().println("{\"error\" : \"Token timed out!\"}");
+                return;
+            }
+        } catch (Exception e) {
+            SecurityContextHolder.clearContext();
+            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+            response.getOutputStream().println("{\"error\" : \"Some other error related to jwt token!\"}");
+            return;
         }
+
+        chain.doFilter(request, response);
     }
-}
\ No newline at end of file
+}
+
diff --git a/src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/WebSecurityConfig.java b/src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/WebSecurityConfig.java
index 7146656..7f92112 100644
--- a/src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/WebSecurityConfig.java
+++ b/src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/WebSecurityConfig.java
@@ -66,14 +66,14 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
                 .authorizeRequests()
                 .antMatchers("/v2/user/register", "/v2/user/login").permitAll()
                 .anyRequest().authenticated()
-                .and()
-                .exceptionHandling()
-                .authenticationEntryPoint(new OAuthServiceImpl())
+//                .and()
+//                .exceptionHandling()
+//                .authenticationEntryPoint(new OAuthServiceImpl())
                 .and()
                 .sessionManagement()
-                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
-//                .and()
-//                .addFilterBefore(new JwtAuthenticationFilter(new OAuthServiceImpl()), UsernamePasswordAuthenticationFilter.class);
+                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
+                .and()
+                .addFilterBefore(new JwtAuthenticationFilter(new OAuthServiceImpl()), UsernamePasswordAuthenticationFilter.class);
 //        httpSecurity.addFilterAfter(new JwtAuthenticationFilter(new OAuthServiceImpl()), UsernamePasswordAuthenticationFilter.class);
 //        httpSecurity.addFilter(new JwtAuthenticationFilter(new OAuthServiceImpl()));
     }
