diff --git a/internal/auth/auth.go b/internal/auth/auth.go index ed83d4e2e732c62a91b125e10ab66c2a2e875e91..860511c060dda2a24bec483dee7ccbde5f074ccd 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -117,7 +117,7 @@ func ValidateAuthMiddleware(next http.Handler, allowedRoles []string, checkXSRF return http.HandlerFunc(roleChecker) } -func SGEAuthMiddleware(next http.Handler) http.Handler { +func BOAuthMiddleware(next http.Handler) http.Handler { tokenChecker := func(w http.ResponseWriter, r *http.Request) { // Check API Token if r.Header.Get("Authorization") != "Bearer "+SGEApiToken { diff --git a/internal/models/grdfConsent.go b/internal/models/grdfConsent.go new file mode 100644 index 0000000000000000000000000000000000000000..1316a842ff9d0924d1d9a582a428aed6c919bf46 --- /dev/null +++ b/internal/models/grdfConsent.go @@ -0,0 +1,192 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "net/http" + "time" + + "forge.grandlyon.com/web-et-numerique/factory/llle_project/backoffice-server/internal/common" + "forge.grandlyon.com/web-et-numerique/factory/llle_project/backoffice-server/internal/constants" + "gorm.io/gorm" +) + +type GrdfConsent struct { + Base + Firstname string `json:"firstname"` + Lastname string `json:"lastname"` + Pce string `json:"pce"` + PostalCode string `json:"postalCode"` + StartDate time.Time `json:"startDate"` + EndDate time.Time `json:"endDate"` +} + +// This type is only used for Swagger documentation +type GrdfConsentSwagger struct { + ID int `json:"ID"` + CreatedAt time.Time `json:"CreatedAt"` + UpdatedAt time.Time `json:"UpdatedAt"` + DeletedAt time.Time `json:"DeletedAt"` + Firstname string `json:"firstname"` + Lastname string `json:"lastname"` + Pce string `json:"pce"` + PostalCode string `json:"postalCode"` + StartDate time.Time `json:"startDate"` + EndDate time.Time `json:"endDate"` +} + +// GetConsentById godoc +// +// @Summary Get details of a specific consent +// @Description Get details of a specific consent +// @Tags consent +// @Produce json +// @Success 200 {object} GrdfConsentSwagger +// @Failure 404 {string} string "Not found" +// @Param id path int true "ID of the consent" +// @Router /api/grdf/consent/{id} [get] +func (dh *DataHandler) GetGrdfConsentById(w http.ResponseWriter, r *http.Request) { + id, err := common.IdFromRequest(r) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + var consent GrdfConsent + err = dh.sqlClient.First(&consent, "id = ?", id).Error + if err != nil { + 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 + } + + w.Header().Set(constants.ContentType, constants.Json) + json.NewEncoder(w).Encode(consent) + + log.Printf("| get consent | name : %v | %v", consent.Lastname, r.RemoteAddr) +} + +// PostConsent godoc +// +// @Summary Create a new consent +// @Description Create a new consent +// @Tags consent +// @Produce json +// @Success 201 {object} GrdfConsentSwagger +// @Failure 400 {string} string "Bad request" +// @Failure 500 {string} string "couldn't create consent" +// @Param id path int true "ID of the consent" +// @Router /api/grdf/consent [post] +func (dh *DataHandler) PostGrdfConsent(w http.ResponseWriter, r *http.Request) { + if r.Body == http.NoBody { + http.Error(w, "request body is empty", http.StatusBadRequest) + return + } + + decoder := json.NewDecoder(r.Body) + var consent GrdfConsent + err := decoder.Decode(&consent) + if err != nil { + http.Error(w, "couldn't parse body", http.StatusInternalServerError) + log.Println(err.Error()) + return + } + + // Create a consent in SQL + err = dh.sqlClient.Create(&consent).Error + if err != nil { + http.Error(w, "couldn't create consent", http.StatusInternalServerError) + log.Println(err.Error()) + return + } + + w.Header().Set(constants.ContentType, constants.Json) + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(consent) + + log.Printf("| new consent | name : %v | %v", consent.Lastname, r.RemoteAddr) +} + +// DeleteConsentById godoc +// +// @Summary Delete a specific consent +// @Description Delete a specific consent +// @Tags consent +// @Produce json +// @Success 200 {object} GrdfConsentSwagger +// @Failure 404 {string} string "Not found" +// @Failure 500 {string} string "Not found" +// @Param id path int true "ID of the consent" +// @Router /api/grdf/consent/{id} [delete] +func (dh *DataHandler) DeleteGrdfConsentById(w http.ResponseWriter, r *http.Request) { + id, err := common.IdFromRequest(r) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + var consent = GrdfConsent{} + err = dh.sqlClient.First(&consent, "id = ?", id).Error + if err != nil { + http.Error(w, "couldn't find consent", http.StatusInternalServerError) + log.Println(err.Error()) + return + } + + // Update and save consent in MySQL + consent.EndDate = time.Now() + err = dh.sqlClient.Save(&consent).Error + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Println(err.Error()) + return + } + + dh.sqlClient.Delete(&consent) + + log.Printf("| deleted consent | id : %v | %v", id, r.RemoteAddr) +} + +// SearchConsent godoc +// +// @Summary Search for consents +// @Description Search for consents based on the pointID +// @Tags consent +// @Produce json +// @Success 200 {array} GrdfConsentSwagger +// @Failure 400 {string} string "Not found" +// @Param search query string true "pointID to search" +// @Router /api/admin/consent [get] +func (dh *DataHandler) SearchGrdfConsent(w http.ResponseWriter, r *http.Request) { + search := r.URL.Query().Get("search") + + page, limit, err := common.PageLimitFromRequest(r) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + var totalRows int64 + dh.sqlClient.Unscoped().Model(GrdfConsent{}).Where("pce LIKE ?", "%"+search+"%").Count(&totalRows) + offset := page * limit + + var consents []GrdfConsent + dh.sqlClient.Unscoped().Order("created_at desc").Offset(offset).Limit(limit).Where("pce LIKE ?", "%"+search+"%").Find(&consents) + + var pagination struct { + TotalRows int64 `json:"totalRows"` + Rows []GrdfConsent `json:"rows"` + } + pagination.TotalRows = totalRows + pagination.Rows = consents + + w.Header().Set(constants.ContentType, constants.Json) + json.NewEncoder(w).Encode(pagination) + + log.Printf("| get all consents | limit : %d | page : %d | %v", limit, page, r.RemoteAddr) + +} diff --git a/internal/models/models.go b/internal/models/models.go index e82db3463ec4772766044562040ca05c96f276a4..96bda0af838f2e7f3528a7f7a2b1a93b6565dc6b 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -48,7 +48,8 @@ func NewDataHandler() *DataHandler { sqlClient.AutoMigrate(&PartnersInfo{}) sqlClient.AutoMigrate(&CustomPopup{}) sqlClient.AutoMigrate(&Price{}) - sqlClient.AutoMigrate(&Consent{}) + sqlClient.AutoMigrate(&SgeConsent{}) + sqlClient.AutoMigrate(&GrdfConsent{}) // Check if partners info already exists var partnersInfo PartnersInfo diff --git a/internal/models/consent.go b/internal/models/sgeConsent.go similarity index 85% rename from internal/models/consent.go rename to internal/models/sgeConsent.go index f7a528747e40aa97027c573088a5a4964752b1cf..da8ca65b382f7ec9aace48aacd92e90be22076df 100644 --- a/internal/models/consent.go +++ b/internal/models/sgeConsent.go @@ -20,7 +20,12 @@ type Base struct { DeletedAt gorm.DeletedAt `sql:"index"` } -type Consent struct { +func (b *Base) BeforeCreate(tx *gorm.DB) (err error) { + b.ID = uuid.NewString() + return +} + +type SgeConsent struct { Base Firstname string `json:"firstname"` Lastname string `json:"lastname"` @@ -35,7 +40,7 @@ type Consent struct { } // This type is only used for Swagger documentation -type ConsentSwagger struct { +type SgeConsentSwagger struct { ID int `json:"ID"` CreatedAt time.Time `json:"CreatedAt"` UpdatedAt time.Time `json:"UpdatedAt"` @@ -52,33 +57,28 @@ type ConsentSwagger struct { ServiceID int `json:"serviceID,omitempty"` } -type UpdateConsentBody struct { +type UpdateSgeConsentBody struct { ServiceID int `json:"serviceID"` } -func (b *Base) BeforeCreate(tx *gorm.DB) (err error) { - b.ID = uuid.NewString() - return -} - -// GetConsentById godoc +// GetSgeConsentById godoc // // @Summary Get details of a specific consent // @Description Get details of a specific consent // @Tags consent // @Produce json -// @Success 200 {object} ConsentSwagger +// @Success 200 {object} SgeConsentSwagger // @Failure 404 {string} string "Not found" // @Param id path int true "ID of the consent" // @Router /api/sge/consent/{id} [get] -func (dh *DataHandler) GetConsentById(w http.ResponseWriter, r *http.Request) { +func (dh *DataHandler) GetSgeConsentById(w http.ResponseWriter, r *http.Request) { id, err := common.IdFromRequest(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } - var consent Consent + var consent SgeConsent err = dh.sqlClient.First(&consent, "id = ?", id).Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { @@ -95,25 +95,25 @@ func (dh *DataHandler) GetConsentById(w http.ResponseWriter, r *http.Request) { log.Printf("| get consent | name : %v | %v", consent.Lastname, r.RemoteAddr) } -// PostConsent godoc +// PostSgeConsent godoc // // @Summary Create a new consent // @Description Create a new consent // @Tags consent // @Produce json -// @Success 201 {object} ConsentSwagger +// @Success 201 {object} SgeConsentSwagger // @Failure 400 {string} string "Bad request" // @Failure 500 {string} string "couldn't create consent" // @Param id path int true "ID of the consent" // @Router /api/sge/consent [post] -func (dh *DataHandler) PostConsent(w http.ResponseWriter, r *http.Request) { +func (dh *DataHandler) PostSgeConsent(w http.ResponseWriter, r *http.Request) { if r.Body == http.NoBody { http.Error(w, "request body is empty", http.StatusBadRequest) return } decoder := json.NewDecoder(r.Body) - var consent Consent + var consent SgeConsent err := decoder.Decode(&consent) if err != nil { http.Error(w, "couldn't parse body", http.StatusInternalServerError) @@ -137,19 +137,19 @@ func (dh *DataHandler) PostConsent(w http.ResponseWriter, r *http.Request) { log.Printf("| new consent | name : %v | %v", consent.Lastname, r.RemoteAddr) } -// UpdateConsent godoc +// UpdateSgeConsent godoc // // @Summary Update a consent, giving it a serviceID // @Description Update a consent, giving it a serviceID // @Tags consent // @Produce json -// @Success 200 {object} ConsentSwagger +// @Success 200 {object} SgeConsentSwagger // @Failure 400 {string} string "invalid service id" // @Failure 404 {string} string "couldn't find consent" // @Failure 500 {string} string "couldn't parse body" // @Param id body UpdateConsentBody true "service ID" // @Router /api/sge/consent [put] -func (dh *DataHandler) UpdateConsent(w http.ResponseWriter, r *http.Request) { +func (dh *DataHandler) UpdateSgeConsent(w http.ResponseWriter, r *http.Request) { if r.Body == http.NoBody { http.Error(w, "request body is empty", http.StatusBadRequest) return @@ -161,7 +161,7 @@ func (dh *DataHandler) UpdateConsent(w http.ResponseWriter, r *http.Request) { } // Find consent - var consent Consent + var consent SgeConsent err = dh.sqlClient.First(&consent, "id = ?", id).Error if err != nil { http.Error(w, "couldn't find consent", http.StatusNotFound) @@ -170,7 +170,7 @@ func (dh *DataHandler) UpdateConsent(w http.ResponseWriter, r *http.Request) { } // Get service ID decoder := json.NewDecoder(r.Body) - var body UpdateConsentBody + var body UpdateSgeConsentBody err = decoder.Decode(&body) if err != nil { http.Error(w, "couldn't parse body", http.StatusInternalServerError) @@ -196,25 +196,25 @@ func (dh *DataHandler) UpdateConsent(w http.ResponseWriter, r *http.Request) { log.Printf("| updated consent | name : %v | serviceID : %v | %v", consent.Lastname, consent.ServiceID, r.RemoteAddr) } -// DeleteConsentById godoc +// DeleteSgeConsentById godoc // // @Summary Delete a specific consent // @Description Delete a specific consent // @Tags consent // @Produce json -// @Success 200 {object} ConsentSwagger +// @Success 200 {object} SgeConsentSwagger // @Failure 404 {string} string "Not found" // @Failure 500 {string} string "Not found" // @Param id path int true "ID of the consent" // @Router /api/sge/consent/{id} [delete] -func (dh *DataHandler) DeleteConsentById(w http.ResponseWriter, r *http.Request) { +func (dh *DataHandler) DeleteSgeConsentById(w http.ResponseWriter, r *http.Request) { id, err := common.IdFromRequest(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } - var consent = Consent{} + var consent = SgeConsent{} err = dh.sqlClient.First(&consent, "id = ?", id).Error if err != nil { http.Error(w, "couldn't find consent", http.StatusInternalServerError) @@ -236,17 +236,17 @@ func (dh *DataHandler) DeleteConsentById(w http.ResponseWriter, r *http.Request) log.Printf("| deleted consent | id : %v | %v", id, r.RemoteAddr) } -// SearchConsent godoc +// SearchSgeConsent godoc // // @Summary Search for consents // @Description Search for consents based on the pointID // @Tags consent // @Produce json -// @Success 200 {array} ConsentSwagger +// @Success 200 {array} SgeConsentSwagger // @Failure 400 {string} string "Not found" // @Param search query string true "pointID to search" -// @Router /api/admin/consent [get] -func (dh *DataHandler) SearchConsent(w http.ResponseWriter, r *http.Request) { +// @Router /api/admin/sge/consent [get] +func (dh *DataHandler) SearchSgeConsent(w http.ResponseWriter, r *http.Request) { search := r.URL.Query().Get("search") page, limit, err := common.PageLimitFromRequest(r) @@ -256,15 +256,15 @@ func (dh *DataHandler) SearchConsent(w http.ResponseWriter, r *http.Request) { } var totalRows int64 - dh.sqlClient.Unscoped().Model(Consent{}).Where("point_id LIKE ?", "%"+search+"%").Count(&totalRows) + dh.sqlClient.Unscoped().Model(SgeConsent{}).Where("point_id LIKE ?", "%"+search+"%").Count(&totalRows) offset := page * limit - var consents []Consent + var consents []SgeConsent dh.sqlClient.Unscoped().Order("created_at desc").Offset(offset).Limit(limit).Where("point_id LIKE ?", "%"+search+"%").Find(&consents) var pagination struct { - TotalRows int64 `json:"totalRows"` - Rows []Consent `json:"rows"` + TotalRows int64 `json:"totalRows"` + Rows []SgeConsent `json:"rows"` } pagination.TotalRows = totalRows pagination.Rows = consents diff --git a/internal/rootmux/rootmux.go b/internal/rootmux/rootmux.go index 1d572e9fcab8fbaf61a1b4959c7632aee3848436..5eb4a4df94b6bc5030e7fc626d034933a3aa2269 100644 --- a/internal/rootmux/rootmux.go +++ b/internal/rootmux/rootmux.go @@ -80,15 +80,23 @@ func CreateRootMux() RootMux { r.Route("/api/admin", func(r chi.Router) { r.Use(auth.AdminAuthMiddleware) - r.Get("/consent", dh.SearchConsent) + r.Get("/sge/consent", dh.SearchSgeConsent) + r.Get("/grdf/consent", dh.SearchGrdfConsent) }) r.Route("/api/sge", func(r chi.Router) { - r.Use(auth.SGEAuthMiddleware) - r.Post("/consent", dh.PostConsent) - r.Get("/consent/{id}", dh.GetConsentById) - r.Put("/consent/{id}", dh.UpdateConsent) - r.Delete("/consent/{id}", dh.DeleteConsentById) + r.Use(auth.BOAuthMiddleware) + r.Post("/consent", dh.PostSgeConsent) + r.Get("/consent/{id}", dh.GetSgeConsentById) + r.Put("/consent/{id}", dh.UpdateSgeConsent) + r.Delete("/consent/{id}", dh.DeleteSgeConsentById) + }) + + r.Route("/api/grdf", func(r chi.Router) { + r.Use(auth.BOAuthMiddleware) + r.Post("/consent", dh.PostGrdfConsent) + r.Get("/consent/{id}", dh.GetGrdfConsentById) + r.Delete("/consent/{id}", dh.DeleteGrdfConsentById) }) r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { /** handles Oauth2 redirection */ }) diff --git a/internal/rootmux/rootmux_test.go b/internal/rootmux/rootmux_test.go index 73d1df7a6efa3e98849bfacc7a5093a091b85767..f5de0866c37b003aec423fc178a2c825b30f7ac1 100644 --- a/internal/rootmux/rootmux_test.go +++ b/internal/rootmux/rootmux_test.go @@ -27,24 +27,28 @@ const ( ) var ( - oAuth2Server *httptest.Server - mailSubject = models.MailSubject{Year: 2021, Month: 1, Subject: "[Ecolyo] Newsletter"} - mailSubjectStr string - monthlyInfo = models.MonthlyInfo{Year: 2021, Month: 1, Info: "Informations du mois", Image: "imagebase64"} - monthlyInfoStr string - monthlyNews = models.MonthlyNews{Year: 2021, Month: 1, Title: "", Content: "Nouvelles fonctionnalités"} - monthlyNewsStr string - newPoll = models.Poll{Year: 2021, Month: 1, Question: "pollQuestion", Link: "pollLink"} - newPollStr string - partnersInfo = models.PartnersInfo{ID: 1, GRDFFailure: false, EnedisFailure: false, EGLFailure: true, NotificationActivated: true} - partnersInfoStr string - customPopupInfo = models.CustomPopup{ID: 1, PopupEnabled: false, Title: "Alerte personnalisée", Description: "Ecolyo 4ever"} - customPopupStr string - consent = models.Consent{Firstname: "Foo", Lastname: "Bar", PointID: "12345671234567"} - consentStr string - otherConsent = models.Consent{Firstname: "John", Lastname: "Doe", PointID: "01234560123456"} - otherConsentStr string - noH map[string]string + oAuth2Server *httptest.Server + mailSubject = models.MailSubject{Year: 2021, Month: 1, Subject: "[Ecolyo] Newsletter"} + mailSubjectStr string + monthlyInfo = models.MonthlyInfo{Year: 2021, Month: 1, Info: "Informations du mois", Image: "imagebase64"} + monthlyInfoStr string + monthlyNews = models.MonthlyNews{Year: 2021, Month: 1, Title: "", Content: "Nouvelles fonctionnalités"} + monthlyNewsStr string + newPoll = models.Poll{Year: 2021, Month: 1, Question: "pollQuestion", Link: "pollLink"} + newPollStr string + partnersInfo = models.PartnersInfo{ID: 1, GRDFFailure: false, EnedisFailure: false, EGLFailure: true, NotificationActivated: true} + partnersInfoStr string + customPopupInfo = models.CustomPopup{ID: 1, PopupEnabled: false, Title: "Alerte personnalisée", Description: "Ecolyo 4ever"} + customPopupStr string + consent = models.SgeConsent{Firstname: "Foo", Lastname: "Bar", PointID: "12345671234567"} + consentStr string + otherConsent = models.SgeConsent{Firstname: "John", Lastname: "Doe", PointID: "01234560123456"} + otherConsentStr string + grdfConsent = models.GrdfConsent{Firstname: "Foo", Lastname: "Bar", Pce: "12345671234567"} + grdfConsentStr string + otherGrdfConsent = models.GrdfConsent{Firstname: "John", Lastname: "Doe", Pce: "01234560123456"} + otherGrdfConsentStr string + noH map[string]string ) func TestMain(m *testing.M) { @@ -85,6 +89,10 @@ func TestMain(m *testing.M) { consentStr = string(consentBytes) otherConsentBytes, _ := json.Marshal(otherConsent) otherConsentStr = string(otherConsentBytes) + grdfConsentBytes, _ := json.Marshal(grdfConsent) + grdfConsentStr = string(grdfConsentBytes) + otherGrdfConsentBytes, _ := json.Marshal(otherGrdfConsent) + otherGrdfConsentStr = string(otherGrdfConsentBytes) code := m.Run() // Remove the database @@ -98,6 +106,8 @@ func TestAll(t *testing.T) { // SGE API tests sgeTests(t) + // GRDF API tests + grdfTests(t) // Set up testers os.Setenv("AUTH_URL", oAuth2Server.URL+"/auth-wrong-state") // Set the server to access failing OAuth2 endpoints @@ -266,11 +276,15 @@ func adminTests(t *testing.T) { xsrfHeader := map[string]string{"XSRF-TOKEN": token.XSRFToken} // Try to get SGE consents (must pass) - do("GET", "/api/admin/consent?limit=50&page=0", xsrfHeader, "", http.StatusOK, `{"totalRows":2,"rows":[{"ID":"9566c74d-1003-4c4d-bbbb-0407d1e2c649"`) + do("GET", "/api/admin/sge/consent?limit=50&page=0", xsrfHeader, "", http.StatusOK, `{"totalRows":2,"rows":[{"ID":"9566c74d-1003-4c4d-bbbb-0407d1e2c649"`) + // Try to get GRDF consents (must pass) + do("GET", "/api/admin/grdf/consent?limit=50&page=0", xsrfHeader, "", http.StatusOK, `{"totalRows":2,"rows":[{"ID":"6694d2c4-22ac-4208-a007-2939487f6999"`) // Try to logout (must pass) do("GET", "/Logout", noH, "", http.StatusOK, "") // Try to get SGE consents again (must fail) - do("GET", "/api/admin/consent?limit=50&page=0", xsrfHeader, "", http.StatusUnauthorized, ErrorExtractingToken) + do("GET", "/api/admin/sge/consent?limit=50&page=0", xsrfHeader, "", http.StatusUnauthorized, ErrorExtractingToken) + // Try to get GRDF consents again (must fail) + do("GET", "/api/admin/grdf/consent?limit=50&page=0", xsrfHeader, "", http.StatusUnauthorized, ErrorExtractingToken) } func sgeTests(t *testing.T) { @@ -287,19 +301,44 @@ func sgeTests(t *testing.T) { do("DELETE", "/api/sge/consent/1", noH, "", http.StatusUnauthorized, ErrorInvalidToken) // Create correct authorization header - sgeApiHeader := map[string]string{"Authorization": "Bearer " + auth.SGEApiToken} + boApiHeader := map[string]string{"Authorization": "Bearer " + auth.SGEApiToken} // Try to create a consent (must pass) - do("POST", "/api/sge/consent", sgeApiHeader, consentStr, http.StatusCreated, `{"ID":"52fdfc07-2182-454f-963f-5f0f9a621d72"`) + do("POST", "/api/sge/consent", boApiHeader, consentStr, http.StatusCreated, `{"ID":"52fdfc07-2182-454f-963f-5f0f9a621d72"`) // Try to create another consent (must pass) - do("POST", "/api/sge/consent", sgeApiHeader, otherConsentStr, http.StatusCreated, `{"ID":"9566c74d-1003-4c4d-bbbb-0407d1e2c649"`) + do("POST", "/api/sge/consent", boApiHeader, otherConsentStr, http.StatusCreated, `{"ID":"9566c74d-1003-4c4d-bbbb-0407d1e2c649"`) // Try to update a consent (must pass) - do("PUT", "/api/sge/consent/52fdfc07-2182-454f-963f-5f0f9a621d72", sgeApiHeader, `{"serviceId":123456}`, http.StatusOK, `{"ID":"52fdfc07-2182-454f-963f-5f0f9a621d72"`) + do("PUT", "/api/sge/consent/52fdfc07-2182-454f-963f-5f0f9a621d72", boApiHeader, `{"serviceId":123456}`, http.StatusOK, `{"ID":"52fdfc07-2182-454f-963f-5f0f9a621d72"`) // Try to get a consent (must pass) - do("GET", "/api/sge/consent/52fdfc07-2182-454f-963f-5f0f9a621d72", sgeApiHeader, "", http.StatusOK, `{"ID":"52fdfc07-2182-454f-963f-5f0f9a621d72"`) + do("GET", "/api/sge/consent/52fdfc07-2182-454f-963f-5f0f9a621d72", boApiHeader, "", http.StatusOK, `{"ID":"52fdfc07-2182-454f-963f-5f0f9a621d72"`) // Try to get a consent that doesn't exist (must fail not found) - do("GET", "/api/sge/consent/3", sgeApiHeader, "", http.StatusNotFound, `consent not found`) + do("GET", "/api/sge/consent/3", boApiHeader, "", http.StatusNotFound, `consent not found`) // Try to delete a consent (must pass) - do("DELETE", "/api/sge/consent/52fdfc07-2182-454f-963f-5f0f9a621d72", sgeApiHeader, "", http.StatusOK, "") + do("DELETE", "/api/sge/consent/52fdfc07-2182-454f-963f-5f0f9a621d72", boApiHeader, "", http.StatusOK, "") +} + +func grdfTests(t *testing.T) { + // Create the tester + ts, do, _ := createTester(t) + defer ts.Close() // Close the tester + // Try to create a consent (must fail) + do("POST", "/api/grdf/consent", noH, grdfConsentStr, http.StatusUnauthorized, ErrorInvalidToken) + // Try to get a consent (must fail) + do("GET", "/api/grdf/consent/1", noH, "", http.StatusUnauthorized, ErrorInvalidToken) + // Try to delete a consent (must fail) + do("DELETE", "/api/grdf/consent/1", noH, "", http.StatusUnauthorized, ErrorInvalidToken) + + // Create correct authorization header + boApiHeader := map[string]string{"Authorization": "Bearer " + auth.SGEApiToken} + // Try to create a consent (must pass) + do("POST", "/api/grdf/consent", boApiHeader, grdfConsentStr, http.StatusCreated, `{"ID":"81855ad8-681d-4d86-91e9-1e00167939cb"`) + // Try to create another consent (must pass) + do("POST", "/api/grdf/consent", boApiHeader, otherGrdfConsentStr, http.StatusCreated, `{"ID":"6694d2c4-22ac-4208-a007-2939487f6999"`) + // Try to get a consent (must pass) + do("GET", "/api/grdf/consent/81855ad8-681d-4d86-91e9-1e00167939cb", boApiHeader, "", http.StatusOK, `{"ID":"81855ad8-681d-4d86-91e9-1e00167939cb"`) + // Try to get a consent that doesn't exist (must fail not found) + do("GET", "/api/grdf/consent/3", boApiHeader, "", http.StatusNotFound, `consent not found`) + // Try to delete a consent (must pass) + do("DELETE", "/api/grdf/consent/81855ad8-681d-4d86-91e9-1e00167939cb", boApiHeader, "", http.StatusOK, "") } func createTester(t *testing.T) (*httptest.Server, tester.DoFn, tester.DoFn) {