From 3b7dc413a08176856cd49bbfc4a950bbca2be58f Mon Sep 17 00:00:00 2001
From: birkon <birkon@stud.ntnu.no>
Date: Tue, 2 May 2023 16:59:26 +0200
Subject: [PATCH] fixed add and delete allergy

---
 .../controller/user/UserController.java       | 34 +++++-----
 .../v233/SmartMat/entity/product/Allergy.java | 12 ++++
 .../v233/SmartMat/entity/user/User.java       |  3 +-
 .../SmartMat/service/user/UserService.java    | 65 ++++++++-----------
 4 files changed, 59 insertions(+), 55 deletions(-)

diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/user/UserController.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/user/UserController.java
index 9bb5d58d..15290417 100644
--- a/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/user/UserController.java
+++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/user/UserController.java
@@ -6,16 +6,19 @@ import ntnu.idatt2016.v233.SmartMat.dto.request.AllergyRequest;
 import ntnu.idatt2016.v233.SmartMat.dto.request.RegisterUserRequest;
 import ntnu.idatt2016.v233.SmartMat.dto.enums.Authority;
 import ntnu.idatt2016.v233.SmartMat.dto.request.UpdateUserRequest;
+import ntnu.idatt2016.v233.SmartMat.entity.product.Allergy;
 import ntnu.idatt2016.v233.SmartMat.entity.user.User;
 import ntnu.idatt2016.v233.SmartMat.service.user.UserService;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
 import org.springframework.security.core.Authentication;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
 import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.web.bind.annotation.*;
 
 import java.util.ArrayList;
 import java.util.Optional;
+import java.util.stream.Collectors;
 
 
 /**
@@ -105,14 +108,13 @@ public class UserController {
      * @return a ResponseEntity with a boolean indicating whether the operation was successful
      */
     @PostMapping("/addAllergy")
