From 2d878d05f38766544e71c0aea3b485754833416e Mon Sep 17 00:00:00 2001 From: Torgrim <sir_alexiner@hotmail.com> Date: Sat, 20 Apr 2024 17:49:59 +0200 Subject: [PATCH] Project Updated and streamlined for final code documentation. Code updated slightly to increase coverage. --- Go/.env.example | 3 +- Go/Dockerfile | 2 + Go/Dockerfile-test | 2 + Go/auth/auth.go | 18 +- Go/cmd/globeboard/app.go | 7 + Go/cmd/globeboard/app_test.go | 525 +++++++++++------- Go/db/db.go | 262 +-------- Go/docker-compose.yml | 2 + Go/internal/func/dashboardFunctions.go | 21 +- Go/internal/func/supported_countries.go | 7 +- Go/internal/func/webhook_payload.go | 39 +- .../dashboard/dashboards_id_handler.go | 8 +- .../dashboard/notifications_handler.go | 11 +- .../dashboard/notifications_id_handler.go | 14 +- .../dashboard/registrations_handler.go | 13 - .../dashboard/registrations_id_handler.go | 23 +- .../endpoint/dashboard/status_handler.go | 30 +- .../handlers/endpoint/util/apikey_handler.go | 21 +- .../endpoint/util/user_delete_handler.go | 12 +- .../endpoint/util/user_register_handler.go | 11 +- .../utils/constants/External/external.go | 2 +- Go/internal/utils/constants/Paths/paths.go | 2 +- Go/internal/utils/constants/constants.go | 1 - Go/internal/utils/structs/structs.go | 1 - README.md | 4 +- 25 files changed, 411 insertions(+), 630 deletions(-) diff --git a/Go/.env.example b/Go/.env.example index c7a5360..9172e5b 100644 --- a/Go/.env.example +++ b/Go/.env.example @@ -1,2 +1,3 @@ PORT=8080 -FIREBASE_CREDENTIALS_FILE=path_to_Firebase_credentials_file \ No newline at end of file +FIREBASE_CREDENTIALS_FILE=./super_secret_folder/database_file.json +FIRESTORE_PROJECT_ID=firestore_project_1 \ No newline at end of file diff --git a/Go/Dockerfile b/Go/Dockerfile index c7b2417..951b631 100644 --- a/Go/Dockerfile +++ b/Go/Dockerfile @@ -1,6 +1,7 @@ # syntax=docker/dockerfile:1.2 FROM golang:1.22 AS builder +# Define Authors LABEL authors="Torgrim Thorsen" # Set destination for COPY @@ -21,6 +22,7 @@ FROM alpine:3.19 # Install CA certificates. RUN apk --no-cache add ca-certificates +# Set new Working Directory. WORKDIR /root/ # Copy the pre-built binary file from the previous stage. diff --git a/Go/Dockerfile-test b/Go/Dockerfile-test index aeed904..63bff94 100644 --- a/Go/Dockerfile-test +++ b/Go/Dockerfile-test @@ -1,6 +1,7 @@ # syntax=docker/dockerfile:1.2 FROM golang:1.22 AS builder +# Define Authors LABEL authors="Torgrim Thorsen" # Set destination for COPY @@ -24,6 +25,7 @@ RUN apk --no-cache add ca-certificates # Install Report Tool. RUN go install github.com/jstemmer/go-junit-report/v2@latest +# Set new Working Directory. WORKDIR /root/ # Copy the pre-built binary file from the previous stage. diff --git a/Go/auth/auth.go b/Go/auth/auth.go index 2ba8ef4..1d505e1 100644 --- a/Go/auth/auth.go +++ b/Go/auth/auth.go @@ -5,28 +5,24 @@ import ( firebase "firebase.google.com/go" "firebase.google.com/go/auth" "google.golang.org/api/option" + "log" "os" ) var ( - // Use a context for Firebase operations - ctx = context.Background() + ctx = context.Background() + Client *auth.Client ) -func GetFireBaseAuthClient() (*auth.Client, error) { - // Using the credential file +func init() { sa := option.WithCredentialsFile(os.Getenv("FIREBASE_CREDENTIALS_FILE")) app, err := firebase.NewApp(ctx, nil, sa) if err != nil { - return nil, err + log.Panic("Firebase Failed to initialize: ", err) } - //No initial error, so a client is used to gather other information - client, err := app.Auth(ctx) + Client, err = app.Auth(ctx) if err != nil { - return nil, err + log.Panic("Firebase Failed to initialize Authentication client: ", err) } - - // No errors, so we return the test client and no error - return client, nil } diff --git a/Go/cmd/globeboard/app.go b/Go/cmd/globeboard/app.go index d44c928..5140bbf 100644 --- a/Go/cmd/globeboard/app.go +++ b/Go/cmd/globeboard/app.go @@ -1,6 +1,7 @@ package main import ( + "globeboard/db" "globeboard/internal/handlers" "globeboard/internal/handlers/endpoint/dashboard" "globeboard/internal/handlers/endpoint/util" @@ -22,9 +23,15 @@ func fileExists(filename string) bool { } func main() { + // confirm that the Firebase Credentials file is accessible, if not panic. if !fileExists(os.Getenv("FIREBASE_CREDENTIALS_FILE")) { log.Panic("Firebase Credentials file is not mounted") } + defer func() { + if err := db.Client.Close(); err != nil { + log.Printf("Error closing Firestore client: %v", err) + } + }() // Get the port from the environment variable or set default to 8080 port := os.Getenv("PORT") diff --git a/Go/cmd/globeboard/app_test.go b/Go/cmd/globeboard/app_test.go index 500ea5a..527daf7 100644 --- a/Go/cmd/globeboard/app_test.go +++ b/Go/cmd/globeboard/app_test.go @@ -65,17 +65,15 @@ func init() { // TestRoot confirms that Root Endpoint returns 303 See Other for All Requests. func TestRoot(t *testing.T) { - // Create a request to your endpoint with the GET method + rr := httptest.NewRecorder() + req, err := http.NewRequest(http.MethodGet, Paths.Root, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response - rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusSeeOther { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusSeeOther) @@ -86,10 +84,8 @@ func TestRoot(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusSeeOther { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusSeeOther) @@ -100,10 +96,8 @@ func TestRoot(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusSeeOther { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusSeeOther) @@ -114,10 +108,8 @@ func TestRoot(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusSeeOther { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusSeeOther) @@ -128,10 +120,8 @@ func TestRoot(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusSeeOther { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusSeeOther) @@ -155,12 +145,10 @@ func TestRegisterHandlerRegister(t *testing.T) { rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code is what we expect. if status := rr.Code; status != http.StatusCreated { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusCreated) } - // Decode the JSON response var response struct { Token string `json:"token"` UserID string `json:"userid"` @@ -204,7 +192,6 @@ func TestGetAPIKeyHandler(t *testing.T) { t.Errorf("GET handler returned wrong status code: got %v want %v", status, http.StatusCreated) } - // Optionally decode the response to check if the correct API key is retrieved var response struct { APIKey string `json:"token"` } @@ -216,17 +203,14 @@ func TestGetAPIKeyHandler(t *testing.T) { } func TestStatusGet(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Status+"?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) @@ -323,7 +307,7 @@ func TestNotificationsHandlerGet(t *testing.T) { func TestRegistrationsHandlerPost(t *testing.T) { registrationData := []byte(`{ - "country": "united states", + "isocode": "us", "features": { "temperature": true, "coordinates": true @@ -357,7 +341,7 @@ func TestRegistrationsHandlerPost(t *testing.T) { func TestRegistrationsHandlerPostMinimal(t *testing.T) { registrationData := []byte(`{ - "isoCode": "no", + "country": "norway", "features": { "temperature": true } @@ -509,17 +493,14 @@ func TestDeleteAPIKeyHandlerWrongToken(t *testing.T) { } func TestStatusGetWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Status+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -527,17 +508,14 @@ func TestStatusGetWrongToken(t *testing.T) { } func TestRegistrationsPostWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodPost, Endpoints.Registrations+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -545,17 +523,14 @@ func TestRegistrationsPostWrongToken(t *testing.T) { } func TestRegistrationsGetWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Registrations+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -563,17 +538,14 @@ func TestRegistrationsGetWrongToken(t *testing.T) { } func TestRegistrationsGetIdWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Registrations+"/"+docId1+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -581,17 +553,14 @@ func TestRegistrationsGetIdWrongToken(t *testing.T) { } func TestRegistrationsPatchIdWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodPatch, Endpoints.Registrations+"/"+docId1+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -599,17 +568,14 @@ func TestRegistrationsPatchIdWrongToken(t *testing.T) { } func TestRegistrationsDeleteIdWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodDelete, Endpoints.Registrations+"/"+docId1+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -617,17 +583,14 @@ func TestRegistrationsDeleteIdWrongToken(t *testing.T) { } func TestDashboardGetIdWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Dashboards+"/"+docId1+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -635,17 +598,14 @@ func TestDashboardGetIdWrongToken(t *testing.T) { } func TestNotificationsPostWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodPost, Endpoints.Notifications+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -653,17 +613,14 @@ func TestNotificationsPostWrongToken(t *testing.T) { } func TestNotificationsGetWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Notifications+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -671,17 +628,14 @@ func TestNotificationsGetWrongToken(t *testing.T) { } func TestNotificationsGetIdWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Notifications+"/"+webhookId1+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -689,17 +643,14 @@ func TestNotificationsGetIdWrongToken(t *testing.T) { } func TestNotificationsDeleteIdWrongToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodDelete, Endpoints.Notifications+"/"+webhookId1+"?token="+wrongToken, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotAcceptable { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotAcceptable) @@ -725,17 +676,14 @@ func TestDeleteAPIKeyHandlerNoToken(t *testing.T) { } func TestStatusGetNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Status, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -743,17 +691,14 @@ func TestStatusGetNoToken(t *testing.T) { } func TestRegistrationsPostNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodPost, Endpoints.Registrations, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -761,17 +706,14 @@ func TestRegistrationsPostNoToken(t *testing.T) { } func TestRegistrationsGetNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Registrations, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -779,17 +721,14 @@ func TestRegistrationsGetNoToken(t *testing.T) { } func TestRegistrationsGetIdNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Registrations+"/"+docId1, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -797,17 +736,14 @@ func TestRegistrationsGetIdNoToken(t *testing.T) { } func TestRegistrationsPatchIdNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodPatch, Endpoints.Registrations+"/"+docId1, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -815,17 +751,14 @@ func TestRegistrationsPatchIdNoToken(t *testing.T) { } func TestRegistrationsDeleteIdNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodDelete, Endpoints.Registrations+"/"+docId1, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -833,17 +766,14 @@ func TestRegistrationsDeleteIdNoToken(t *testing.T) { } func TestDashboardGetIdNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Dashboards+"/"+docId1, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -851,17 +781,14 @@ func TestDashboardGetIdNoToken(t *testing.T) { } func TestNotificationsPostNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodPost, Endpoints.Notifications, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -869,17 +796,14 @@ func TestNotificationsPostNoToken(t *testing.T) { } func TestNotificationsGetNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Notifications, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -887,17 +811,14 @@ func TestNotificationsGetNoToken(t *testing.T) { } func TestNotificationsGetIdNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Notifications+"/"+webhookId1, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -905,17 +826,14 @@ func TestNotificationsGetIdNoToken(t *testing.T) { } func TestNotificationsDeleteIdNoToken(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodDelete, Endpoints.Notifications+"/"+webhookId1, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) @@ -925,17 +843,14 @@ func TestNotificationsDeleteIdNoToken(t *testing.T) { /* Empty ID */ func TestRegistrationsGetEmptyId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Registrations+"/?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) @@ -943,17 +858,14 @@ func TestRegistrationsGetEmptyId(t *testing.T) { } func TestRegistrationsPatchEmptyId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodPatch, Endpoints.Registrations+"/?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) @@ -961,17 +873,14 @@ func TestRegistrationsPatchEmptyId(t *testing.T) { } func TestRegistrationsDeleteEmptyId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodDelete, Endpoints.Registrations+"/?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) @@ -979,17 +888,14 @@ func TestRegistrationsDeleteEmptyId(t *testing.T) { } func TestDashboardGetEmptyId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Dashboards+"/?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) @@ -997,17 +903,14 @@ func TestDashboardGetEmptyId(t *testing.T) { } func TestNotificationsGetEmptyId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Notifications+"/?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) @@ -1015,37 +918,123 @@ func TestNotificationsGetEmptyId(t *testing.T) { } func TestNotificationsDeleteEmptyId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodDelete, Endpoints.Notifications+"/?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) } } +/* Whitespace ID */ + +func TestRegistrationsGetWhitespaceId(t *testing.T) { + req, err := http.NewRequest(http.MethodGet, Endpoints.Registrations+"/%20?token="+token, nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusBadRequest) + } +} + +func TestRegistrationsPatchWhitespaceId(t *testing.T) { + req, err := http.NewRequest(http.MethodPatch, Endpoints.Registrations+"/%20?token="+token, nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusBadRequest) + } +} + +func TestRegistrationsDeleteWhitespaceId(t *testing.T) { + req, err := http.NewRequest(http.MethodDelete, Endpoints.Registrations+"/%20?token="+token, nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusBadRequest) + } +} + +func TestDashboardGetWhitespaceId(t *testing.T) { + req, err := http.NewRequest(http.MethodGet, Endpoints.Dashboards+"/%20?token="+token, nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusBadRequest) + } +} + +func TestNotificationsGetWhitespaceId(t *testing.T) { + req, err := http.NewRequest(http.MethodGet, Endpoints.Notifications+"/%20?token="+token, nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusBadRequest) + } +} + +func TestNotificationsDeleteWhitespaceId(t *testing.T) { + req, err := http.NewRequest(http.MethodDelete, Endpoints.Notifications+"/%20?token="+token, nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusBadRequest) + } +} + /* Wrong ID */ func TestRegistrationsGetWrongId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Registrations+"/aaaaaaaaaaaaaaaaa?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) @@ -1063,11 +1052,9 @@ func TestRegistrationsPatchWrongId(t *testing.T) { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) @@ -1075,17 +1062,14 @@ func TestRegistrationsPatchWrongId(t *testing.T) { } func TestRegistrationsDeleteWrongId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodDelete, Endpoints.Registrations+"/aaaaaaaaaaaaaaaaa?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) @@ -1093,17 +1077,14 @@ func TestRegistrationsDeleteWrongId(t *testing.T) { } func TestDashboardGetWrongId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Dashboards+"/aaaaaaaaaaaaaaaaa?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) @@ -1111,17 +1092,14 @@ func TestDashboardGetWrongId(t *testing.T) { } func TestNotificationsGetWrongId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodGet, Endpoints.Notifications+"/aaaaaaaaaaaaaaaaa?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) @@ -1129,17 +1107,14 @@ func TestNotificationsGetWrongId(t *testing.T) { } func TestNotificationsDeleteWrongId(t *testing.T) { - // Create a request to your endpoint with the GET method req, err := http.NewRequest(http.MethodDelete, Endpoints.Notifications+"/aaaaaaaaaaaaaaaaa?token="+token, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusInternalServerError { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusInternalServerError) @@ -1163,7 +1138,6 @@ func TestRegisterHandlerRegisterBadEmail(t *testing.T) { rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code is what we expect. if status := rr.Code; status != http.StatusBadRequest { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) } @@ -1184,7 +1158,65 @@ func TestRegisterHandlerRegisterBadPassword(t *testing.T) { rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code is what we expect. + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + } +} + +func TestRegisterHandlerRegisterBadLongPassword(t *testing.T) { + form := url.Values{} + form.Add("username", DisplayName) + form.Add("email", Email) + form.Add("password", "passwordpassword") + + req, err := http.NewRequest(http.MethodPost, Endpoints.UserRegistration, strings.NewReader(form.Encode())) + if err != nil { + t.Fatal(err) + } + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + } +} +func TestRegisterHandlerRegisterBadLongPasswordUppercase(t *testing.T) { + form := url.Values{} + form.Add("username", DisplayName) + form.Add("email", Email) + form.Add("password", "PasswordPassword") + + req, err := http.NewRequest(http.MethodPost, Endpoints.UserRegistration, strings.NewReader(form.Encode())) + if err != nil { + t.Fatal(err) + } + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + } +} + +func TestRegisterHandlerRegisterBadLongPasswordUppercaseNumber(t *testing.T) { + form := url.Values{} + form.Add("username", DisplayName) + form.Add("email", Email) + form.Add("password", "Passwordp455w0rd") + + req, err := http.NewRequest(http.MethodPost, Endpoints.UserRegistration, strings.NewReader(form.Encode())) + if err != nil { + t.Fatal(err) + } + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusBadRequest { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) } @@ -1233,7 +1265,6 @@ func TestRegisterHandlerEmptyRegister(t *testing.T) { rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code is what we expect. if status := rr.Code; status != http.StatusBadRequest { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) } @@ -1284,7 +1315,159 @@ func TestRegistrationsIdHandlerEmptyPatch(t *testing.T) { } } -/* Delete User No UUID & Wrong UUID */ +/* Wrong POST/PATCH BODY */ + +func TestRegistrationsIdHandlerPostNoFeatures(t *testing.T) { + patchData := []byte(`{ + "country": "Sweden", + "features": { + "temperature": false, + "precipitation": false, + "capital": false, + "coordinates": false, + "population": false, + "area": false, + "targetCurrencies": [] + } + }`) + + req, err := http.NewRequest(http.MethodPost, Endpoints.Registrations+"?token="+token, bytes.NewBuffer(patchData)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + t.Log(rr.Body.String()) + } +} + +func TestRegistrationsIdHandlerPatchCountry(t *testing.T) { + patchData := []byte(`{ + "country": "Sweden", + "features": { + "temperature": true, + "precipitation": true, + "capital": true, + "coordinates": true, + "population": true, + "area": true, + "targetCurrencies": ["jpy", "nok", "eur","gbp"] + } + }`) + + req, err := http.NewRequest(http.MethodPatch, Endpoints.Registrations+"/"+docId1+"?token="+token, bytes.NewBuffer(patchData)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + t.Log(rr.Body.String()) + } +} + +func TestRegistrationsIdHandlerPatchIsocode(t *testing.T) { + patchData := []byte(`{ + "isocode": "gb", + "features": { + "temperature": true, + "precipitation": true, + "capital": true, + "coordinates": true, + "population": true, + "area": true, + "targetCurrencies": ["jpy", "nok", "eur","gbp"] + } + }`) + + req, err := http.NewRequest(http.MethodPatch, Endpoints.Registrations+"/"+docId1+"?token="+token, bytes.NewBuffer(patchData)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + } +} + +func TestRegistrationsIdHandlerPatchNoFeatures(t *testing.T) { + patchData := []byte(`{ + }`) + + req, err := http.NewRequest(http.MethodPatch, Endpoints.Registrations+"/"+docId1+"?token="+token, bytes.NewBuffer(patchData)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + } +} + +func TestRegistrationsIdHandlerPatchEmptyFeatures(t *testing.T) { + patchData := []byte(`{ + "features": {} + }`) + + req, err := http.NewRequest(http.MethodPatch, Endpoints.Registrations+"/"+docId1+"?token="+token, bytes.NewBuffer(patchData)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + } +} + +func TestRegistrationsIdHandlerAllFalse(t *testing.T) { + patchData := []byte(`{ + "features": { + "temperature": false, + "precipitation": false, + "capital": false, + "coordinates": false, + "population": false, + "area": false, + "targetCurrencies": [] + } + }`) + + req, err := http.NewRequest(http.MethodPatch, Endpoints.Registrations+"/"+docId1+"?token="+token, bytes.NewBuffer(patchData)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + } +} + +/* Delete User No UUID, Whitespace UUID & Wrong UUID */ func TestRegisterHandlerDeleteNoUUID(t *testing.T) { req, err := http.NewRequest(http.MethodDelete, Endpoints.UserDeletion+"/", nil) @@ -1295,12 +1478,25 @@ func TestRegisterHandlerDeleteNoUUID(t *testing.T) { rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code is what we expect. if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) } } +func TestRegisterHandlerDeleteWhitespaceUUID(t *testing.T) { + req, err := http.NewRequest(http.MethodDelete, Endpoints.UserDeletion+"/%20", nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + } +} + func TestRegisterHandlerDeleteWrongUUID(t *testing.T) { req, err := http.NewRequest(http.MethodDelete, Endpoints.UserDeletion+"/NTNU2024", nil) if err != nil { @@ -1310,7 +1506,6 @@ func TestRegisterHandlerDeleteWrongUUID(t *testing.T) { rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code is what we expect. if status := rr.Code; status != http.StatusInternalServerError { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusInternalServerError) } @@ -1319,17 +1514,15 @@ func TestRegisterHandlerDeleteWrongUUID(t *testing.T) { /* Endpoint "Not Implemented" Methods Check */ func TestUserRegister(t *testing.T) { - // Create a request to your endpoint with the GET method + rr := httptest.NewRecorder() + req, err := http.NewRequest(http.MethodGet, Endpoints.UserRegistration, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response - rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1340,10 +1533,8 @@ func TestUserRegister(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1354,10 +1545,8 @@ func TestUserRegister(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1368,10 +1557,8 @@ func TestUserRegister(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1379,17 +1566,15 @@ func TestUserRegister(t *testing.T) { } func TestUserDeletion(t *testing.T) { - // Create a request to your endpoint with the GET method + rr := httptest.NewRecorder() + req, err := http.NewRequest(http.MethodGet, Endpoints.UserDeletion+"/"+UUID, nil) if err != nil { t.Fatal(err) } - // Create a ResponseRecorder to record the response - rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1400,10 +1585,8 @@ func TestUserDeletion(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1414,10 +1597,8 @@ func TestUserDeletion(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1428,10 +1609,8 @@ func TestUserDeletion(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1439,7 +1618,6 @@ func TestUserDeletion(t *testing.T) { } func TestAPIKeyHandler(t *testing.T) { - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() req, err := http.NewRequest(http.MethodPut, Endpoints.ApiKey, nil) @@ -1447,10 +1625,8 @@ func TestAPIKeyHandler(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1461,10 +1637,8 @@ func TestAPIKeyHandler(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1475,10 +1649,8 @@ func TestAPIKeyHandler(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1486,7 +1658,6 @@ func TestAPIKeyHandler(t *testing.T) { } func TestStatus(t *testing.T) { - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() req, err := http.NewRequest(http.MethodPut, Endpoints.Status, nil) @@ -1494,10 +1665,8 @@ func TestStatus(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1508,10 +1677,8 @@ func TestStatus(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1522,10 +1689,8 @@ func TestStatus(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1536,10 +1701,8 @@ func TestStatus(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1547,7 +1710,6 @@ func TestStatus(t *testing.T) { } func TestRegistrations(t *testing.T) { - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() req, err := http.NewRequest(http.MethodPut, Endpoints.Registrations, nil) @@ -1555,10 +1717,8 @@ func TestRegistrations(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1569,10 +1729,8 @@ func TestRegistrations(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1583,10 +1741,8 @@ func TestRegistrations(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1594,7 +1750,6 @@ func TestRegistrations(t *testing.T) { } func TestRegistrationsId(t *testing.T) { - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() req, err := http.NewRequest(http.MethodPut, Endpoints.Registrations+"/"+docId1, nil) @@ -1602,10 +1757,8 @@ func TestRegistrationsId(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1616,10 +1769,8 @@ func TestRegistrationsId(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1627,7 +1778,6 @@ func TestRegistrationsId(t *testing.T) { } func TestDashboardId(t *testing.T) { - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() req, err := http.NewRequest(http.MethodPut, Endpoints.Dashboards+"/"+docId1, nil) @@ -1635,10 +1785,8 @@ func TestDashboardId(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1649,10 +1797,8 @@ func TestDashboardId(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1663,10 +1809,8 @@ func TestDashboardId(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1677,10 +1821,8 @@ func TestDashboardId(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1688,7 +1830,6 @@ func TestDashboardId(t *testing.T) { } func TestNotifications(t *testing.T) { - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() req, err := http.NewRequest(http.MethodPut, Endpoints.Notifications, nil) @@ -1696,10 +1837,8 @@ func TestNotifications(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1710,10 +1849,8 @@ func TestNotifications(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1724,10 +1861,8 @@ func TestNotifications(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1735,7 +1870,6 @@ func TestNotifications(t *testing.T) { } func TestNotificationsId(t *testing.T) { - // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() req, err := http.NewRequest(http.MethodPut, Endpoints.Notifications+"/"+docId1, nil) @@ -1743,10 +1877,8 @@ func TestNotificationsId(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1757,10 +1889,8 @@ func TestNotificationsId(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1771,10 +1901,8 @@ func TestNotificationsId(t *testing.T) { t.Fatal(err) } - // Serve the request to the handler mux.ServeHTTP(rr, req) - // Check the status code if status := rr.Code; status != http.StatusNotImplemented { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotImplemented) @@ -1850,7 +1978,6 @@ func TestRegisterHandlerDelete(t *testing.T) { rr := httptest.NewRecorder() mux.ServeHTTP(rr, req) - // Check the status code is what we expect. if status := rr.Code; status != http.StatusNoContent { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNoContent) } diff --git a/Go/db/db.go b/Go/db/db.go index 4cf3dfa..b0b5741 100644 --- a/Go/db/db.go +++ b/Go/db/db.go @@ -4,7 +4,6 @@ import ( "cloud.google.com/go/firestore" "context" "errors" - firebase "firebase.google.com/go" "fmt" authenticate "globeboard/auth" "globeboard/internal/utils/constants/Firestore" @@ -26,48 +25,24 @@ const ( var ( // Use a context for Firestore operations - ctx = context.Background() + ctx = context.Background() + Client *firestore.Client + err error ) -func getFirestoreClient() (*firestore.Client, error) { - - // Using the credential file +func init() { sa := option.WithCredentialsFile(os.Getenv("FIREBASE_CREDENTIALS_FILE")) - app, err := firebase.NewApp(ctx, nil, sa) - if err != nil { - log.Println("Credentials not found: " + os.Getenv("FIREBASE_CREDENTIALS_FILE")) - log.Println("Error on getting the application") - return nil, err - } - - //No initial error, so a client is used to gather other information - client, err := app.Firestore(ctx) + Client, err = firestore.NewClient(ctx, os.Getenv("FIRESTORE_PROJECT_ID"), sa) if err != nil { - // Logging the error - log.Print("Firestore reported an error: ", err) - return nil, err + log.Panic("Firestore was unable to initialize: ", err) } - - // No errors, so we return the test client and no error - return client, nil } func TestDBConnection() string { - client, err := getFirestoreClient() - if err != nil { - return fmt.Sprintf("%d %s: %v", http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError), err) - } - defer func() { - if err := client.Close(); err != nil { - log.Printf("Error closing Firestore client: %v", err) - } - }() - collectionID := "Connectivity" documentID := "DB_Connection_Test" - // Attempt to update a specific document to test connectivity and permissions. - _, err = client.Collection(collectionID).Doc(documentID).Set(ctx, map[string]interface{}{ + _, err = Client.Collection(collectionID).Doc(documentID).Set(ctx, map[string]interface{}{ "PSA": "DO NOT DELETE THIS DOCUMENT!", "lastChecked": firestore.ServerTimestamp, }, firestore.MergeAll) @@ -103,33 +78,19 @@ func TestDBConnection() string { } func AddApiKey(docID, UUID string, key string) error { - client, err := getFirestoreClient() - if err != nil { - return err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Create a reference to the Firestore collection - ref := client.Collection(Firestore.ApiKeyCollection) + ref := Client.Collection(Firestore.ApiKeyCollection) iter := ref.Where("UUID", "==", UUID).Limit(1).Documents(ctx) defer iter.Stop() for { - doc, err := iter.Next() + _, err := iter.Next() if errors.Is(err, iterator.Done) { break } if err != nil { return fmt.Errorf(IterationFailed, err) } - _ = doc err = errors.New("API key is already registered to user") return err } @@ -139,7 +100,6 @@ func AddApiKey(docID, UUID string, key string) error { APIKey: key, } - // Create a new document and add it to the firebase _, err = ref.Doc(docID).Set(ctx, apiKeys) if err != nil { err := fmt.Errorf("error saving API key to Database: %v", err) @@ -150,20 +110,7 @@ func AddApiKey(docID, UUID string, key string) error { } func DeleteApiKey(UUID, apiKey string) error { - client, err := getFirestoreClient() - if err != nil { - return err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Create a reference to the Firestore collection - ref := client.Collection(Firestore.ApiKeyCollection) + ref := Client.Collection(Firestore.ApiKeyCollection) iter := ref.Where("UUID", "==", UUID).Where("APIKey", "==", apiKey).Limit(1).Documents(ctx) defer iter.Stop() @@ -180,12 +127,10 @@ func DeleteApiKey(UUID, apiKey string) error { docID = doc.Ref.ID } - // If docID is empty, the API key does not exist in Firestore if docID == "" { return errors.New("API key not found") } - // Delete the document with the provided API key _, err = ref.Doc(docID).Delete(ctx) if err != nil { return fmt.Errorf("failed to delete API Key: %v", err) @@ -195,29 +140,13 @@ func DeleteApiKey(UUID, apiKey string) error { } func GetAPIKeyUUID(apiKey string) string { - client, err := getFirestoreClient() - if err != nil { - log.Printf("Error retriving firestore client: %v", err) - return "" - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Create a reference to the Firestore collection - ref := client.Collection(Firestore.ApiKeyCollection) + ref := Client.Collection(Firestore.ApiKeyCollection) - // Query Firestore to check if the API key exists iter := ref.Where("APIKey", "==", apiKey).Limit(1).Documents(ctx) defer iter.Stop() var key structs.APIKey - // Iterate over the query results for { doc, err := iter.Next() if errors.Is(err, iterator.Done) { @@ -232,13 +161,8 @@ func GetAPIKeyUUID(apiKey string) string { return "" } } - clientAuth, err := authenticate.GetFireBaseAuthClient() // Assuming you have your initFirebase function from earlier - if err != nil { - log.Printf("Error retriving firebase auth client: %v", err) - return "" - } - _, err = clientAuth.GetUser(ctx, key.UUID) + _, err = authenticate.Client.GetUser(ctx, key.UUID) if err != nil { log.Println("Error getting user:", err) return "" @@ -248,22 +172,8 @@ func GetAPIKeyUUID(apiKey string) string { } func AddRegistration(docID string, data *structs.CountryInfoInternal) error { - client, err := getFirestoreClient() - if err != nil { - return err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Create a reference to the Firestore collection - ref := client.Collection(Firestore.RegistrationCollection) + ref := Client.Collection(Firestore.RegistrationCollection) - // Create a new document and add to it _, err = ref.Doc(docID).Set(ctx, map[string]interface{}{ "ID": data.ID, "UUID": data.UUID, @@ -280,22 +190,8 @@ func AddRegistration(docID string, data *structs.CountryInfoInternal) error { } func GetRegistrations(UUID string) ([]*structs.CountryInfoInternal, error) { - client, err := getFirestoreClient() - if err != nil { - return nil, err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Reference to the Firestore collection - ref := client.Collection(Firestore.RegistrationCollection) + ref := Client.Collection(Firestore.RegistrationCollection) - // Query all documents docs, _ := ref.Where("UUID", "==", UUID).OrderBy("Lastchange", firestore.Desc).Documents(ctx).GetAll() if err != nil { log.Printf("Error fetching Registration: %v\n", err) @@ -317,27 +213,13 @@ func GetRegistrations(UUID string) ([]*structs.CountryInfoInternal, error) { } func GetSpecificRegistration(ID, UUID string) (*structs.CountryInfoInternal, error) { - client, err := getFirestoreClient() - if err != nil { - return nil, err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Reference to the Firestore collection - ref := client.Collection(Firestore.RegistrationCollection) + ref := Client.Collection(Firestore.RegistrationCollection) iter := ref.Where("ID", "==", ID).Where("UUID", "==", UUID).Limit(1).Documents(ctx) defer iter.Stop() var ci *structs.CountryInfoInternal - // Iterate over the query results for { doc, err := iter.Next() if errors.Is(err, iterator.Done) { @@ -357,25 +239,11 @@ func GetSpecificRegistration(ID, UUID string) (*structs.CountryInfoInternal, err } func UpdateRegistration(ID, UUID string, data *structs.CountryInfoInternal) error { - client, err := getFirestoreClient() - if err != nil { - return err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Reference to the Firestore collection - ref := client.Collection(Firestore.RegistrationCollection) + ref := Client.Collection(Firestore.RegistrationCollection) iter := ref.Where("ID", "==", ID).Where("UUID", "==", UUID).Limit(1).Documents(ctx) defer iter.Stop() - // Iterate over the query results for { doc, err := iter.Next() if errors.Is(err, iterator.Done) { @@ -403,20 +271,7 @@ func UpdateRegistration(ID, UUID string, data *structs.CountryInfoInternal) erro } func DeleteRegistration(ID, UUID string) error { - client, err := getFirestoreClient() - if err != nil { - return err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Create a reference to the Firestore collection - ref := client.Collection(Firestore.RegistrationCollection) + ref := Client.Collection(Firestore.RegistrationCollection) iter := ref.Where("ID", "==", ID).Where("UUID", "==", UUID).Limit(1).Documents(ctx) defer iter.Stop() @@ -433,12 +288,10 @@ func DeleteRegistration(ID, UUID string) error { docID = doc.Ref.ID } - // If docID is empty, the API key does not exist in Firestore if docID == "" { return errors.New("ID match was not found") } - // Delete the document with the provided API key _, err = ref.Doc(docID).Delete(ctx) if err != nil { return fmt.Errorf("failed to delete document: %v", err) @@ -449,22 +302,8 @@ func DeleteRegistration(ID, UUID string) error { } func AddWebhook(docID string, webhook *structs.WebhookGet) error { - client, err := getFirestoreClient() - if err != nil { - return err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) + ref := Client.Collection(Firestore.WebhookCollection) - // Create a reference to the Firestore collection - ref := client.Collection(Firestore.WebhookCollection) - - // Create a new document and add it to the _, err = ref.Doc(docID).Set(ctx, webhook) if err != nil { log.Printf(FirebaseClosingErr, err) @@ -475,22 +314,8 @@ func AddWebhook(docID string, webhook *structs.WebhookGet) error { } func GetAllWebhooks() ([]structs.WebhookGet, error) { - client, err := getFirestoreClient() - if err != nil { - return nil, err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Reference to the Firestore collection - ref := client.Collection(Firestore.WebhookCollection) + ref := Client.Collection(Firestore.WebhookCollection) - // Query all documents docs, err := ref.Documents(ctx).GetAll() if err != nil { log.Printf("Error fetching all stored Webhooks: %v\n", err) @@ -512,22 +337,8 @@ func GetAllWebhooks() ([]structs.WebhookGet, error) { } func GetWebhooksUser(UUID string) ([]structs.WebhookResponse, error) { - client, err := getFirestoreClient() - if err != nil { - return nil, err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Reference to the Firestore collection - ref := client.Collection(Firestore.WebhookCollection) + ref := Client.Collection(Firestore.WebhookCollection) - // Query all documents docs, err := ref.Where("UUID", "==", UUID).Documents(ctx).GetAll() if err != nil { log.Printf("Error fetching users webhooks: %v\n", err) @@ -549,27 +360,13 @@ func GetWebhooksUser(UUID string) ([]structs.WebhookResponse, error) { } func GetSpecificWebhook(ID, UUID string) (*structs.WebhookResponse, error) { - client, err := getFirestoreClient() - if err != nil { - return nil, err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Reference to the Firestore collection - ref := client.Collection(Firestore.WebhookCollection) + ref := Client.Collection(Firestore.WebhookCollection) iter := ref.Where("ID", "==", ID).Where("UUID", "==", UUID).Limit(1).Documents(ctx) defer iter.Stop() var webhook *structs.WebhookResponse - // Iterate over the query results for { doc, err := iter.Next() if errors.Is(err, iterator.Done) { @@ -588,20 +385,7 @@ func GetSpecificWebhook(ID, UUID string) (*structs.WebhookResponse, error) { } func DeleteWebhook(ID, UUID string) error { - client, err := getFirestoreClient() - if err != nil { - return err - } - defer func(client *firestore.Client) { - err := client.Close() - if err != nil { - log.Printf(FirebaseClosingErr, err) - return - } - }(client) - - // Create a reference to the Firestore collection - ref := client.Collection(Firestore.WebhookCollection) + ref := Client.Collection(Firestore.WebhookCollection) iter := ref.Where("ID", "==", ID).Where("UUID", "==", UUID).Limit(1).Documents(ctx) defer iter.Stop() @@ -618,12 +402,10 @@ func DeleteWebhook(ID, UUID string) error { docID = doc.Ref.ID } - // If docID is empty, the API key does not exist in Firestore if docID == "" { return fmt.Errorf("ID match was not found") } - // Delete the document with the provided API key _, err = ref.Doc(docID).Delete(ctx) if err != nil { return fmt.Errorf("failed to delete document: %v", err) diff --git a/Go/docker-compose.yml b/Go/docker-compose.yml index 44bb571..967d997 100644 --- a/Go/docker-compose.yml +++ b/Go/docker-compose.yml @@ -10,6 +10,7 @@ services: environment: PORT: ${PORT} FIREBASE_CREDENTIALS_FILE: /run/secrets/Firebase + FIRESTORE_PROJECT_ID: ${FIRESTORE_PROJECT_ID} volumes: - ./web:/root/web:ro secrets: @@ -23,6 +24,7 @@ services: restart: no environment: FIREBASE_CREDENTIALS_FILE: /run/secrets/Firebase + FIRESTORE_PROJECT_ID: ${FIRESTORE_PROJECT_ID} volumes: - ./web:/root/web:ro secrets: diff --git a/Go/internal/func/dashboardFunctions.go b/Go/internal/func/dashboardFunctions.go index 986106b..6fc55ee 100644 --- a/Go/internal/func/dashboardFunctions.go +++ b/Go/internal/func/dashboardFunctions.go @@ -123,12 +123,6 @@ func GetCoordinates(isocode string) (structs.CoordinatesDashboard, error) { if err != nil { return empty, err } - defer func(Body io.ReadCloser) { - err := Body.Close() - if err != nil { - log.Print("Error closing countries api response body @ dashboardFunctions:GetCapital: ", err) - } - }(response.Body) body, err := io.ReadAll(response.Body) if err != nil { @@ -157,12 +151,6 @@ func GetPopulation(isocode string) (int, error) { if err != nil { return 0, err } - defer func(Body io.ReadCloser) { - err := Body.Close() - if err != nil { - log.Print("Error closing countries api response body @ dashboardFunctions:GetPopulation: ", err) - } - }(response.Body) body, err := io.ReadAll(response.Body) if err != nil { @@ -232,7 +220,6 @@ func GetExchangeRate(isocode string, currencies []string) (map[string]float64, e return exchangeRate, nil } -// fetchCurrencyRates sends an HTTP GET request to the currency rates API and extracts the rates as a map func fetchCurrencyRates(currency string) (map[string]float64, error) { response, err := http.Get(External.CurrencyAPI + currency) if err != nil { @@ -263,12 +250,6 @@ func getExchangeRateList(isocode string) (map[string]float64, error) { if err != nil { return nil, err } - defer func(Body io.ReadCloser) { - err := Body.Close() - if err != nil { - log.Print("Error closing countries api response body @ dashboardFunctions:getExchangeRateList: ", err) - } - }(response.Body) body, err := io.ReadAll(response.Body) if err != nil { @@ -288,5 +269,5 @@ func getExchangeRateList(isocode string) (map[string]float64, error) { return rates, nil } - return nil, errors.New("no currency currency found") + return nil, errors.New("no currency data found") } diff --git a/Go/internal/func/supported_countries.go b/Go/internal/func/supported_countries.go index 0f10336..2c72d70 100644 --- a/Go/internal/func/supported_countries.go +++ b/Go/internal/func/supported_countries.go @@ -13,7 +13,7 @@ import ( "time" ) -// getSupportedCountries fetches countries with their common names and cca2 codes. +// getSupportedCountries fetches supported countries with their common names and cca2 codes. func getSupportedCountries() (map[string]string, error) { url := fmt.Sprintf("%sall?fields=name,cca2", External.CountriesAPI) var responseData []struct { @@ -54,8 +54,9 @@ func ValidateCountryInfo(ci *structs.CountryInfoInternal) error { } if !ci.Features.Temperature && !ci.Features.Precipitation && !ci.Features.Capital && - !ci.Features.Coordinates && !ci.Features.Population && !ci.Features.Area { - return errors.New("at least one feature must be true") + !ci.Features.Coordinates && !ci.Features.Population && !ci.Features.Area && + (ci.Features.TargetCurrencies == nil || len(ci.Features.TargetCurrencies) == 0) { + return errors.New("at least one feature must be populated") } return nil } diff --git a/Go/internal/func/webhook_payload.go b/Go/internal/func/webhook_payload.go index cf0e16b..fb99317 100644 --- a/Go/internal/func/webhook_payload.go +++ b/Go/internal/func/webhook_payload.go @@ -25,16 +25,10 @@ var ( ) func LoopSendWebhooksRegistrations(caller string, ci *structs.CountryInfoExternal, endpoint, eventAction string) { - client, err := authenticate.GetFireBaseAuthClient() - if err != nil { - log.Printf("Error initializing Firebase Auth: %v", err) - return - } - ctx := context.Background() // Ignoring error as we've already confirmed the caller at the endpoint. - user, _ := client.GetUser(ctx, caller) + user, _ := authenticate.Client.GetUser(ctx, caller) email := user.DisplayName + " (" + strings.ToLower(user.Email) + ")" @@ -90,16 +84,10 @@ func LoopSendWebhooksRegistrations(caller string, ci *structs.CountryInfoExterna } func LoopSendWebhooksDashboard(caller string, dr *structs.DashboardResponse) { - client, err := authenticate.GetFireBaseAuthClient() - if err != nil { - log.Printf("Error initializing Firebase Auth: %v", err) - return - } - ctx := context.Background() // Ignoring error as we've already confirmed the caller at the endpoint. - user, _ := client.GetUser(ctx, caller) + user, _ := authenticate.Client.GetUser(ctx, caller) email := user.DisplayName + " (" + strings.ToLower(user.Email) + ")" title = Webhooks.GETTitle @@ -179,12 +167,12 @@ func sendDiscordWebhookPayload(email, title string, color int, event, endpoint s log.Println("Error marshaling request body:", err) return } + // Remove the UUID field from the payload. requestBodyString := string(requestBodyJSON) requestBodyString = strings.Replace(requestBodyString, " \"uuid\": \"\",\n", "", -1) requestBodyString = fmt.Sprintf("```json\n%s\n```", requestBodyString) - // Define default and dynamic fields fields := []structs.Field{ { Name: "Event", @@ -228,24 +216,20 @@ func sendDiscordWebhookPayload(email, title string, color int, event, endpoint s }, } - // Convert the payload into a JSON string payloadBytes, err := json.Marshal(payload) if err != nil { log.Println("Error marshaling payload:", err) return } - // Create a new request using http req, err := http.NewRequest("POST", payloadUrl, bytes.NewBuffer(payloadBytes)) if err != nil { log.Println("Error creating request:", err) return } - // Set headers req.Header.Set("Content-Type", "application/json") - // Execute the request client := &http.Client{} resp, err := client.Do(req) if err != nil { @@ -253,16 +237,11 @@ func sendDiscordWebhookPayload(email, title string, color int, event, endpoint s return } - // Read the response body - body, err := io.ReadAll(resp.Body) + _, err = io.ReadAll(resp.Body) if err != nil { log.Println("Error reading response body:", err) return } - - // You can now log the response status and body - log.Println("Response Status:", resp.Status) - log.Println("Response Body:", string(body)) } func sendWebhookPayload(email, title string, event, endpoint, country string, payloadUrl string) { @@ -276,24 +255,20 @@ func sendWebhookPayload(email, title string, event, endpoint, country string, pa "timestamp": time.Now().UTC().Format("2006-01-02T15:04:05.999Z"), // Formatting the current time to ISO8601 } - // Convert the payload into a JSON string payloadBytes, err := json.Marshal(payload) if err != nil { log.Println("Error marshaling payload:", err) return } - // Create a new request using http req, err := http.NewRequest(http.MethodPost, payloadUrl, bytes.NewBuffer(payloadBytes)) if err != nil { log.Println("Error creating request:", err) return } - // Set headers req.Header.Set("Content-Type", "application/json") - // Execute the request client := &http.Client{} resp, err := client.Do(req) if err != nil { @@ -301,13 +276,9 @@ func sendWebhookPayload(email, title string, event, endpoint, country string, pa return } - // Read the response body - body, err := io.ReadAll(resp.Body) + _, err = io.ReadAll(resp.Body) if err != nil { log.Println("Error reading response body:", err) return } - - // You can now log the response status and body - log.Println("Response Status:" + resp.Status + "Response Body:" + string(body)) } diff --git a/Go/internal/handlers/endpoint/dashboard/dashboards_id_handler.go b/Go/internal/handlers/endpoint/dashboard/dashboards_id_handler.go index 394437e..261c422 100644 --- a/Go/internal/handlers/endpoint/dashboard/dashboards_id_handler.go +++ b/Go/internal/handlers/endpoint/dashboard/dashboards_id_handler.go @@ -17,7 +17,6 @@ const ( RetrivalError = "Error getting country information" ) -// DashboardsIdHandler handles requests to the book count API endpoint. func DashboardsIdHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: @@ -28,7 +27,6 @@ func DashboardsIdHandler(w http.ResponseWriter, r *http.Request) { } } -// handleDashboardGetRequest handles GET requests to retrieve book count information. func handleDashboardGetRequest(w http.ResponseWriter, r *http.Request) { ID := r.PathValue("ID") query := r.URL.Query() @@ -43,7 +41,7 @@ func handleDashboardGetRequest(w http.ResponseWriter, r *http.Request) { http.Error(w, err, http.StatusNotAcceptable) return } - if ID == "" { + if ID == "" || ID == " " { http.Error(w, ProvideID, http.StatusBadRequest) return } @@ -79,16 +77,12 @@ func handleDashboardGetRequest(w http.ResponseWriter, r *http.Request) { // Set the LastRetrieval time and format it to ISO8601 format to mirror Firestore Timestamp dr.LastRetrieval = time.Now().UTC().Format("2006-01-02T15:04:05.999Z") - // Set Content-Type header w.Header().Set("Content-Type", "application/json") - // Write the status code to the response w.WriteHeader(http.StatusOK) - // Serialize the struct to JSON and write it to the response err = json.NewEncoder(w).Encode(dr) if err != nil { - // Handle error http.Error(w, err.Error(), http.StatusInternalServerError) return } diff --git a/Go/internal/handlers/endpoint/dashboard/notifications_handler.go b/Go/internal/handlers/endpoint/dashboard/notifications_handler.go index f4efe27..10dcfcb 100644 --- a/Go/internal/handlers/endpoint/dashboard/notifications_handler.go +++ b/Go/internal/handlers/endpoint/dashboard/notifications_handler.go @@ -12,7 +12,6 @@ import ( "net/http" ) -// NotificationsHandler handles requests to retrieve readership dashboard for a specific language. func NotificationsHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodPost: @@ -76,16 +75,12 @@ func handleNotifPostRequest(w http.ResponseWriter, r *http.Request) { "id": hook.ID, } - // Set Content-Type header w.Header().Set(ContentType, ApplicationJSON) - // Write the status code to the response w.WriteHeader(http.StatusCreated) - // Serialize the struct to JSON and write it to the response err = json.NewEncoder(w).Encode(response) if err != nil { - // Handle error http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -106,21 +101,17 @@ func handleNotifGetAllRequest(w http.ResponseWriter, r *http.Request) { } regs, err := db.GetWebhooksUser(UUID) if err != nil { - errmsg := fmt.Sprint("Error retrieving document from database: ", err) + errmsg := fmt.Sprint("Error retrieving webhooks from database: ", err) http.Error(w, errmsg, http.StatusInternalServerError) return } - // Set Content-Type header w.Header().Set(ContentType, ApplicationJSON) - // Write the status code to the response w.WriteHeader(http.StatusOK) - // Serialize the struct to JSON and write it to the response err = json.NewEncoder(w).Encode(regs) if err != nil { - // Handle error http.Error(w, err.Error(), http.StatusInternalServerError) return } diff --git a/Go/internal/handlers/endpoint/dashboard/notifications_id_handler.go b/Go/internal/handlers/endpoint/dashboard/notifications_id_handler.go index 8958cc9..5c2983b 100644 --- a/Go/internal/handlers/endpoint/dashboard/notifications_id_handler.go +++ b/Go/internal/handlers/endpoint/dashboard/notifications_id_handler.go @@ -5,11 +5,9 @@ import ( "encoding/json" "fmt" "globeboard/db" - "log" "net/http" ) -// NotificationsIdHandler handles requests to retrieve readership dashboard for a specific language. func NotificationsIdHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: @@ -36,28 +34,24 @@ func handleNotifGetRequest(w http.ResponseWriter, r *http.Request) { http.Error(w, err, http.StatusNotAcceptable) return } - if ID == "" { + if ID == "" || ID == " " { http.Error(w, ProvideID, http.StatusBadRequest) return } hook, err := db.GetSpecificWebhook(ID, UUID) if err != nil { - log.Print("Error getting document from database: ", err) - http.Error(w, "Error retrieving data from database", http.StatusNotFound) + err := fmt.Sprintf("Error getting document from database: %v", err) + http.Error(w, err, http.StatusNotFound) return } - // Set Content-Type header w.Header().Set(ContentType, ApplicationJSON) - // Write the status code to the response w.WriteHeader(http.StatusOK) - // Serialize the struct to JSON and write it to the response err = json.NewEncoder(w).Encode(hook) if err != nil { - // Handle error http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -77,7 +71,7 @@ func handleNotifDeleteRequest(w http.ResponseWriter, r *http.Request) { http.Error(w, err, http.StatusNotAcceptable) return } - if ID == "" { + if ID == "" || ID == " " { http.Error(w, ProvideID, http.StatusBadRequest) return } diff --git a/Go/internal/handlers/endpoint/dashboard/registrations_handler.go b/Go/internal/handlers/endpoint/dashboard/registrations_handler.go index 093ee9a..67ee8d1 100644 --- a/Go/internal/handlers/endpoint/dashboard/registrations_handler.go +++ b/Go/internal/handlers/endpoint/dashboard/registrations_handler.go @@ -22,7 +22,6 @@ const ( ApplicationJSON = "application/json" ) -// RegistrationsHandler handles HTTP GET requests to retrieve supported languages. func RegistrationsHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodPost: @@ -49,7 +48,6 @@ func DecodeCountryInfo(data io.ReadCloser) (*structs.CountryInfoInternal, error) return ci, nil } -// handleRegPostRequest handles POST requests to register a country. func handleRegPostRequest(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() token := query.Get("token") @@ -70,7 +68,6 @@ func handleRegPostRequest(w http.ResponseWriter, r *http.Request) { return } - // Decode the body into a CountryInfoPost struct ci, err := DecodeCountryInfo(r.Body) if err != nil { err := fmt.Sprintf("Error decoding request body: %v", err) @@ -103,16 +100,12 @@ func handleRegPostRequest(w http.ResponseWriter, r *http.Request) { "lastChange": reg.Lastchange, } - // Set Content-Type header w.Header().Set(ContentType, ApplicationJSON) - // Write the status code to the response w.WriteHeader(http.StatusCreated) - // Serialize the struct to JSON and write it to the response err = json.NewEncoder(w).Encode(response) if err != nil { - // Handle error http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -126,7 +119,6 @@ func handleRegPostRequest(w http.ResponseWriter, r *http.Request) { _func.LoopSendWebhooksRegistrations(UUID, cie, Endpoints.Registrations, Webhooks.EventRegister) } -// handleRegGetAllRequest handles GET requests to retrieve a registered country. func handleRegGetAllRequest(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() token := query.Get("token") @@ -147,13 +139,10 @@ func handleRegGetAllRequest(w http.ResponseWriter, r *http.Request) { return } - // Set Content-Type header w.Header().Set(ContentType, ApplicationJSON) - // Write the status code to the response w.WriteHeader(http.StatusOK) - // Parse Data for External Users var cies []*structs.CountryInfoExternal for _, reg := range regs { cie := new(structs.CountryInfoExternal) @@ -165,10 +154,8 @@ func handleRegGetAllRequest(w http.ResponseWriter, r *http.Request) { cies = append(cies, cie) } - // Serialize the struct to JSON and write it to the response err = json.NewEncoder(w).Encode(cies) if err != nil { - // Handle error http.Error(w, err.Error(), http.StatusInternalServerError) return } diff --git a/Go/internal/handlers/endpoint/dashboard/registrations_id_handler.go b/Go/internal/handlers/endpoint/dashboard/registrations_id_handler.go index 4f06d22..1842594 100644 --- a/Go/internal/handlers/endpoint/dashboard/registrations_id_handler.go +++ b/Go/internal/handlers/endpoint/dashboard/registrations_id_handler.go @@ -18,7 +18,6 @@ const ( ProvideID = "Please Provide ID" ) -// RegistrationsIdHandler handles HTTP GET requests to retrieve supported languages. func RegistrationsIdHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: @@ -33,7 +32,6 @@ func RegistrationsIdHandler(w http.ResponseWriter, r *http.Request) { } } -// handleRegGetRequest handles GET requests to retrieve a registered country. func handleRegGetRequest(w http.ResponseWriter, r *http.Request) { ID := r.PathValue("ID") query := r.URL.Query() @@ -48,7 +46,7 @@ func handleRegGetRequest(w http.ResponseWriter, r *http.Request) { http.Error(w, err, http.StatusNotAcceptable) return } - if ID == "" { + if ID == "" || ID == " " { http.Error(w, ProvideID, http.StatusBadRequest) return } @@ -60,10 +58,8 @@ func handleRegGetRequest(w http.ResponseWriter, r *http.Request) { return } - // Set Content-Type header w.Header().Set(ContentType, ApplicationJSON) - // Write the status code to the response w.WriteHeader(http.StatusOK) cie := new(structs.CountryInfoExternal) @@ -73,10 +69,8 @@ func handleRegGetRequest(w http.ResponseWriter, r *http.Request) { cie.Features = reg.Features cie.Lastchange = reg.Lastchange - // Serialize the struct to JSON and write it to the response err = json.NewEncoder(w).Encode(cie) if err != nil { - // Handle error http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -84,7 +78,6 @@ func handleRegGetRequest(w http.ResponseWriter, r *http.Request) { _func.LoopSendWebhooksRegistrations(UUID, cie, Endpoints.RegistrationsID, Webhooks.EventInvoke) } -// handleRegPatchRequest handles PUT requests to Update a registered country. func handleRegPatchRequest(w http.ResponseWriter, r *http.Request) { ID := r.PathValue("ID") query := r.URL.Query() @@ -99,7 +92,7 @@ func handleRegPatchRequest(w http.ResponseWriter, r *http.Request) { http.Error(w, err, http.StatusNotAcceptable) return } - if ID == "" { + if ID == "" || ID == " " { http.Error(w, ProvideID, http.StatusBadRequest) return } @@ -119,7 +112,7 @@ func handleRegPatchRequest(w http.ResponseWriter, r *http.Request) { err = _func.ValidateCountryInfo(ci) if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusBadRequest) return } @@ -201,13 +194,11 @@ func patchCountryInformation(r *http.Request, ID, UUID string) (*structs.Country } } - // Marshal the original data back to JSON. jsonData, err := json.Marshal(originalData) if err != nil { return nil, err, http.StatusInternalServerError } - // Unmarshal the JSON data into the CountryInfoInternal struct. var countryInfo *structs.CountryInfoInternal err = json.Unmarshal(jsonData, &countryInfo) if err != nil { @@ -224,9 +215,9 @@ func validatePatchData(patchData map[string]interface{}, originalData map[string } } - if isoCode, ok := patchData["isoCode"]; ok { - if isoCodeStr, isStr := isoCode.(string); isStr && isoCodeStr != "" && originalData["isoCode"] != isoCode { - return nil, errors.New("modification of 'isoCode' field is not allowed"), http.StatusBadRequest + if isoCode, ok := patchData["isocode"]; ok { + if isoCodeStr, isStr := isoCode.(string); isStr && isoCodeStr != "" && originalData["isocode"] != isoCode { + return nil, errors.New("modification of 'isocode' field is not allowed"), http.StatusBadRequest } } @@ -256,7 +247,7 @@ func handleRegDeleteRequest(w http.ResponseWriter, r *http.Request) { http.Error(w, err, http.StatusNotAcceptable) return } - if ID == "" { + if ID == "" || ID == " " { http.Error(w, ProvideID, http.StatusBadRequest) return } diff --git a/Go/internal/handlers/endpoint/dashboard/status_handler.go b/Go/internal/handlers/endpoint/dashboard/status_handler.go index 424c5f6..e5babb1 100644 --- a/Go/internal/handlers/endpoint/dashboard/status_handler.go +++ b/Go/internal/handlers/endpoint/dashboard/status_handler.go @@ -13,27 +13,20 @@ import ( "time" ) -// getEndpointStatus returns the HTTP status code of the provided endpoint. func getEndpointStatus(endpointURL string) string { - // Create new request r, err := http.NewRequest(http.MethodGet, endpointURL, nil) if err != nil { - // Log and handle the error if request creation fails. err := fmt.Errorf("error in creating request: %v", err) log.Println(err) } - // Set content type header r.Header.Add("content-type", "application/json") - // Create an HTTP client client := &http.Client{} defer client.CloseIdleConnections() - // Issue request res, err := client.Do(r) if err != nil { - // Log and handle the error if request execution fails. err := fmt.Errorf("error in response: %v", err) log.Println(err) } @@ -41,19 +34,16 @@ func getEndpointStatus(endpointURL string) string { return res.Status } -// StatusHandler handles requests to retrieve the status of Endpoints. func StatusHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: handleStatusGetRequest(w, r) default: - // If the method is not supported, return an error response. http.Error(w, "REST Method: "+r.Method+" not supported. Only supported methods for this endpoint is: "+http.MethodGet, http.StatusNotImplemented) return } } -// handleStatusGetRequest handles GET requests to retrieve the status of Endpoints. func handleStatusGetRequest(w http.ResponseWriter, r *http.Request) { token := r.URL.Query().Get("token") if token == "" { @@ -67,36 +57,30 @@ func handleStatusGetRequest(w http.ResponseWriter, r *http.Request) { return } - user, err := db.GetWebhooksUser(UUID) + webhooksUser, err := db.GetWebhooksUser(UUID) if err != nil { log.Print("Error retrieving users webhooks:", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } - // Initialize a status response. status := structs.StatusResponse{ - CountriesApi: getEndpointStatus(External.CountriesAPI + "alpha?codes=no"), - MeteoApi: getEndpointStatus(External.OpenMeteoAPI), - CurrencyApi: getEndpointStatus(External.CurrencyAPI + "nok"), - FirebaseDB: db.TestDBConnection(), - Webhooks: len(user), - Version: constants.APIVersion, - // Calculate uptime since the last restart of the service. + CountriesApi: getEndpointStatus(External.CountriesAPI + "alpha?codes=no"), + MeteoApi: getEndpointStatus(External.OpenMeteoAPI), + CurrencyApi: getEndpointStatus(External.CurrencyAPI + "nok"), + FirebaseDB: db.TestDBConnection(), + Webhooks: len(webhooksUser), + Version: constants.APIVersion, UptimeInSeconds: fmt.Sprintf("%f Seconds", time.Since(startTime).Seconds()), } - // Set content type header w.Header().Add("content-type", "application/json") - // Encode status as JSON and send the response. err = json.NewEncoder(w).Encode(status) if err != nil { - // If encoding fails, return an error response. http.Error(w, "Error during encoding: "+err.Error(), http.StatusInternalServerError) return } } -// startTime keeps track of the service start time. var startTime = time.Now() diff --git a/Go/internal/handlers/endpoint/util/apikey_handler.go b/Go/internal/handlers/endpoint/util/apikey_handler.go index 10058a1..5590474 100644 --- a/Go/internal/handlers/endpoint/util/apikey_handler.go +++ b/Go/internal/handlers/endpoint/util/apikey_handler.go @@ -32,15 +32,7 @@ func handleApiKeyDeleteRequest(w http.ResponseWriter, r *http.Request) { ctx := context.Background() - client, err := authenticate.GetFireBaseAuthClient() - if err != nil { - log.Printf("error getting Auth client: %v\n", err) - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - return - } - - // Verify the ID token - _, err = client.GetUser(ctx, UUID) + _, err := authenticate.Client.GetUser(ctx, UUID) if err != nil { log.Printf("error verifying UUID: %v\n", err) http.Error(w, "Not Authorized", http.StatusUnauthorized) @@ -71,15 +63,7 @@ func handleApiKeyGetRequest(w http.ResponseWriter, r *http.Request) { ctx := context.Background() - client, err := authenticate.GetFireBaseAuthClient() - if err != nil { - log.Printf("error getting Auth client: %v\n", err) - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - return - } - - // Verify the ID token - _, err = client.GetUser(ctx, UUID) + _, err := authenticate.Client.GetUser(ctx, UUID) if err != nil { log.Printf("error verifying UUID: %v\n", err) http.Error(w, "Not Authorized", http.StatusUnauthorized) @@ -99,7 +83,6 @@ func handleApiKeyGetRequest(w http.ResponseWriter, r *http.Request) { "token": key, } - // Encode books as JSON and send the response. if err := json.NewEncoder(w).Encode(response); err != nil { http.Error(w, "Error encoding JSON response: "+err.Error(), http.StatusInternalServerError) return diff --git a/Go/internal/handlers/endpoint/util/user_delete_handler.go b/Go/internal/handlers/endpoint/util/user_delete_handler.go index 30748a0..c146b68 100644 --- a/Go/internal/handlers/endpoint/util/user_delete_handler.go +++ b/Go/internal/handlers/endpoint/util/user_delete_handler.go @@ -7,7 +7,6 @@ import ( "net/http" ) -// UserDeletionHandler handles HTTP Delete requests func UserDeletionHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodDelete: @@ -20,21 +19,14 @@ func UserDeletionHandler(w http.ResponseWriter, r *http.Request) { func deleteUser(w http.ResponseWriter, r *http.Request) { ID := r.PathValue("ID") - if ID == "" { + if ID == "" || ID == " " { http.Error(w, "Please Provide User ID", http.StatusBadRequest) return } - // Initialize Firebase - client, err := authenticate.GetFireBaseAuthClient() // Assuming you have your initFirebase function from earlier - if err != nil { - http.Error(w, "Error initializing Firebase Auth", http.StatusInternalServerError) - return - } - ctx := context.Background() - err = client.DeleteUser(ctx, ID) + err := authenticate.Client.DeleteUser(ctx, ID) if err != nil { log.Printf("error deleting user: %v\n", err) http.Error(w, err.Error(), http.StatusInternalServerError) diff --git a/Go/internal/handlers/endpoint/util/user_register_handler.go b/Go/internal/handlers/endpoint/util/user_register_handler.go index 684675f..984fa4c 100644 --- a/Go/internal/handlers/endpoint/util/user_register_handler.go +++ b/Go/internal/handlers/endpoint/util/user_register_handler.go @@ -17,7 +17,6 @@ const ( ISE = "Internal Server Error" ) -// UserRegistrationHandler handles HTTP POST requests func UserRegistrationHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodPost: @@ -29,13 +28,6 @@ func UserRegistrationHandler(w http.ResponseWriter, r *http.Request) { } func registerUser(w http.ResponseWriter, r *http.Request) { - - // Initialize Firebase - client, err := authenticate.GetFireBaseAuthClient() // Assuming you have your initFirebase function from earlier - if err != nil { - http.Error(w, "Error initializing Firebase Auth", http.StatusInternalServerError) - return - } name := r.FormValue("username") email := r.FormValue("email") password := r.FormValue("password") @@ -58,7 +50,8 @@ func registerUser(w http.ResponseWriter, r *http.Request) { DisplayName(name). Email(email). Password(password) - u, err := client.CreateUser(ctx, params) + + u, err := authenticate.Client.CreateUser(ctx, params) if err != nil { log.Printf("error creating user: %v\n", err) http.Error(w, err.Error(), http.StatusInternalServerError) diff --git a/Go/internal/utils/constants/External/external.go b/Go/internal/utils/constants/External/external.go index f82f680..7934e16 100644 --- a/Go/internal/utils/constants/External/external.go +++ b/Go/internal/utils/constants/External/external.go @@ -1,4 +1,4 @@ -// Package External provides external API endpoints used in the application. +// Package External provides external API endpoints used throughout the application. package External // CurrencyAPI represents the endpoint for the Currency API. diff --git a/Go/internal/utils/constants/Paths/paths.go b/Go/internal/utils/constants/Paths/paths.go index fca9208..1cce018 100644 --- a/Go/internal/utils/constants/Paths/paths.go +++ b/Go/internal/utils/constants/Paths/paths.go @@ -3,7 +3,7 @@ package Paths // Root represents the root path. // Util represents the root path to the util endpoints -// Dashboards represents the root path to the util stats endpoints +// Dashboards represents the root path to the dashboard endpoints const ( Root = "/" Util = "/util/" diff --git a/Go/internal/utils/constants/constants.go b/Go/internal/utils/constants/constants.go index a79df75..bca0e37 100644 --- a/Go/internal/utils/constants/constants.go +++ b/Go/internal/utils/constants/constants.go @@ -1,7 +1,6 @@ // Package constants provide constant values used throughout the application. package constants -// APIVersion represents the version of the API. const ( APIVersion = "v1" ApiKeyLength = 20 diff --git a/Go/internal/utils/structs/structs.go b/Go/internal/utils/structs/structs.go index 4cfa3ac..0158c68 100644 --- a/Go/internal/utils/structs/structs.go +++ b/Go/internal/utils/structs/structs.go @@ -64,7 +64,6 @@ type CoordinatesDashboard struct { // Status structs -// StatusResponse represents the status response structure. type StatusResponse struct { CountriesApi string `json:"countries_api"` MeteoApi string `json:"meteo_api"` diff --git a/README.md b/README.md index c4321ba..e7ff6fb 100644 --- a/README.md +++ b/README.md @@ -197,7 +197,7 @@ In collaboration with: ```json { "id": "The registration's ID", - "lastChange": "Firestore timestamp indicating creation (RFC3339 Format)", + "lastChange": "Firestore timestamp indicating creation (ISO8601 Format)", } ``` @@ -542,6 +542,8 @@ To run this project, you will need to add the following environment variables to `FIREBASE_CREDENTIALS_FILE` - Path to your Firebase credentials file. +`FIRESTORE_PROJECT_ID` - Project ID from Google Firebase that contains Firestore. + ## Run Locally - Clone the repository -- GitLab