Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions src/main/java/edu/eci/cvds/prometeo/config/CorsConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@

@Configuration
public class CorsConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(@SuppressWarnings("null") CorsRegistry registry) {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") // Cambiar el origen al necesario
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(false);
.allowCredentials(true);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws ServletException, IOException {
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return;
}

final String authHeader = request.getHeader("Authorization");

System.out.println("🔍 Checking Authorization header...");
Expand Down
23 changes: 20 additions & 3 deletions src/main/java/edu/eci/cvds/prometeo/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@Slf4j
@Configuration
Expand All @@ -22,13 +27,12 @@ public SecurityConfig(JwtRequestFilter jwtRequestFilter) {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> {})
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth

.requestMatchers("/api/users/create").authenticated()

.requestMatchers("/api/users/trainer/sessions").hasAnyRole("STUDENT", "TRAINER")
.requestMatchers("/api/users/trainer/**").hasRole("TRAINER")

.anyRequest().hasAnyRole("TRAINER", "STUDENT", "ADMIN")
)
.formLogin(form -> form.disable())
Expand All @@ -37,4 +41,17 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.addFilterBefore(new LoggingFilter(), JwtRequestFilter.class);
return http.build();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("http://localhost:3000"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("*"));
config.setAllowCredentials(true);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
19 changes: 14 additions & 5 deletions src/main/java/edu/eci/cvds/prometeo/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@
*/
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
@Tag(name = "User Controller", description = "API for managing user profiles, physical tracking, goals, routines, and reservations")
public class UserController {

Expand Down Expand Up @@ -91,16 +90,26 @@ public class UserController {
@ApiResponse(responseCode = "200", description = "User found", content = @Content(schema = @Schema(implementation = User.class)))
@ApiResponse(responseCode = "404", description = "User not found")
public ResponseEntity<User> getUserById(@Parameter(description = "User ID") @PathVariable String id) {
return ResponseEntity.ok(userService.getUserById(id));
try {
User user = userService.getUserById(id);
return ResponseEntity.ok(user);
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
}

@GetMapping("/by-institutional-id/{institutionalId}")
@Operation(summary = "Get user by institutional ID", description = "Retrieves a user by their institutional identifier")
@ApiResponse(responseCode = "200", description = "User found", content = @Content(schema = @Schema(implementation = User.class)))
@ApiResponse(responseCode = "404", description = "User not found")
public ResponseEntity<User> getUserByInstitutionalId(
public ResponseEntity<?> getUserByInstitutionalId(
@Parameter(description = "Institutional ID") @PathVariable String institutionalId) {
return ResponseEntity.ok(userService.getUserByInstitutionalId(institutionalId));
try {
User user = userService.getUserByInstitutionalId(institutionalId);
return ResponseEntity.ok(user);
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
}
}

@GetMapping
Expand Down Expand Up @@ -858,7 +867,7 @@ public ResponseEntity<Object> cancelSession(
@GetMapping("/trainer/sessions")
@Operation(summary = "Get sessions by date", description = "Retrieves all gym sessions for a specific date")
@ApiResponse(responseCode = "200", description = "Sessions retrieved successfully")
@PreAuthorize("hasRole('TRAINER') or hasRole('ADMIN')")
@PreAuthorize("hasRole('TRAINER') or hasRole('ADMIN') or hasRole('STUDENT')")
public ResponseEntity<List<Object>> getSessionsByDate(
@Parameter(description = "Date to check") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/edu/eci/cvds/prometeo/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class User extends BaseEntity {
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;

@Column(name = "instutional_id", unique = true, nullable = false)
@Column(name = "institutional_id", unique = true, nullable = false)
private String institutionalId;

@Column(name = "name", nullable = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ void testGetUserById() {
public void testGetUserByInstitutionalId() {
when(userService.getUserByInstitutionalId(anyString())).thenReturn(testUser);

ResponseEntity<User> response = userController.getUserByInstitutionalId("A12345");
ResponseEntity<User> response = (ResponseEntity<User>) userController.getUserByInstitutionalId("A12345");

assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(testUser, response.getBody());
Expand Down