Skip to content
Snippets Groups Projects
Commit 40d0b20f authored by Birk Øvstetun Narvhus's avatar Birk Øvstetun Narvhus
Browse files

Merge branch 'feature/226-add-leave-group-endpoint' into 'main'

Resolve "add leave group endpoint"

Closes #226

See merge request idatt2106-v23-03/backend!184
parents f70d3360 59747b97
No related branches found
No related tags found
No related merge requests found
......@@ -335,4 +335,49 @@ public class GroupController {
return ResponseEntity.ok(groupService.getUserGroupAssoByUserName(auth.getName()));
}
/**
* Handles the HTTP DELETE request to remove a user from a group.
* @param groupId the ID of the group to get the members of
* @param username the username of the user to remove from the group
* @param auth the authentication object containing the username of the user
* @return a ResponseEntity object containing the list of groups the
* user is associated with and an HTTP status code of 200,
*/
@DeleteMapping("/removeUser/{groupId}/{username}")
public ResponseEntity<?> removeUserFromGroup(@PathVariable("groupId") long groupId,
@PathVariable("username") String username,
Authentication auth) {
Optional<User> groupAdminOpt = userService.getUserFromUsername(auth.getName());
if (groupAdminOpt.isPresent()) {
User groupAdmin = groupAdminOpt.get();
if (!(groupService.isUserAssociatedWithGroup(groupAdmin.getUsername(), groupId)
&& (groupService.getUserGroupAssoAuthority(groupAdmin.getUsername(), groupId).equals("ADMIN"))
|| groupAdmin.getUsername().equals(username)))
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("You are not authorized to remove this user.");
}
Optional<Group> groupOpt = groupService.getGroupById(groupId);
Optional<User> userOpt = userService.getUserFromUsername(username);
if (groupOpt.isEmpty() || userOpt.isEmpty()) {
return ResponseEntity.notFound().build();
}
User user = userOpt.get();
UserGroupAsso userGroupAsso = user.getGroup().stream()
.filter(asso -> asso.getGroup().getGroupId() == groupId)
.findFirst()
.orElse(null);
if (userGroupAsso != null) {
groupService.removeUserFromGroup(userGroupAsso);
return ResponseEntity.ok("User removed successfully.");
} else {
return ResponseEntity.notFound().build();
}
}
}
......@@ -56,8 +56,10 @@ public class Group {
private ShoppingList shoppingList;
@OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH},
fetch = FetchType.LAZY, mappedBy = "group")
@OneToMany(cascade = {CascadeType.ALL},
fetch = FetchType.LAZY, mappedBy = "group",
orphanRemoval = true
)
@JsonIgnoreProperties("group")
private List<UserGroupAsso> user = new ArrayList<>();
......
......@@ -55,8 +55,7 @@ public class User implements UserDetails {
private Date dateOfBirth;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "username")
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
@JsonIgnore
private List<UserGroupAsso> group;
......
package ntnu.idatt2016.v233.SmartMat.service.group;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import ntnu.idatt2016.v233.SmartMat.entity.ShoppingList;
import ntnu.idatt2016.v233.SmartMat.entity.group.Fridge;
......@@ -229,4 +230,27 @@ public class GroupService {
public List<UserGroupAsso> getUserGroupAssoByUserName(String username) {
return userGroupAssoRepository.findAllByUserUsername(username);
}
/**
* removes user_group relatioon
* @param username the username of the user
* @param groupId the id of the group
* @return true if the user is the owner of the group, false otherwise
*/
@Transactional
public boolean removeUserFromGroup(UserGroupAsso userGroup) {
Group group = groupRepository.findByGroupId(userGroup.getGroup().getGroupId())
.orElseThrow(() -> new IllegalArgumentException("Group does not exist"));
group.getUser().remove(userGroup);
if (group.getUser().isEmpty()) {
groupRepository.delete(group);
} else {
groupRepository.save(group);
}
userGroupAssoRepository.delete(userGroup);
return true;
}
}
......@@ -106,24 +106,22 @@ public class GroupRepositoryTest {
@Test
void groupShouldHaveAchivments(){
Optional<Group> tempGroupe = groupRepository.findByGroupName("test");
assertTrue(tempGroupe.isPresent());
Group tempgroup = Group.builder().groupName("testiossxjak").build();
Achievement tempAchievement = Achievement.builder().achievementName("test2").build();
Group tempGroup = tempGroupe.get();
tempgroup.setAchievements(new ArrayList<>(Collections.singletonList(tempAchievement)));
groupRepository.save(tempgroup);
tempGroup.setAchievements(new ArrayList<>(Collections.singletonList(tempAchievement)));
Optional<Group> tempGroupe = groupRepository.findByGroupName("testiossxjak");
groupRepository.save(tempGroup);
assertTrue(groupRepository.findByGroupName("test").isPresent());
assertTrue(tempGroupe.isPresent());
assertTrue(groupRepository.findByGroupName("test").get().getAchievements().contains(tempAchievement));
assertTrue(tempGroupe.get().getAchievements().contains(tempAchievement));
assertNull(groupRepository.findByGroupName("test").get().getAchievements().get(0).getGroups());
assertNull(tempGroupe.get().getAchievements().get(0).getGroups());
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment