From bddfcd66d5977a4da29da74ab4301035f1fff240 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?R=C3=A9mi=20PAILHAREY?= <rpailharey@grandlyon.com>
Date: Wed, 21 Sep 2022 13:18:54 +0000
Subject: [PATCH] fix: getting consent with unknown id now returns 404

---
 internal/models/consent.go       | 7 ++++++-
 internal/rootmux/rootmux_test.go | 4 +++-
 2 files changed, 9 insertions(+), 2 deletions(-)

diff --git a/internal/models/consent.go b/internal/models/consent.go
index e7ed2da..c76ed46 100644
--- a/internal/models/consent.go
+++ b/internal/models/consent.go
@@ -2,6 +2,7 @@ package models
 
 import (
 	"encoding/json"
+	"errors"
 	"fmt"
 	"log"
 	"net/http"
@@ -34,7 +35,11 @@ func (dh *DataHandler) GetConsentById(w http.ResponseWriter, r *http.Request) {
 	var consent Consent
 	err = dh.sqlClient.First(&consent, id).Error
 	if err != nil {
-		http.Error(w, "couldn't find consent", http.StatusInternalServerError)
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			http.Error(w, "consent not found", http.StatusNotFound)
+			return
+		}
+		http.Error(w, "error while finding consent", http.StatusInternalServerError)
 		return
 	}
 
diff --git a/internal/rootmux/rootmux_test.go b/internal/rootmux/rootmux_test.go
index d6ee76e..f22c2cf 100644
--- a/internal/rootmux/rootmux_test.go
+++ b/internal/rootmux/rootmux_test.go
@@ -245,8 +245,10 @@ func sgeTests(t *testing.T) {
 	time.Sleep(1 * time.Second)
 	// Try to update a consent  (must pass)
 	do("PUT", "/api/sge/consent/1", sgeApiHeader, `{"serviceId":123456}`, http.StatusOK, `{"ID":1`)
+	// Try to get a consent that doesn't exist (must fail not found)
+	do("GET", "/api/sge/consent/123456", sgeApiHeader, "", http.StatusNotFound, `consent not found`)
 	// Try to get a consent  (must pass)
-	do("GET", "/api/sge/consent/1", sgeApiHeader, `{"serviceId":123456}`, http.StatusOK, `{"ID":1`)
+	do("GET", "/api/sge/consent/1", sgeApiHeader, "", http.StatusOK, `{"ID":1`)
 
 	// Try to login (must pass)
 	do("GET", "/OAuth2Login", noH, "", http.StatusOK, "")
-- 
GitLab