From 989bd7701b119c321d15880314e698167064d130 Mon Sep 17 00:00:00 2001
From: Florent Gluck <florent.gluck@hesge.ch>
Date: Thu, 24 Nov 2022 17:27:28 +0100
Subject: [PATCH] Updated vms.DeleteVMAccess(..) so that even a user who
 doesn't exist anymore can be removed from a VM's access. Also, returns an
 error if trying to remove an user access for a user that's not present in the
 VM's accesses.

---
 src/router/routerVMs.go | 7 ++-----
 src/vms/vms.go          | 8 ++++++--
 2 files changed, 8 insertions(+), 7 deletions(-)

diff --git a/src/router/routerVMs.go b/src/router/routerVMs.go
index dc634e3..bd94f5c 100644
--- a/src/router/routerVMs.go
+++ b/src/router/routerVMs.go
@@ -358,12 +358,9 @@ func (r *RouterVMs)DeleteVMAccessForUser(c echo.Context) error {
 		return echo.NewHTTPError(http.StatusUnauthorized, msgInsufficientCaps)
 	}
 
-	// Checks the user for which to modify the VM Access actually exists.
+	// Does not check that the user to remove the VM access for actually exists.
+	// Indeed, it might have been deleted.
 	email := c.Param("email")
-	_, err = r.users.GetUserByEmail(email)
-	if err != nil {
-		return echo.NewHTTPError(http.StatusNotFound, err.Error())
-	}
 
 	// Retrieves the vmID of the VM to modify.
 	vmID, err := uuid.Parse(c.Param("id"))
diff --git a/src/vms/vms.go b/src/vms/vms.go
index 475d678..7a1dc01 100644
--- a/src/vms/vms.go
+++ b/src/vms/vms.go
@@ -379,8 +379,12 @@ func (vms *VMs)DeleteVMAccess(vmID uuid.UUID, loggedUserEmail, userEmail string)
 		return errors.New("Insufficient capability")
 	}
 
-	// Removes the user from the Access map
-	delete(vm.Access, userEmail)
+	// Only removes the user from the Access map if it actually had an access.
+	if _, exists := vm.Access[userEmail]; exists {
+		delete(vm.Access, userEmail)
+	} else {
+		return errors.New("User "+userEmail+" has no VM access")
+	}
 
 	if err = vms.updateVM(&vm); err != nil {
 		return err
-- 
GitLab