Enhance tutorial management with user-specific features and improve error handling

This commit is contained in:
liosha84
2025-07-08 20:36:37 +03:00
parent ec1581e88a
commit b37f62e59b
13 changed files with 259 additions and 29 deletions
@@ -24,7 +24,7 @@ import java.util.Optional;
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600, allowCredentials="true")
//@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600, allowCredentials="true")
@RestController
@RequestMapping("/api")
public class TutorialController {
@@ -117,7 +117,7 @@ public class TutorialController {
}
}
@PostMapping("/tutorials")
@PostMapping("user/tutorial-add")
public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
@@ -16,6 +16,9 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@@ -134,7 +137,9 @@ public class WebSecurityConfig implements WebMvcConfigurer {// extends WebSecuri
// Allow public access to tutorials (without login)
.requestMatchers("/api/public/tutorials").permitAll()
.requestMatchers("/api/user").permitAll()
.requestMatchers("/api/public/tutorials/**").permitAll()
.requestMatchers("/api/user/**").permitAll()
.anyRequest().authenticated()
);
@@ -145,4 +150,16 @@ public class WebSecurityConfig implements WebMvcConfigurer {// extends WebSecuri
return http.build();
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
@@ -25,6 +25,7 @@ public class AuthEntryPointJwt implements AuthenticationEntryPoint {
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());
logger.error("Unauthorized error to resource {}", request.getRequestURI());
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error: Unauthorized");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);