Skip to content

Commit de5a13a

Browse files
Merge pull request #14 from Equipe-Meta-Code/dev
Dev
2 parents 48bc1bd + f55c891 commit de5a13a

File tree

8 files changed

+125
-94
lines changed

8 files changed

+125
-94
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package metacode.com.nutrimind.config;
2+
3+
import com.fasterxml.jackson.databind.ObjectMapper;
4+
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
5+
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.Configuration;
8+
import org.springframework.context.annotation.Primary;
9+
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
10+
11+
@Configuration
12+
public class JacksonConfig {
13+
14+
@Bean
15+
@Primary
16+
public ObjectMapper objectMapper() {
17+
return Jackson2ObjectMapperBuilder.json()
18+
.modules(new JavaTimeModule())
19+
.propertyNamingStrategy(PropertyNamingStrategies.LOWER_CAMEL_CASE)
20+
.build();
21+
}
22+
}

src/main/java/metacode/com/nutrimind/controller/HealthProfileController.java

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public ResponseEntity<List<HealthProfileResponseDTO>> getAllHealthProfiles() {
6363
}
6464

6565
@GetMapping("/{id}")
66-
@PreAuthorize("hasRole('Admin') or hasRole('Nutricionista') or @authService.isOwnerOrAdmin(#id)")
66+
@PreAuthorize("hasRole('Admin') or hasRole('Nutricionista') or @authService.isOwnerOfProfile(#id)")
6767
@Operation(summary = "Buscar perfil por ID", description = "Retorna um perfil de saúde específico pelo seu ID")
6868
@SecurityRequirement(name = "Bearer Authentication")
6969
@ApiResponses(value = {
@@ -165,7 +165,7 @@ public ResponseEntity<HealthProfileResponseDTO> createHealthProfile(
165165
}
166166

167167
@PutMapping("/{id}")
168-
@PreAuthorize("hasRole('Admin') or hasRole('Nutricionista') or @authService.isOwnerOrAdmin(#id)")
168+
@PreAuthorize("hasRole('Admin') or hasRole('Nutricionista') or @authService.isOwnerOfProfile(#id)")
169169
@Operation(summary = "Atualizar perfil por ID", description = "Atualiza um perfil de saúde pelo seu ID")
170170
@SecurityRequirement(name = "Bearer Authentication")
171171
public ResponseEntity<HealthProfileResponseDTO> updateHealthProfile(
@@ -347,56 +347,57 @@ public ResponseEntity<Void> removeDiseaseFromProfile(@PathVariable Long profileI
347347
}
348348

349349
@PostMapping("/{profileId}/allergies/{allergyId}")
350-
@PreAuthorize("isAuthenticated()")
351-
@Operation(summary = "Adicionar alergia a um perfil")
350+
@PreAuthorize("hasRole('Admin') or @authService.isOwnerOfProfile(#profileId)")
351+
@Operation(summary = "Adicionar alergia a um perfil", description = "Associa uma alergia existente a um perfil de saúde")
352352
@SecurityRequirement(name = "Bearer Authentication")
353353
public ResponseEntity<Void> addAllergyToProfile(@PathVariable Long profileId, @PathVariable Long allergyId) {
354354
healthProfileService.addAllergyToProfile(profileId, allergyId);
355355
return ResponseEntity.ok().build();
356356
}
357357

358358
@DeleteMapping("/{profileId}/allergies/{allergyId}")
359-
@PreAuthorize("isAuthenticated()")
360-
@Operation(summary = "Remover alergia de um perfil")
359+
@PreAuthorize("hasRole('Admin') or @authService.isOwnerOfProfile(#profileId)")
360+
@Operation(summary = "Remover alergia de um perfil", description = "Desassocia uma alergia de um perfil de saúde")
361361
@SecurityRequirement(name = "Bearer Authentication")
362362
public ResponseEntity<Void> removeAllergyFromProfile(@PathVariable Long profileId, @PathVariable Long allergyId) {
363363
healthProfileService.removeAllergyFromProfile(profileId, allergyId);
364364
return ResponseEntity.noContent().build();
365365
}
366366

367+
// Endpoints para Intolerâncias
367368
@PostMapping("/{profileId}/intolerances/{intoleranceId}")
368-
@PreAuthorize("isAuthenticated()")
369-
@Operation(summary = "Adicionar intolerância a um perfil")
369+
@PreAuthorize("hasRole('Admin') or @authService.isOwnerOfProfile(#profileId)")
370+
@Operation(summary = "Adicionar intolerância a um perfil", description = "Associa uma intolerância existente a um perfil de saúde")
370371
@SecurityRequirement(name = "Bearer Authentication")
371372
public ResponseEntity<Void> addIntoleranceToProfile(@PathVariable Long profileId, @PathVariable Long intoleranceId) {
372373
healthProfileService.addIntoleranceToProfile(profileId, intoleranceId);
373374
return ResponseEntity.ok().build();
374375
}
375376

376377
@DeleteMapping("/{profileId}/intolerances/{intoleranceId}")
377-
@PreAuthorize("isAuthenticated()")
378-
@Operation(summary = "Remover intolerância de um perfil")
378+
@PreAuthorize("hasRole('Admin') or @authService.isOwnerOfProfile(#profileId)")
379+
@Operation(summary = "Remover intolerância de um perfil", description = "Desassocia uma intolerância de um perfil de saúde")
379380
@SecurityRequirement(name = "Bearer Authentication")
380381
public ResponseEntity<Void> removeIntoleranceFromProfile(@PathVariable Long profileId, @PathVariable Long intoleranceId) {
381382
healthProfileService.removeIntoleranceFromProfile(profileId, intoleranceId);
382383
return ResponseEntity.noContent().build();
383384
}
384385

385-
@PostMapping("/{profileId}/dietary-preferences/{preferenceId}")
386-
@PreAuthorize("isAuthenticated()")
387-
@Operation(summary = "Adicionar preferência alimentar a um perfil")
386+
@PostMapping("/{profileId}/dietary-preferences/{dietaryPreferenceId}")
387+
@PreAuthorize("hasRole('Admin') or @authService.isOwnerOfProfile(#profileId)")
388+
@Operation(summary = "Adicionar preferência alimentar a um perfil", description = "Associa uma preferência alimentar existente a um perfil de saúde")
388389
@SecurityRequirement(name = "Bearer Authentication")
389-
public ResponseEntity<Void> addDietaryPreferenceToProfile(@PathVariable Long profileId, @PathVariable Long preferenceId) {
390-
healthProfileService.addDietaryPreferenceToProfile(profileId, preferenceId);
390+
public ResponseEntity<Void> addDietaryPreferenceToProfile(@PathVariable Long profileId, @PathVariable Long dietaryPreferenceId) {
391+
healthProfileService.addDietaryPreferenceToProfile(profileId, dietaryPreferenceId);
391392
return ResponseEntity.ok().build();
392393
}
393394

394-
@DeleteMapping("/{profileId}/dietary-preferences/{preferenceId}")
395-
@PreAuthorize("isAuthenticated()")
396-
@Operation(summary = "Remover preferência alimentar de um perfil")
395+
@DeleteMapping("/{profileId}/dietary-preferences/{dietaryPreferenceId}")
396+
@PreAuthorize("hasRole('Admin') or @authService.isOwnerOfProfile(#profileId)")
397+
@Operation(summary = "Remover preferência alimentar de um perfil", description = "Desassocia uma preferência alimentar de um perfil de saúde")
397398
@SecurityRequirement(name = "Bearer Authentication")
398-
public ResponseEntity<Void> removeDietaryPreferenceFromProfile(@PathVariable Long profileId, @PathVariable Long preferenceId) {
399-
healthProfileService.removeDietaryPreferenceFromProfile(profileId, preferenceId);
399+
public ResponseEntity<Void> removeDietaryPreferenceFromProfile(@PathVariable Long profileId, @PathVariable Long dietaryPreferenceId) {
400+
healthProfileService.removeDietaryPreferenceFromProfile(profileId, dietaryPreferenceId);
400401
return ResponseEntity.noContent().build();
401402
}
402403
}

src/main/java/metacode/com/nutrimind/dto/healthprofile/HealthProfileCreateDTO.java

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,27 +20,36 @@ public class HealthProfileCreateDTO {
2020
private Long userId;
2121

2222
@PastOrPresent(message = "Data de nascimento deve ser no passado")
23+
@JsonProperty("birthDate")
2324
private LocalDate birthDate;
2425

26+
@JsonProperty("gender")
2527
private Gender gender;
2628

2729
@DecimalMin(value = "1.0", message = "Peso deve ser maior que 1kg")
2830
@DecimalMax(value = "999.99", message = "Peso deve ser menor que 1000kg")
31+
@JsonProperty("weight")
2932
private BigDecimal weight;
3033

3134
@DecimalMin(value = "1.0", message = "Peso deve ser maior que 1kg")
3235
@DecimalMax(value = "999.99", message = "Peso deve ser menor que 1000kg")
36+
@JsonProperty("maxWeight")
3337
private BigDecimal maxWeight;
3438

3539
@DecimalMin(value = "1.0", message = "Peso deve ser maior que 1kg")
3640
@DecimalMax(value = "999.99", message = "Peso deve ser menor que 1000kg")
41+
@JsonProperty("minWeight")
3742
private BigDecimal minWeight;
3843

3944
@DecimalMin(value = "0.5", message = "Altura deve ser maior que 0.5m")
4045
@DecimalMax(value = "3.0", message = "Altura deve ser menor que 3m")
46+
@JsonProperty("height")
4147
private BigDecimal height;
4248

49+
@JsonProperty("activityLevel")
4350
private ActivityLevel activityLevel;
51+
52+
@JsonProperty("goal")
4453
private Goal goal;
4554

4655
public HealthProfileCreateDTO() {
@@ -126,7 +135,7 @@ public Goal getGoal() {
126135
return goal;
127136
}
128137

129-
public void setGoals(Goal goal) {
138+
public void setGoal(Goal goal) {
130139
this.goal = goal;
131140
}
132141

@@ -137,8 +146,8 @@ public String toString() {
137146
", birthDate=" + birthDate +
138147
", gender='" + gender + '\'' +
139148
", weight=" + weight +
140-
", maxWeight" + maxWeight +
141-
", minWeight" + minWeight +
149+
", maxWeight=" + maxWeight +
150+
", minWeight=" + minWeight +
142151
", height=" + height +
143152
", activityLevel='" + activityLevel + '\'' +
144153
", goal='" + goal + '\'' +

src/main/java/metacode/com/nutrimind/service/impl/AuthService.java

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@
44
import metacode.com.nutrimind.dto.auth.LoginRequestDTO;
55
import metacode.com.nutrimind.dto.user.UserResponseDTO;
66
import metacode.com.nutrimind.dto.user.UserCreateDTO;
7+
import metacode.com.nutrimind.dto.healthprofile.HealthProfileResponseDTO;
78
import metacode.com.nutrimind.entity.Role;
89
import metacode.com.nutrimind.entity.User;
910
import metacode.com.nutrimind.service.interfaces.IAuthService;
1011
import metacode.com.nutrimind.repository.RoleRepository;
1112
import metacode.com.nutrimind.repository.UserRepository;
1213
import metacode.com.nutrimind.security.JwtTokenProvider;
1314
import metacode.com.nutrimind.service.interfaces.IUserService;
15+
import metacode.com.nutrimind.service.interfaces.IHealthProfileService;
1416
import org.springframework.beans.factory.annotation.Autowired;
1517
import org.springframework.security.authentication.AuthenticationManager;
1618
import org.springframework.security.authentication.BadCredentialsException;
@@ -36,17 +38,20 @@ public class AuthService implements IAuthService {
3638
private final AuthenticationManager authenticationManager;
3739
private final JwtTokenProvider jwtTokenProvider;
3840
private final IUserService userService;
41+
private final IHealthProfileService healthProfileService;
3942

4043
@Autowired
4144
public AuthService(UserRepository userRepository, RoleRepository roleRepository,
4245
PasswordEncoder passwordEncoder, AuthenticationManager authenticationManager,
43-
JwtTokenProvider jwtTokenProvider, IUserService userService) {
46+
JwtTokenProvider jwtTokenProvider, IUserService userService,
47+
IHealthProfileService healthProfileService) {
4448
this.userRepository = userRepository;
4549
this.roleRepository = roleRepository;
4650
this.passwordEncoder = passwordEncoder;
4751
this.authenticationManager = authenticationManager;
4852
this.jwtTokenProvider = jwtTokenProvider;
4953
this.userService = userService;
54+
this.healthProfileService = healthProfileService;
5055
}
5156

5257
public LoginResponseDTO login(LoginRequestDTO loginRequestDTO) {
@@ -167,14 +172,15 @@ public boolean isOwnerOrAdmin(Long userId) {
167172
UserResponseDTO user = currentUser.get();
168173
return user.getId().equals(userId) || user.getRole().getName().equals("admin");
169174
}
170-
175+
171176
@Transactional(readOnly = true)
172-
public boolean isOwnerByUserId(Long userId) {
173-
Optional<UserResponseDTO> currentUserOpt = getCurrentUser();
174-
if (currentUserOpt.isEmpty()) {
177+
public boolean isOwnerOfProfile(Long profileId) {
178+
Optional<HealthProfileResponseDTO> profileOpt = healthProfileService.findById(profileId);
179+
if (profileOpt.isEmpty()) {
175180
return false;
176181
}
177-
return currentUserOpt.get().getId().equals(userId);
182+
183+
return isOwnerOrAdmin(profileOpt.get().getUserId());
178184
}
179185

180186
public void logout() {

0 commit comments

Comments
 (0)