From 7ae6cce6b42027aa4ef6345e818dc874c3839111 Mon Sep 17 00:00:00 2001 From: al8763be Date: Mon, 18 Mar 2024 22:39:02 +0100 Subject: [PATCH 1/9] Sample data --- .../database/migrations/0010_users.sql | 2 +- .../database/sample_data/0010_sample_data.sql | 53 ++++++++++++++++--- 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/backend/internal/database/migrations/0010_users.sql b/backend/internal/database/migrations/0010_users.sql index a3ee5b1..93c4df8 100644 --- a/backend/internal/database/migrations/0010_users.sql +++ b/backend/internal/database/migrations/0010_users.sql @@ -10,4 +10,4 @@ CREATE TABLE IF NOT EXISTS users ( -- Users are commonly searched by username and userId CREATE INDEX IF NOT EXISTS users_username_index ON users (username); -CREATE INDEX IF NOT EXISTS users_userId_index ON users (userId); \ No newline at end of file +CREATE INDEX IF NOT EXISTS users_userId_index ON users (Id); \ No newline at end of file diff --git a/backend/internal/database/sample_data/0010_sample_data.sql b/backend/internal/database/sample_data/0010_sample_data.sql index f3d9412..d3012c6 100644 --- a/backend/internal/database/sample_data/0010_sample_data.sql +++ b/backend/internal/database/sample_data/0010_sample_data.sql @@ -1,7 +1,48 @@ -INSERT OR IGNORE INTO users (username, password) VALUES - ('admin', 'password'), - ('user', 'password'); +INSERT OR IGNORE INTO users(username, password) +VALUES ("admin", "123"); -INSERT OR IGNORE INTO projects (name, description, owner_user_id) VALUES - ('Project 1', 'Description 1', 1), - ('Project 2', 'Description 2', 2); \ No newline at end of file +INSERT OR IGNORE INTO users(username, password) +VALUES ("user", "123"); + +INSERT OR IGNORE INTO users(username, password) +VALUES ("user2", "123"); + +INSERT OR IGNORE INTO projects(name,description,owner_user_id) +VALUES ("projecttest","test project", 1) + +INSERT OR IGNORE INTO projects(name,description,owner_user_id) +VALUES ("projecttest2","test project2", 1) + +INSERT OR IGNORE INTO projects(name,description,owner_user_id) +VALUES ("projecttest3","test project3", 1) + +INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role) +VALUES (1,1,"project_manager"); + +INSERT INTO user_roles(user_id,project_id,p_role) +VALUES (2,1,"member"); + +INSERT INTO user_roles(user_id,project_id,p_role) +VALUES (3,1,"member"); + +INSERT INTO user_roles(user_id,project_id,p_role) +VALUES (3,2,"member"); + +INSERT INTO user_roles(user_id,project_id,p_role) +VALUES (3,3,"member"); + +INSERT INTO user_roles(user_id,project_id,p_role) +VALUES (2,1,"project_manager"); + + +SELECT p.id, p.name, p.description +FROM projects p +JOIN user_roles ur ON p.id = ur.project_id +JOIN users u ON ur.user_id = u.id +WHERE u.username = 'admin'; + +SELECT id FROM users WHERE username = "admin" + +SELECT id FROM users WHERE username = "user" + +SELECT id FROM users WHERE username = "user2" From a5399c9335219b0301837722c98c945231409d2a Mon Sep 17 00:00:00 2001 From: al8763be Date: Mon, 18 Mar 2024 22:39:43 +0100 Subject: [PATCH 2/9] Samle data without query --- backend/internal/database/sample_data/0010_sample_data.sql | 6 ------ 1 file changed, 6 deletions(-) diff --git a/backend/internal/database/sample_data/0010_sample_data.sql b/backend/internal/database/sample_data/0010_sample_data.sql index d3012c6..0af0d66 100644 --- a/backend/internal/database/sample_data/0010_sample_data.sql +++ b/backend/internal/database/sample_data/0010_sample_data.sql @@ -35,12 +35,6 @@ INSERT INTO user_roles(user_id,project_id,p_role) VALUES (2,1,"project_manager"); -SELECT p.id, p.name, p.description -FROM projects p -JOIN user_roles ur ON p.id = ur.project_id -JOIN users u ON ur.user_id = u.id -WHERE u.username = 'admin'; - SELECT id FROM users WHERE username = "admin" SELECT id FROM users WHERE username = "user" From 95b09a8ce776b00f42f66188a5eccd0d673a66ac Mon Sep 17 00:00:00 2001 From: al8763be Date: Mon, 18 Mar 2024 22:46:53 +0100 Subject: [PATCH 3/9] Fixed getProjectForUsers --- backend/internal/database/db.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/backend/internal/database/db.go b/backend/internal/database/db.go index 95cf8ed..25dd04b 100644 --- a/backend/internal/database/db.go +++ b/backend/internal/database/db.go @@ -64,9 +64,10 @@ const addWeeklyReport = `WITH UserLookup AS (SELECT id FROM users WHERE username const addUserToProject = "INSERT INTO user_roles (user_id, project_id, p_role) VALUES (?, ?, ?)" // WIP const changeUserRole = "UPDATE user_roles SET p_role = ? WHERE user_id = ? AND project_id = ?" -const getProjectsForUser = `SELECT projects.id, projects.name, projects.description, projects.owner_user_id - FROM projects JOIN user_roles ON projects.id = user_roles.project_id - JOIN users ON user_roles.user_id = users.id WHERE users.username = ?;` +const getProjectsForUser = `SELECT p.id, p.name, p.description FROM projects p + JOIN user_roles ur ON p.id = ur.project_id + JOIN users u ON ur.user_id = u.id + WHERE u.username = ?` // DbConnect connects to the database func DbConnect(dbpath string) Database { From 7932350980a99f2faf85bd4c40b42bea03febabc Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Mon, 18 Mar 2024 23:04:08 +0100 Subject: [PATCH 4/9] Exit with non-zero if migration fails --- backend/main.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/main.go b/backend/main.go index 24c3702..16a033c 100644 --- a/backend/main.go +++ b/backend/main.go @@ -46,10 +46,12 @@ func main() { // Migrate the database if err = db.Migrate(); err != nil { fmt.Println("Error migrating database: ", err) + os.Exit(1) } if err = db.MigrateSampleData(); err != nil { fmt.Println("Error migrating sample data: ", err) + os.Exit(1) } // Get our global state From 2cff1d55f9829393765180d4035308b5b1ccd46d Mon Sep 17 00:00:00 2001 From: al8763be Date: Mon, 18 Mar 2024 23:08:38 +0100 Subject: [PATCH 5/9] Fixed migration data --- .../database/sample_data/0010_sample_data.sql | 23 +++++++------------ 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/backend/internal/database/sample_data/0010_sample_data.sql b/backend/internal/database/sample_data/0010_sample_data.sql index 0af0d66..4dac91b 100644 --- a/backend/internal/database/sample_data/0010_sample_data.sql +++ b/backend/internal/database/sample_data/0010_sample_data.sql @@ -8,35 +8,28 @@ INSERT OR IGNORE INTO users(username, password) VALUES ("user2", "123"); INSERT OR IGNORE INTO projects(name,description,owner_user_id) -VALUES ("projecttest","test project", 1) +VALUES ("projecttest","test project", 1); INSERT OR IGNORE INTO projects(name,description,owner_user_id) -VALUES ("projecttest2","test project2", 1) +VALUES ("projecttest2","test project2", 1); INSERT OR IGNORE INTO projects(name,description,owner_user_id) -VALUES ("projecttest3","test project3", 1) +VALUES ("projecttest3","test project3", 1); INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role) VALUES (1,1,"project_manager"); -INSERT INTO user_roles(user_id,project_id,p_role) +INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role) VALUES (2,1,"member"); -INSERT INTO user_roles(user_id,project_id,p_role) +INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role) VALUES (3,1,"member"); -INSERT INTO user_roles(user_id,project_id,p_role) +INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role) VALUES (3,2,"member"); -INSERT INTO user_roles(user_id,project_id,p_role) +INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role) VALUES (3,3,"member"); -INSERT INTO user_roles(user_id,project_id,p_role) +INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role) VALUES (2,1,"project_manager"); - - -SELECT id FROM users WHERE username = "admin" - -SELECT id FROM users WHERE username = "user" - -SELECT id FROM users WHERE username = "user2" From 9056aafd2eb470841eb2f97b7806c6a1e21a5148 Mon Sep 17 00:00:00 2001 From: al8763be Date: Mon, 18 Mar 2024 23:34:03 +0100 Subject: [PATCH 6/9] Test for getUserProjectsAdded --- testing.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/testing.py b/testing.py index 6381afc..c094dca 100644 --- a/testing.py +++ b/testing.py @@ -28,6 +28,21 @@ addUserToProjectPath = base_url + "/api/addUserToProject" promoteToAdminPath = base_url + "/api/promoteToAdmin" getUserProjectsPath = base_url + "/api/getUserProjects" +def test_get_user_projects(): + + print("Testing get user projects") + loginResponse = login("user2", "123") + # Check if the user is added to the project + response = requests.get( + getUserProjectsPath, + json={"username": "user2"}, + headers={"Authorization": "Bearer " + loginResponse.json()["token"]}, + ) + print(response.text) + print(response.json()) + assert response.status_code == 200, "Get user projects failed" + print("got user projects successfully") + # Posts the username and password to the register endpoint def register(username: string, password: string): @@ -146,17 +161,7 @@ def test_add_user_to_project(): print(response.text) assert response.status_code == 200, "Add user to project failed" - print("Add user to project successful") - - # Check if the user is added to the project - response = requests.get( - getUserProjectsPath, - json={"username": new_user}, - headers={"Authorization": "Bearer " + admin_token}, - ) - print(response.text) - assert response.status_code == 200, "Get user projects failed" - print("got user projects successfully") + print("Add user to project successful") # Test function to sign a report def test_sign_report(): @@ -235,6 +240,7 @@ def test_sign_report(): if __name__ == "__main__": + test_get_user_projects() test_create_user() test_login() test_add_project() From 0fa7558d646992bdb2f379a958cfb2b498049d87 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Mon, 18 Mar 2024 23:38:50 +0100 Subject: [PATCH 7/9] Proper logging, all endpoint debug printing replaced with suitable log level --- .../handlers/handlers_project_related.go | 17 +++++------ .../handlers/handlers_report_related.go | 15 +++++----- .../handlers/handlers_user_related.go | 28 ++++++++++--------- backend/main.go | 3 ++ 4 files changed, 35 insertions(+), 28 deletions(-) diff --git a/backend/internal/handlers/handlers_project_related.go b/backend/internal/handlers/handlers_project_related.go index 3732249..96f6840 100644 --- a/backend/internal/handlers/handlers_project_related.go +++ b/backend/internal/handlers/handlers_project_related.go @@ -5,6 +5,7 @@ import ( "ttime/internal/types" "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/log" "github.com/golang-jwt/jwt/v5" ) @@ -69,7 +70,7 @@ func (gs *GState) GetProject(c *fiber.Ctx) error { if projectID == "" { return c.Status(400).SendString("No project ID provided") } - println("Getting project with ID: ", projectID) + log.Info("Getting project with ID: ", projectID) // Parse the project ID into an integer projectIDInt, err := strconv.Atoi(projectID) @@ -84,7 +85,7 @@ func (gs *GState) GetProject(c *fiber.Ctx) error { } // Return the project as JSON - println("Returning project: ", project.Name) + log.Info("Returning project: ", project.Name) return c.JSON(project) } @@ -111,7 +112,7 @@ func (gs *GState) AddUserToProjectHandler(c *fiber.Ctx) error { Role string `json:"role"` } if err := c.BodyParser(&requestData); err != nil { - println("Error parsing request body:", err) + log.Info("Error parsing request body:", err) return c.Status(400).SendString("Bad request") } @@ -119,27 +120,27 @@ func (gs *GState) AddUserToProjectHandler(c *fiber.Ctx) error { user := c.Locals("user").(*jwt.Token) claims := user.Claims.(jwt.MapClaims) adminUsername := claims["name"].(string) - println("Admin username from claims:", adminUsername) + log.Info("Admin username from claims:", adminUsername) isAdmin, err := gs.Db.IsSiteAdmin(adminUsername) if err != nil { - println("Error checking admin status:", err) + log.Info("Error checking admin status:", err) return c.Status(500).SendString(err.Error()) } if !isAdmin { - println("User is not a site admin:", adminUsername) + log.Info("User is not a site admin:", adminUsername) return c.Status(403).SendString("User is not a site admin") } // Add the user to the project with the specified role err = gs.Db.AddUserToProject(requestData.Username, requestData.ProjectName, requestData.Role) if err != nil { - println("Error adding user to project:", err) + log.Info("Error adding user to project:", err) return c.Status(500).SendString(err.Error()) } // Return success message - println("User added to project successfully:", requestData.Username) + log.Info("User added to project successfully:", requestData.Username) return c.SendStatus(fiber.StatusOK) } diff --git a/backend/internal/handlers/handlers_report_related.go b/backend/internal/handlers/handlers_report_related.go index 291d068..9219bd9 100644 --- a/backend/internal/handlers/handlers_report_related.go +++ b/backend/internal/handlers/handlers_report_related.go @@ -5,6 +5,7 @@ import ( "ttime/internal/types" "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/log" "github.com/golang-jwt/jwt/v5" ) @@ -37,16 +38,16 @@ func (gs *GState) SubmitWeeklyReport(c *fiber.Ctx) error { // Handler for retrieving weekly report func (gs *GState) GetWeeklyReport(c *fiber.Ctx) error { // Extract the necessary parameters from the request - println("GetWeeklyReport") + log.Info("GetWeeklyReport") user := c.Locals("user").(*jwt.Token) claims := user.Claims.(jwt.MapClaims) username := claims["name"].(string) // Extract project name and week from query parameters projectName := c.Query("projectName") - println(projectName) + log.Info(projectName) week := c.Query("week") - println(week) + log.Info(week) // Convert week to integer weekInt, err := strconv.Atoi(week) @@ -69,7 +70,7 @@ type ReportId struct { } func (gs *GState) SignReport(c *fiber.Ctx) error { - println("Signing report...") + log.Info("Signing report...") // Extract the necessary parameters from the token user := c.Locals("user").(*jwt.Token) claims := user.Claims.(jwt.MapClaims) @@ -81,9 +82,9 @@ func (gs *GState) SignReport(c *fiber.Ctx) error { if err := c.BodyParser(rid); err != nil { return err } - println("Signing report for: ", rid.ReportId) + log.Info("Signing report for: ", rid.ReportId) // reportIDInt, err := strconv.Atoi(rid.ReportId) - // println("Signing report for: ", rid.ReportId) + // log.Info("Signing report for: ", rid.ReportId) // if err != nil { // return c.Status(400).SendString("Invalid report ID") // } @@ -93,7 +94,7 @@ func (gs *GState) SignReport(c *fiber.Ctx) error { if err != nil { return c.Status(500).SendString("Failed to get project manager ID") } - println("blabla", projectManagerID) + log.Info("blabla", projectManagerID) // Call the database function to sign the weekly report err = gs.Db.SignWeeklyReport(rid.ReportId, projectManagerID) diff --git a/backend/internal/handlers/handlers_user_related.go b/backend/internal/handlers/handlers_user_related.go index 0f7c047..24175ee 100644 --- a/backend/internal/handlers/handlers_user_related.go +++ b/backend/internal/handlers/handlers_user_related.go @@ -1,10 +1,11 @@ package handlers import ( - "fmt" "time" "ttime/internal/types" + "github.com/gofiber/fiber/v2/log" + "github.com/gofiber/fiber/v2" "github.com/golang-jwt/jwt/v5" ) @@ -23,16 +24,17 @@ import ( func (gs *GState) Register(c *fiber.Ctx) error { u := new(types.NewUser) if err := c.BodyParser(u); err != nil { - println("Error parsing body") + log.Warn("Error parsing body") return c.Status(400).SendString(err.Error()) } - println("Adding user:", u.Username) + log.Info("Adding user:", u.Username) + log.Info("Adding user:", u.Username) if err := gs.Db.AddUser(u.Username, u.Password); err != nil { return c.Status(500).SendString(err.Error()) } - println("User added:", u.Username) + log.Info("User added:", u.Username) return c.Status(200).SendString("User added") } @@ -61,13 +63,13 @@ func (gs *GState) Login(c *fiber.Ctx) error { // The body type is identical to a NewUser u := new(types.NewUser) if err := c.BodyParser(u); err != nil { - println("Error parsing body") + log.Warn("Error parsing body") return c.Status(400).SendString(err.Error()) } - println("Username:", u.Username) + log.Info("Username:", u.Username) if !gs.Db.CheckUser(u.Username, u.Password) { - println("User not found") + log.Info("User not found") return c.SendStatus(fiber.StatusUnauthorized) } @@ -80,16 +82,16 @@ func (gs *GState) Login(c *fiber.Ctx) error { // Create token token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - println("Token created for user:", u.Username) + log.Info("Token created for user:", u.Username) // Generate encoded token and send it as response. t, err := token.SignedString([]byte("secret")) if err != nil { - println("Error signing token") + log.Warn("Error signing token") return c.SendStatus(fiber.StatusInternalServerError) } - println("Successfully signed token for user:", u.Username) + log.Info("Successfully signed token for user:", u.Username) return c.JSON(fiber.Map{"token": t}) } @@ -132,15 +134,15 @@ func (gs *GState) PromoteToAdmin(c *fiber.Ctx) error { } username := newUser.Username - println("Promoting user to admin:", username) // Debug print + log.Info("Promoting user to admin:", username) // Debug print // Promote the user to a site admin in the database if err := gs.Db.PromoteToAdmin(username); err != nil { - fmt.Println("Error promoting user to admin:", err) // Debug print + log.Info("Error promoting user to admin:", err) // Debug print return c.Status(500).SendString(err.Error()) } - println("User promoted to admin successfully:", username) // Debug print + log.Info("User promoted to admin successfully:", username) // Debug print // Return a success message return c.SendStatus(fiber.StatusOK) diff --git a/backend/main.go b/backend/main.go index da89043..5517dbe 100644 --- a/backend/main.go +++ b/backend/main.go @@ -10,6 +10,7 @@ import ( "github.com/BurntSushi/toml" "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/swagger" jwtware "github.com/gofiber/contrib/jwt" @@ -53,6 +54,8 @@ func main() { // Create the server server := fiber.New() + server.Use(logger.New()) + server.Get("/swagger/*", swagger.HandlerDefault) // Mount our static files (Beware of the security implications of this!) From 4c297ab2efc799a56f26b81ea7cc191751666038 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Mon, 18 Mar 2024 23:39:02 +0100 Subject: [PATCH 8/9] Old unresolved merge conflict fixed --- testing.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/testing.py b/testing.py index e342598..7a8a52b 100644 --- a/testing.py +++ b/testing.py @@ -22,13 +22,10 @@ loginPath = base_url + "/api/login" addProjectPath = base_url + "/api/project" submitReportPath = base_url + "/api/submitReport" getWeeklyReportPath = base_url + "/api/getWeeklyReport" -<<<<<<< HEAD getProjectPath = base_url + "/api/project" -======= signReportPath = base_url + "/api/signReport" addUserToProjectPath = base_url + "/api/addUserToProject" promoteToAdminPath = base_url + "/api/promoteToAdmin" ->>>>>>> 9ad89d60636ac6091d71b0bf307982becc9b89fe # Posts the username and password to the register endpoint @@ -232,9 +229,6 @@ if __name__ == "__main__": test_add_project() test_submit_report() test_get_weekly_report() -<<<<<<< HEAD test_get_project() -======= test_sign_report() test_add_user_to_project() ->>>>>>> 9ad89d60636ac6091d71b0bf307982becc9b89fe From fe08d01e15ed9e293e8c02449d947bc6f002697b Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Tue, 19 Mar 2024 00:00:18 +0100 Subject: [PATCH 9/9] Insanely verbose logging --- .../handlers/handlers_project_related.go | 10 +++++++ .../handlers/handlers_report_related.go | 30 ++++++++++++------- .../handlers/handlers_user_related.go | 16 ++++++++-- 3 files changed, 43 insertions(+), 13 deletions(-) diff --git a/backend/internal/handlers/handlers_project_related.go b/backend/internal/handlers/handlers_project_related.go index 96f6840..f3a7ea0 100644 --- a/backend/internal/handlers/handlers_project_related.go +++ b/backend/internal/handlers/handlers_project_related.go @@ -68,6 +68,7 @@ func (gs *GState) GetProject(c *fiber.Ctx) error { // Extract the project ID from the request parameters or body projectID := c.Params("projectID") if projectID == "" { + log.Info("No project ID provided") return c.Status(400).SendString("No project ID provided") } log.Info("Getting project with ID: ", projectID) @@ -75,12 +76,14 @@ func (gs *GState) GetProject(c *fiber.Ctx) error { // Parse the project ID into an integer projectIDInt, err := strconv.Atoi(projectID) if err != nil { + log.Info("Invalid project ID") return c.Status(400).SendString("Invalid project ID") } // Get the project from the database by its ID project, err := gs.Db.GetProject(projectIDInt) if err != nil { + log.Info("Error getting project:", err) return c.Status(500).SendString(err.Error()) } @@ -92,13 +95,20 @@ func (gs *GState) GetProject(c *fiber.Ctx) error { func (gs *GState) ListAllUsersProject(c *fiber.Ctx) error { // Extract the project name from the request parameters or body projectName := c.Params("projectName") + if projectName == "" { + log.Info("No project name provided") + return c.Status(400).SendString("No project name provided") + } // Get all users associated with the project from the database users, err := gs.Db.GetAllUsersProject(projectName) if err != nil { + log.Info("Error getting users for project:", err) return c.Status(500).SendString(err.Error()) } + log.Info("Returning users for project: ", projectName) + // Return the list of users as JSON return c.JSON(users) } diff --git a/backend/internal/handlers/handlers_report_related.go b/backend/internal/handlers/handlers_report_related.go index 9219bd9..85eb6e2 100644 --- a/backend/internal/handlers/handlers_report_related.go +++ b/backend/internal/handlers/handlers_report_related.go @@ -17,50 +17,62 @@ func (gs *GState) SubmitWeeklyReport(c *fiber.Ctx) error { report := new(types.NewWeeklyReport) if err := c.BodyParser(report); err != nil { + log.Info("Error parsing weekly report") return c.Status(400).SendString(err.Error()) } // Make sure all the fields of the report are valid if report.Week < 1 || report.Week > 52 { + log.Info("Invalid week number") return c.Status(400).SendString("Invalid week number") } if report.DevelopmentTime < 0 || report.MeetingTime < 0 || report.AdminTime < 0 || report.OwnWorkTime < 0 || report.StudyTime < 0 || report.TestingTime < 0 { + log.Info("Invalid time report") return c.Status(400).SendString("Invalid time report") } if err := gs.Db.AddWeeklyReport(report.ProjectName, username, report.Week, report.DevelopmentTime, report.MeetingTime, report.AdminTime, report.OwnWorkTime, report.StudyTime, report.TestingTime); err != nil { + log.Info("Error adding weekly report") return c.Status(500).SendString(err.Error()) } + log.Info("Weekly report added") return c.Status(200).SendString("Time report added") } // Handler for retrieving weekly report func (gs *GState) GetWeeklyReport(c *fiber.Ctx) error { // Extract the necessary parameters from the request - log.Info("GetWeeklyReport") user := c.Locals("user").(*jwt.Token) claims := user.Claims.(jwt.MapClaims) username := claims["name"].(string) + log.Info("Getting weekly report for: ", username) + // Extract project name and week from query parameters projectName := c.Query("projectName") - log.Info(projectName) week := c.Query("week") - log.Info(week) + + if projectName == "" || week == "" { + log.Info("Missing project name or week number") + return c.Status(400).SendString("Missing project name or week number") + } // Convert week to integer weekInt, err := strconv.Atoi(week) if err != nil { + log.Info("Invalid week number") return c.Status(400).SendString("Invalid week number") } // Call the database function to get the weekly report report, err := gs.Db.GetWeeklyReport(username, projectName, weekInt) if err != nil { + log.Info("Error getting weekly report from db:", err) return c.Status(500).SendString(err.Error()) } + log.Info("Returning weekly report") // Return the retrieved weekly report return c.JSON(report) } @@ -70,12 +82,13 @@ type ReportId struct { } func (gs *GState) SignReport(c *fiber.Ctx) error { - log.Info("Signing report...") // Extract the necessary parameters from the token user := c.Locals("user").(*jwt.Token) claims := user.Claims.(jwt.MapClaims) projectManagerUsername := claims["name"].(string) + log.Info("Signing report for: ", projectManagerUsername) + // Extract report ID from the request query parameters // reportID := c.Query("reportId") rid := new(ReportId) @@ -83,22 +96,19 @@ func (gs *GState) SignReport(c *fiber.Ctx) error { return err } log.Info("Signing report for: ", rid.ReportId) - // reportIDInt, err := strconv.Atoi(rid.ReportId) - // log.Info("Signing report for: ", rid.ReportId) - // if err != nil { - // return c.Status(400).SendString("Invalid report ID") - // } // Get the project manager's ID projectManagerID, err := gs.Db.GetUserId(projectManagerUsername) if err != nil { + log.Info("Failed to get project manager ID") return c.Status(500).SendString("Failed to get project manager ID") } - log.Info("blabla", projectManagerID) + log.Info("Project manager ID: ", projectManagerID) // Call the database function to sign the weekly report err = gs.Db.SignWeeklyReport(rid.ReportId, projectManagerID) if err != nil { + log.Info("Error signing weekly report:", err) return c.Status(500).SendString(err.Error()) } diff --git a/backend/internal/handlers/handlers_user_related.go b/backend/internal/handlers/handlers_user_related.go index 24175ee..8f4108c 100644 --- a/backend/internal/handlers/handlers_user_related.go +++ b/backend/internal/handlers/handlers_user_related.go @@ -28,9 +28,9 @@ func (gs *GState) Register(c *fiber.Ctx) error { return c.Status(400).SendString(err.Error()) } - log.Info("Adding user:", u.Username) log.Info("Adding user:", u.Username) if err := gs.Db.AddUser(u.Username, u.Password); err != nil { + log.Warn("Error adding user:", err) return c.Status(500).SendString(err.Error()) } @@ -48,13 +48,16 @@ func (gs *GState) UserDelete(c *fiber.Ctx) error { auth_username := c.Locals("user").(*jwt.Token).Claims.(jwt.MapClaims)["name"].(string) if username != auth_username { + log.Info("User tried to delete another user") return c.Status(403).SendString("You can only delete yourself") } if err := gs.Db.RemoveUser(username); err != nil { + log.Warn("Error deleting user:", err) return c.Status(500).SendString(err.Error()) } + log.Info("User deleted:", username) return c.Status(200).SendString("User deleted") } @@ -67,7 +70,7 @@ func (gs *GState) Login(c *fiber.Ctx) error { return c.Status(400).SendString(err.Error()) } - log.Info("Username:", u.Username) + log.Info("Username logging in:", u.Username) if !gs.Db.CheckUser(u.Username, u.Password) { log.Info("User not found") return c.SendStatus(fiber.StatusUnauthorized) @@ -97,8 +100,10 @@ func (gs *GState) Login(c *fiber.Ctx) error { // LoginRenew is a simple handler that renews the token func (gs *GState) LoginRenew(c *fiber.Ctx) error { - // For testing: curl localhost:3000/restricted -H "Authorization: Bearer " user := c.Locals("user").(*jwt.Token) + + log.Info("Renewing token for user:", user.Claims.(jwt.MapClaims)["name"]) + claims := user.Claims.(jwt.MapClaims) claims["exp"] = time.Now().Add(time.Hour * 72).Unix() renewed := jwt.MapClaims{ @@ -109,8 +114,11 @@ func (gs *GState) LoginRenew(c *fiber.Ctx) error { token := jwt.NewWithClaims(jwt.SigningMethodHS256, renewed) t, err := token.SignedString([]byte("secret")) if err != nil { + log.Warn("Error signing token") return c.SendStatus(fiber.StatusInternalServerError) } + + log.Info("Successfully renewed token for user:", user.Claims.(jwt.MapClaims)["name"]) return c.JSON(fiber.Map{"token": t}) } @@ -119,9 +127,11 @@ func (gs *GState) ListAllUsers(c *fiber.Ctx) error { // Get all users from the database users, err := gs.Db.GetAllUsersApplication() if err != nil { + log.Info("Error getting users from db:", err) // Debug print return c.Status(500).SendString(err.Error()) } + log.Info("Returning all users") // Return the list of users as JSON return c.JSON(users) }