diff --git a/backend/internal/database/db.go b/backend/internal/database/db.go index 99c63ab..f05530a 100644 --- a/backend/internal/database/db.go +++ b/backend/internal/database/db.go @@ -24,6 +24,7 @@ type Database interface { AddUserToProject(username string, projectname string, role string) error ChangeUserRole(username string, projectname string, role string) error GetAllUsersProject(projectname string) ([]UserProjectMember, error) + GetAllUsersApplication() ([]string, error) } // This struct is a wrapper type that holds the database connection @@ -175,6 +176,36 @@ func (d *Db) GetAllUsersProject(projectname string) ([]UserProjectMember, error) return users, nil } +// GetAllUsersApplication retrieves all usernames from the database +func (d *Db) GetAllUsersApplication() ([]string, error) { + // Define the SQL query to fetch all usernames + query := ` + SELECT username FROM users + ` + + // Execute the query + rows, err := d.Queryx(query) + if err != nil { + return nil, err + } + defer rows.Close() + + // Iterate over the rows and populate the result slice + var usernames []string + for rows.Next() { + var username string + if err := rows.Scan(&username); err != nil { + return nil, err + } + usernames = append(usernames, username) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return usernames, nil +} + // Reads a directory of migration files and applies them to the database. // This will eventually be used on an embedded directory func (d *Db) Migrate(dirname string) error { diff --git a/backend/internal/database/db_test.go b/backend/internal/database/db_test.go index fe6cc74..e5aceb2 100644 --- a/backend/internal/database/db_test.go +++ b/backend/internal/database/db_test.go @@ -240,3 +240,49 @@ func TestGetAllUsersProject(t *testing.T) { t.Error("User user not found") } } + +func TestGetAllUsersApplication(t *testing.T) { + db, err := setupState() + if err != nil { + t.Error("setupState failed:", err) + } + + err = db.AddUser("testuser1", "password") + if err != nil { + t.Error("AddUser failed:", err) + } + + err = db.AddUser("testuser2", "password") + if err != nil { + t.Error("AddUser failed:", err) + } + + users, err := db.GetAllUsersApplication() + if err != nil { + t.Error("GetAllUsersApplication failed:", err) + } + + // Check if both users are returned + if len(users) != 2 { + t.Errorf("Expected 2 users, got %d", len(users)) + } + + // Check if the test users are included in the list + foundTestUser1 := false + foundTestUser2 := false + for _, user := range users { + if user == "testuser1" { + foundTestUser1 = true + } + if user == "testuser2" { + foundTestUser2 = true + } + } + + if !foundTestUser1 { + t.Error("testuser1 not found") + } + if !foundTestUser2 { + t.Error("testuser2 not found") + } +}