Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write Test For GetUserDropdownWorkspaces #1813

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions db/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ import (
"gorm.io/gorm"
)

type configHandler struct {
db Database
}

func NewConfigHandler(database Database) *configHandler {
return &configHandler{
db: database,
}
}

type database struct {
db *gorm.DB
getWorkspaceByUuid func(uuid string) Workspace
Expand Down Expand Up @@ -389,6 +399,17 @@ func (db database) UserHasAccess(pubKeyFromAuth string, uuid string, role string
return true
}

func (ch configHandler) UserHasAccess(pubKeyFromAuth string, uuid string, role string) bool {
org := ch.db.GetWorkspaceByUuid(uuid)
var hasRole bool = false
if pubKeyFromAuth != org.OwnerPubKey {
userRoles := ch.db.GetUserRoles(uuid, pubKeyFromAuth)
hasRole = RolesCheck(userRoles, role)
return hasRole
}
return true
}

func (db database) UserHasManageBountyRoles(pubKeyFromAuth string, uuid string) bool {
var manageRolesCount = len(ManageBountiesGroup)
org := db.getWorkspaceByUuid(uuid)
Expand Down
10 changes: 10 additions & 0 deletions db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -1394,6 +1394,16 @@ func (db database) GetPerson(id uint) Person {
return m
}

func (db database) DeleteWorkSpaceAllData() error {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Put these functions in the db/test_config.go file, since we only need them for tests.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tables := []string{"workspace_user_roles", "workspaces"}
for _, table := range tables {
if err := db.db.Exec("DELETE FROM " + table).Error; err != nil {
return err
}
}
return nil
}

func (db database) GetPersonByPubkey(pubkey string) Person {
m := Person{}
db.db.Where("owner_pub_key = ? AND (deleted = false OR deleted is null)", pubkey).Find(&m)
Expand Down
55 changes: 29 additions & 26 deletions handlers/workspaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,20 @@ type workspaceHandler struct {
generateBountyHandler func(bounties []db.NewBounty) []db.BountyResponse
getLightningInvoice func(payment_request string) (db.InvoiceResult, db.InvoiceError)
userHasAccess func(pubKeyFromAuth string, uuid string, role string) bool
configUserHasAccess func(pubKeyFromAuth string, uuid string, role string) bool
userHasManageBountyRoles func(pubKeyFromAuth string, uuid string) bool
}

func NewWorkspaceHandler(database db.Database) *workspaceHandler {
bHandler := NewBountyHandler(http.DefaultClient, database)
dbConf := db.NewDatabaseConfig(&gorm.DB{})
configHandler := db.NewConfigHandler(database)
return &workspaceHandler{
db: database,
generateBountyHandler: bHandler.GenerateBountyResponse,
getLightningInvoice: bHandler.GetLightningInvoice,
userHasAccess: dbConf.UserHasAccess,
configUserHasAccess: configHandler.UserHasAccess,
userHasManageBountyRoles: dbConf.UserHasManageBountyRoles,
}
}
Expand Down Expand Up @@ -454,7 +457,7 @@ func (oh *workspaceHandler) GetUserRoles(w http.ResponseWriter, r *http.Request)
json.NewEncoder(w).Encode(userRoles)
}

func GetUserWorkspaces(w http.ResponseWriter, r *http.Request) {
func (oh *workspaceHandler) GetUserWorkspaces(w http.ResponseWriter, r *http.Request) {
userIdParam := chi.URLParam(r, "userId")
userId, _ := utils.ConvertStringToUint(userIdParam)

Expand All @@ -464,9 +467,9 @@ func GetUserWorkspaces(w http.ResponseWriter, r *http.Request) {
return
}

user := db.DB.GetPerson(userId)
user := oh.db.GetPerson(userId)
// get the user workspaces
workspaces := GetAllUserWorkspaces(user.OwnerPubKey)
workspaces := oh.GetAllUserWorkspaces(user.OwnerPubKey)

w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(workspaces)
Expand All @@ -482,23 +485,23 @@ func (oh *workspaceHandler) GetUserDropdownWorkspaces(w http.ResponseWriter, r *
return
}

user := db.DB.GetPerson(userId)
user := oh.db.GetPerson(userId)

// get the workspaces created by the user, then get all the workspaces
// the user has been added to, loop through to get the workspace
workspaces := GetCreatedWorkspaces(user.OwnerPubKey)
assignedWorkspaces := db.DB.GetUserAssignedWorkspaces(user.OwnerPubKey)
workspaces := oh.GetCreatedWorkspaces(user.OwnerPubKey)
assignedWorkspaces := oh.db.GetUserAssignedWorkspaces(user.OwnerPubKey)
for _, value := range assignedWorkspaces {
uuid := value.WorkspaceUuid
workspace := db.DB.GetWorkspaceByUuid(uuid)
bountyCount := db.DB.GetWorkspaceBountyCount(uuid)
hasRole := db.UserHasAccess(user.OwnerPubKey, uuid, db.ViewReport)
workspace := oh.db.GetWorkspaceByUuid(uuid)
bountyCount := oh.db.GetWorkspaceBountyCount(uuid)
hasRole := oh.configUserHasAccess(user.OwnerPubKey, uuid, db.ViewReport)
hasBountyRoles := oh.userHasManageBountyRoles(user.OwnerPubKey, uuid)

// don't add deleted workspaces to the list
if !workspace.Deleted && hasBountyRoles {
if hasRole {
budget := db.DB.GetWorkspaceBudget(uuid)
budget := oh.db.GetWorkspaceBudget(uuid)
workspace.Budget = budget.TotalBudget
} else {
workspace.Budget = 0
Expand All @@ -512,16 +515,16 @@ func (oh *workspaceHandler) GetUserDropdownWorkspaces(w http.ResponseWriter, r *
json.NewEncoder(w).Encode(workspaces)
}

func GetCreatedWorkspaces(pubkey string) []db.Workspace {
workspaces := db.DB.GetUserCreatedWorkspaces(pubkey)
func (oh *workspaceHandler) GetCreatedWorkspaces(pubkey string) []db.Workspace {
workspaces := oh.db.GetUserCreatedWorkspaces(pubkey)
// add bounty count to the workspace
for index, value := range workspaces {
uuid := value.Uuid
bountyCount := db.DB.GetWorkspaceBountyCount(uuid)
hasRole := db.UserHasAccess(pubkey, uuid, db.ViewReport)
bountyCount := oh.db.GetWorkspaceBountyCount(uuid)
hasRole := oh.configUserHasAccess(pubkey, uuid, db.ViewReport)

if hasRole {
budget := db.DB.GetWorkspaceBudget(uuid)
budget := oh.db.GetWorkspaceBudget(uuid)
workspaces[index].Budget = budget.TotalBudget
} else {
workspaces[index].Budget = 0
Expand Down Expand Up @@ -687,7 +690,7 @@ func (oh *workspaceHandler) PollUserWorkspacesBudget(w http.ResponseWriter, r *h
}

// get the user workspaces
workspaces := GetAllUserWorkspaces(pubKeyFromAuth)
workspaces := oh.GetAllUserWorkspaces(pubKeyFromAuth)
// loop through the worksppaces and get each workspace invoice
for _, space := range workspaces {
// get all workspace invoice
Expand Down Expand Up @@ -737,7 +740,7 @@ func GetInvoicesCount(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(invoiceCount)
}

func GetAllUserInvoicesCount(w http.ResponseWriter, r *http.Request) {
func (oh *workspaceHandler) GetAllUserInvoicesCount(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string)

Expand All @@ -748,9 +751,9 @@ func GetAllUserInvoicesCount(w http.ResponseWriter, r *http.Request) {
}

allCount := int64(0)
workspaces := GetAllUserWorkspaces(pubKeyFromAuth)
workspaces := oh.GetAllUserWorkspaces(pubKeyFromAuth)
for _, space := range workspaces {
invoiceCount := db.DB.GetWorkspaceInvoicesCount(space.Uuid)
invoiceCount := oh.db.GetWorkspaceInvoicesCount(space.Uuid)
allCount += invoiceCount
}
w.WriteHeader(http.StatusOK)
Expand Down Expand Up @@ -995,20 +998,20 @@ func (oh *workspaceHandler) GetFeaturesByWorkspaceUuid(w http.ResponseWriter, r
json.NewEncoder(w).Encode(workspaceFeatures)
}

func GetAllUserWorkspaces(pubkey string) []db.Workspace {
func (oh *workspaceHandler) GetAllUserWorkspaces(pubkey string) []db.Workspace {
// get the workspaces created by the user, then get all the workspaces
// the user has been added to, loop through to get the workspace
workspaces := GetCreatedWorkspaces(pubkey)
assignedWorkspaces := db.DB.GetUserAssignedWorkspaces(pubkey)
workspaces := oh.GetCreatedWorkspaces(pubkey)
assignedWorkspaces := oh.db.GetUserAssignedWorkspaces(pubkey)
for _, value := range assignedWorkspaces {
uuid := value.WorkspaceUuid
workspace := db.DB.GetWorkspaceByUuid(uuid)
bountyCount := db.DB.GetWorkspaceBountyCount(uuid)
hasRole := db.UserHasAccess(pubkey, uuid, db.ViewReport)
workspace := oh.db.GetWorkspaceByUuid(uuid)
bountyCount := oh.db.GetWorkspaceBountyCount(uuid)
hasRole := oh.configUserHasAccess(pubkey, uuid, db.ViewReport)
// don't add deleted workspaces to the list
if !workspace.Deleted {
if hasRole {
budget := db.DB.GetWorkspaceBudget(uuid)
budget := oh.db.GetWorkspaceBudget(uuid)
workspace.Budget = budget.TotalBudget
} else {
workspace.Budget = 0
Expand Down
77 changes: 77 additions & 0 deletions handlers/workspaces_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"math/rand"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -1200,7 +1201,83 @@ func TestGetWorkspaceUsers(t *testing.T) {
}

func TestGetUserDropdownWorkspaces(t *testing.T) {
teardownSuite := SetupSuite(t)
defer teardownSuite(t)

db.TestDB.DeleteWorkSpaceAllData()

oHandler := NewWorkspaceHandler(db.TestDB)

person := db.Person{
Uuid: uuid.New().String(),
OwnerAlias: "test-alias",
UniqueName: "test-unique-name",
OwnerPubKey: "test-pubkey",
PriceToMeet: 0,
Description: "test-description",
}
person2 := db.Person{
Uuid: uuid.New().String(),
OwnerAlias: "test-alias2",
UniqueName: "test-unique-name2",
OwnerPubKey: "test-pubkey2",
PriceToMeet: 0,
Description: "test-description2",
}
db.TestDB.CreateOrEditPerson(person)
db.TestDB.CreateOrEditPerson(person2)

workspace := db.Workspace{
Uuid: uuid.New().String(),
Name: "test-workspace" + uuid.New().String(),
OwnerPubKey: person2.OwnerPubKey,
Github: "https://github.com/test",
Website: "https://www.testwebsite.com",
Description: "test-description",
}
db.TestDB.CreateOrEditWorkspace(workspace)
workspace = db.TestDB.GetWorkspaceByUuid(workspace.Uuid)
ctx := context.WithValue(context.Background(), auth.ContextKey, workspace.OwnerPubKey)

roles := []db.WorkspaceUserRoles{
{WorkspaceUuid: workspace.Uuid, OwnerPubKey: person2.OwnerPubKey, Role: "ADD BOUNTY"},
{WorkspaceUuid: workspace.Uuid, OwnerPubKey: person2.OwnerPubKey, Role: "UPDATE BOUNTY"},
{WorkspaceUuid: workspace.Uuid, OwnerPubKey: person2.OwnerPubKey, Role: "DELETE BOUNTY"},
{WorkspaceUuid: workspace.Uuid, OwnerPubKey: person2.OwnerPubKey, Role: "PAY BOUNTY"},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a "VIEW REPORT" role to the user, which will make the user have 5 roles, it will fix the userHasAccess error.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@elraphty I have try but i got same error:
image

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dropped a comment

{WorkspaceUuid: workspace.Uuid, OwnerPubKey: person2.OwnerPubKey, Role: "VIEW REPORT"},
}
db.TestDB.CreateUserRoles(roles, workspace.Uuid, person2.OwnerPubKey)

dbPerson := db.TestDB.GetPersonByUuid(person2.Uuid)

t.Run("should return user dropdown workspaces", func(t *testing.T) {
rr := httptest.NewRecorder()
rctx := chi.NewRouteContext()
rctx.URLParams.Add("userId", strconv.Itoa(int(dbPerson.ID)))
req, err := http.NewRequestWithContext(context.WithValue(ctx, chi.RouteCtxKey, rctx), http.MethodGet, "/user/dropdown/"+strconv.Itoa(int(dbPerson.ID)), nil)
if err != nil {
t.Fatal(err)
}

handler := http.HandlerFunc(oHandler.GetUserDropdownWorkspaces)
handler.ServeHTTP(rr, req)

assert.Equal(t, http.StatusOK, rr.Code)

var responseWorkspaces []db.Workspace
err = json.Unmarshal(rr.Body.Bytes(), &responseWorkspaces)
if err != nil {
t.Fatal(err)
}

assert.NotEmpty(t, responseWorkspaces)
assert.Equal(t, workspace.Uuid, responseWorkspaces[0].Uuid)
assert.Equal(t, workspace.Name, responseWorkspaces[0].Name)
assert.Equal(t, workspace.OwnerPubKey, responseWorkspaces[0].OwnerPubKey)
assert.Equal(t, workspace.Github, responseWorkspaces[0].Github)
assert.Equal(t, workspace.Website, responseWorkspaces[0].Website)
assert.Equal(t, workspace.Description, responseWorkspaces[0].Description)
})
}

func TestCreateOrEditWorkspaceRepository(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions routes/workspaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func WorkspaceRoutes() chi.Router {
r.Get("/users/{uuid}/count", handlers.GetWorkspaceUsersCount)
r.Get("/bounties/{uuid}", workspaceHandlers.GetWorkspaceBounties)
r.Get("/bounties/{uuid}/count", workspaceHandlers.GetWorkspaceBountiesCount)
r.Get("/user/{userId}", handlers.GetUserWorkspaces)
r.Get("/user/{userId}", workspaceHandlers.GetUserWorkspaces)
r.Get("/user/dropdown/{userId}", workspaceHandlers.GetUserDropdownWorkspaces)
})
r.Group(func(r chi.Router) {
Expand All @@ -38,7 +38,7 @@ func WorkspaceRoutes() chi.Router {
r.Get("/poll/invoices/{uuid}", workspaceHandlers.PollBudgetInvoices)
r.Get("/poll/user/invoices", workspaceHandlers.PollUserWorkspacesBudget)
r.Get("/invoices/count/{uuid}", handlers.GetInvoicesCount)
r.Get("/user/invoices/count", handlers.GetAllUserInvoicesCount)
r.Get("/user/invoices/count", workspaceHandlers.GetAllUserInvoicesCount)
r.Delete("/delete/{uuid}", workspaceHandlers.DeleteWorkspace)

r.Post("/mission", workspaceHandlers.UpdateWorkspace)
Expand Down
Loading