-    public ResponseEntity<Boolean> addAllergyToUser(@RequestBody AllergyRequest allergyRequest) {
-        try {
-            return userService.addAllergyToUser(allergyRequest.getUsername(), allergyRequest.getAllergyName())
-                    .map(user -> ResponseEntity.ok(user.getAllergies().size() > 0))
-                    .orElseGet(() -> ResponseEntity.notFound().build());
-        }catch (Exception e){
-            return ResponseEntity.status(409).body(false);
-        }
+    public ResponseEntity<String> addAllergyToUser(@RequestBody AllergyRequest allergyRequest,
+                                                    Authentication authentication) {
+        if(!allergyRequest.getUsername().equals(authentication.getName()) &&
+                !authentication.getAuthorities().contains(new SimpleGrantedAuthority(Authority.ADMIN.name())))
+            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
+
+        return userService.addAllergyToUser(allergyRequest.getUsername(), allergyRequest.getAllergyName());
     }
 
     /**
@@ -122,14 +124,14 @@ public class UserController {
      * @return a ResponseEntity with a boolean indicating whether the operation was successful
      */
     @DeleteMapping("/deleteAllergy")
-    public ResponseEntity<Boolean> deleteAllergyFromUser(@RequestBody AllergyRequest allergyRequest) {
-        try {
-            return userService.deleteAllergy(allergyRequest.getUsername(), allergyRequest.getAllergyName())
-                    .map(user -> ResponseEntity.ok(true))
-                    .orElseGet(() -> ResponseEntity.notFound().build());
-        }catch (Exception e){
-            return ResponseEntity.status(409).body(false);
-        }
+    public ResponseEntity<String> deleteAllergyFromUser(@RequestBody AllergyRequest allergyRequest,
+                                                         Authentication authentication) {
+        if(!allergyRequest.getUsername().equals(authentication.getName()) &&
+                !authentication.getAuthorities().contains(new SimpleGrantedAuthority(Authority.ADMIN.name())))
+            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
+
+        return userService.removeAllergyFromUser(allergyRequest.getUsername(), allergyRequest.getAllergyName());
+
     }
 
 
diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/product/Allergy.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/product/Allergy.java
index 77870ee4..dc776c20 100644
--- a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/product/Allergy.java
+++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/product/Allergy.java
@@ -9,6 +9,7 @@ import lombok.Data;
 import lombok.NoArgsConstructor;
 import ntnu.idatt2016.v233.SmartMat.entity.user.User;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -49,4 +50,15 @@ public class Allergy{
     @JsonIgnore
     private List<User> users;
 
+    /**
+     * adds a user to the allergy
+     * @param tempuser adds a user to the list of users with this allergy
+     */
+    public void addUser(User tempuser) {
+        if (users == null)
+            users = new ArrayList<>();
+
+        users.add(tempuser);
+
+    }
 }
\ No newline at end of file
diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/user/User.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/user/User.java
index 88646b27..e857f458 100644
--- a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/user/User.java
+++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/user/User.java
@@ -60,7 +60,8 @@ public class User implements UserDetails {
     private List<UserGroupAsso> group;
 
 
-    @ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH},
+    @ManyToMany(fetch = FetchType.LAZY,
+            cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH},
             mappedBy = "users")
     @JsonIgnoreProperties({"users", "products"})
     private List<Allergy> allergies;
diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/service/user/UserService.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/service/user/UserService.java
index 5e900fca..3c21d197 100644
--- a/src/main/java/ntnu/idatt2016/v233/SmartMat/service/user/UserService.java
+++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/service/user/UserService.java
@@ -8,6 +8,8 @@ import ntnu.idatt2016.v233.SmartMat.entity.user.User;
 import ntnu.idatt2016.v233.SmartMat.repository.AllergyRepository;
 import ntnu.idatt2016.v233.SmartMat.repository.user.UserRepository;
 import ntnu.idatt2016.v233.SmartMat.service.RecipeService;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.stereotype.Service;
 
@@ -132,23 +134,27 @@ public class UserService {
      * Adds allergy to user
      * @param username username of user
      * @param allergyName name of allergy
-     * @return user with added allergy
-     * @throws EntityNotFoundException if user or allergy does not exist
+     * @return string of allergies
      */
-    public Optional<User> addAllergyToUser(String username, String allergyName){
+    public ResponseEntity<String> addAllergyToUser(String username, String allergyName){
 
         Optional<User> user = userRepository.findByUsername(username);
         Optional<Allergy> allergy = allergyRepository.findByName(allergyName);
 
         if (user.isPresent() && allergy.isPresent()){
-            user.get().addAllergy(allergy.get());
-            return Optional.of(userRepository.save(user.get()));
-        } else if (!user.isPresent()) {
-            throw new EntityNotFoundException("User not found");
-        } else if (!allergy.isPresent()) {
-            throw new EntityNotFoundException("Allergy not found");
+            if(user.get().getAllergies().contains(allergy.get())
+                    || allergy.get().getUsers().contains(user.get()))
+                return ResponseEntity.status(HttpStatus.NOT_MODIFIED)
+                        .body("User already has this allergy");
+
+            User tempuser = user.get();
+            allergy.get().addUser(tempuser);
+            tempuser.addAllergy(allergy.get());
+            return ResponseEntity.ok(userRepository.save(tempuser).getAllergies().stream()
+                    .map(Allergy::getName)
+                    .reduce("", (a, b) -> a + " " + b));
         }
-        return Optional.empty();
+        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Did not find allergy, our user");
     }
 
     /**
@@ -157,40 +163,23 @@ public class UserService {
      * @param allergyName name of allergy
      * @return user with removed allergy
      */
-    public Optional<User> removeAllergyFromUser(String username, String allergyName){
+    public ResponseEntity<String> removeAllergyFromUser(String username, String allergyName){
         Optional<User> user = userRepository.findByUsername(username);
         Optional<Allergy> allergy = allergyRepository.findByName(allergyName);
 
         if (user.isPresent() && allergy.isPresent()){
+            if (!user.get().getAllergies().contains(allergy.get())
+                    || !allergy.get().getUsers().contains(user.get()))
+                return ResponseEntity.status(HttpStatus.NOT_MODIFIED)
+                        .body("User does not have this allergy");
+
             user.get().getAllergies().remove(allergy.get());
-            return Optional.of(userRepository.save(user.get()));
-        } else if (user.isEmpty()) {
-            throw new EntityNotFoundException("User not found");
-        } else if (allergy.isEmpty()) {
-            throw new EntityNotFoundException("Allergy not found");
+            allergy.get().getUsers().remove(user.get());
+            return ResponseEntity.ok(userRepository.save(user.get()).getAllergies().stream()
+                    .map(Allergy::getName)
+                    .reduce("", (a, b) -> a + " " + b));
         }
-        return Optional.empty();
+        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Did not find allergy, our user");
     }
 
-    /**
-     * Deletes the specified allergy from the user with the given username.
-     *
-     * @param username the username of the user to delete the allergy from
-     * @param allergyName the name of the allergy to delete
-     * @return an Optional containing the updated User object if the operation was successful, or an empty Optional otherwise
-     * @throws EntityNotFoundException if the specified user or allergy cannot be found
-     */
-    public Optional<User> deleteAllergy(String username, String allergyName) {
-        Optional<User> user = userRepository.findByUsername(username);
-        Optional<Allergy> allergy = allergyRepository.findByName(allergyName);
-
-        if (user.isPresent() && allergy.isPresent()) {
-            if(user.get().deleteAllergy(allergy.get())) return Optional.of(userRepository.save(user.get()));
-        } else if (user.isEmpty()) {
-            throw new EntityNotFoundException("User not found");
-        } else {
-            throw new EntityNotFoundException("Allergy not found");
-        }
-        return Optional.empty();
-    }
 }
\ No newline at end of file
-- 
GitLab