Skip to content

Commit

Permalink
chore(BUX-223): replace current router with gin
Browse files Browse the repository at this point in the history
  • Loading branch information
pawellewandowski98 committed Feb 22, 2024
1 parent 37dda37 commit 7a262c9
Show file tree
Hide file tree
Showing 82 changed files with 1,703 additions and 1,705 deletions.
2 changes: 0 additions & 2 deletions actions/access_keys/access_keys.go

This file was deleted.

8 changes: 5 additions & 3 deletions actions/access_keys/access_keys_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package accesskeys

import (
"github.com/bitcoin-sv/spv-wallet/config"
"github.com/gin-gonic/gin"
"testing"

"github.com/bitcoin-sv/spv-wallet/tests"
apirouter "github.com/mrz1836/go-api-router"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)
Expand All @@ -29,9 +30,10 @@ func (ts *TestSuite) SetupTest() {
ts.BaseSetupTest()

// Load the router & register routes
ts.Router = apirouter.New()
ts.Router = gin.Default()
require.NotNil(ts.T(), ts.Router)
RegisterRoutes(ts.Router, ts.AppConfig, ts.Services)
routes := NewHandler(ts.AppConfig, ts.Services)
routes.RegisterApiEndpoints(ts.Router.Group("/" + config.APIVersion))
}

// TearDownTest runs after each test
Expand Down
25 changes: 9 additions & 16 deletions actions/access_keys/count.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package accesskeys

import (
"github.com/bitcoin-sv/spv-wallet/server/auth"
"github.com/gin-gonic/gin"
"net/http"

"github.com/bitcoin-sv/spv-wallet/actions"
"github.com/bitcoin-sv/spv-wallet/engine"
"github.com/bitcoin-sv/spv-wallet/mappings"
"github.com/julienschmidt/httprouter"
apirouter "github.com/mrz1836/go-api-router"
)

// count will fetch a count of access keys filtered by metadata
Expand All @@ -21,30 +19,25 @@ import (
// @Success 200
// @Router /v1/access-key/count [post]
// @Security x-auth-xpub
func (a *Action) count(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
reqXPubID, _ := engine.GetXpubIDFromRequest(req)
func (a *Action) count(c *gin.Context) {
reqXPubID := c.GetString(auth.ParamXPubHashKey)

// Parse the params
params := apirouter.GetParams(req)
_, metadataModel, conditions, err := actions.GetQueryParameters(params)
metadata := mappings.MapToSpvWalletMetadata(metadataModel)
_, metadata, conditions, err := actions.GetQueryParameters(c)
if err != nil {
apirouter.ReturnResponse(w, req, http.StatusExpectationFailed, err.Error())
c.JSON(http.StatusExpectationFailed, err.Error())
return
}

// Record a new transaction (get the hex from parameters)a
var count int64
if count, err = a.Services.SpvWalletEngine.GetAccessKeysByXPubIDCount(
req.Context(),
c.Request.Context(),
reqXPubID,
metadata,
conditions,
); err != nil {
apirouter.ReturnResponse(w, req, http.StatusExpectationFailed, err.Error())
c.JSON(http.StatusExpectationFailed, err.Error())
return
}

// Return response
apirouter.ReturnResponse(w, req, http.StatusOK, count)
c.JSON(http.StatusOK, count)
}
28 changes: 13 additions & 15 deletions actions/access_keys/create.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package accesskeys

import (
"github.com/bitcoin-sv/spv-wallet/server/auth"
"github.com/gin-gonic/gin"
"net/http"

"github.com/bitcoin-sv/spv-wallet/engine"
"github.com/bitcoin-sv/spv-wallet/mappings"
"github.com/julienschmidt/httprouter"
apirouter "github.com/mrz1836/go-api-router"
)

// create will make a new model using the services defined in the action object
Expand All @@ -19,28 +19,26 @@ import (
// @Success 201
// @Router /v1/access-key [post]
// @Security x-auth-xpub
func (a *Action) create(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
reqXPub, _ := engine.GetXpubFromRequest(req)
func (a *Action) create(c *gin.Context) {
reqXPub := c.GetString(auth.ParamXPubKey)

// Parse the params
params := apirouter.GetParams(req)

// params
metadata := params.GetJSON("metadata")
var requestBody CreateAccessKey
if err := c.Bind(&requestBody); err != nil {
c.JSON(http.StatusBadRequest, err.Error())
return
}

// Create a new accessKey
accessKey, err := a.Services.SpvWalletEngine.NewAccessKey(
req.Context(),
c.Request.Context(),
reqXPub,
engine.WithMetadatas(metadata),
engine.WithMetadatas(requestBody.Metadata),
)
if err != nil {
apirouter.ReturnResponse(w, req, http.StatusUnprocessableEntity, err.Error())
c.JSON(http.StatusUnprocessableEntity, err.Error())
return
}

contract := mappings.MapToAccessKeyContract(accessKey)

// Return response
apirouter.ReturnResponse(w, req, http.StatusCreated, contract)
c.JSON(http.StatusCreated, contract)
}
27 changes: 11 additions & 16 deletions actions/access_keys/get.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package accesskeys

import (
"github.com/bitcoin-sv/spv-wallet/engine"
"github.com/bitcoin-sv/spv-wallet/server/auth"
"github.com/gin-gonic/gin"
"net/http"

"github.com/bitcoin-sv/spv-wallet/engine"
"github.com/bitcoin-sv/spv-wallet/mappings"
"github.com/julienschmidt/httprouter"
apirouter "github.com/mrz1836/go-api-router"
)

// get will get an existing model
Expand All @@ -19,34 +19,29 @@ import (
// @Success 200
// @Router /v1/access-key [get]
// @Security x-auth-xpub
func (a *Action) get(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
reqXPubID, _ := engine.GetXpubIDFromRequest(req)

// Parse the params
params := apirouter.GetParams(req)
id := params.GetString("id")
func (a *Action) get(c *gin.Context) {
reqXPubID := c.GetString(auth.ParamXPubHashKey)

id := c.Query("id")
if id == "" {
apirouter.ReturnResponse(w, req, http.StatusExpectationFailed, engine.ErrMissingFieldID)
c.JSON(http.StatusBadRequest, engine.ErrMissingFieldID)
return
}

// Get access key
accessKey, err := a.Services.SpvWalletEngine.GetAccessKey(
req.Context(), reqXPubID, id,
c.Request.Context(), reqXPubID, id,
)
if err != nil {
apirouter.ReturnResponse(w, req, http.StatusExpectationFailed, err.Error())
c.JSON(http.StatusUnprocessableEntity, err.Error())
return
}

if accessKey.XpubID != reqXPubID {
apirouter.ReturnResponse(w, req, http.StatusForbidden, "unauthorized")
c.JSON(http.StatusForbidden, "unauthorized")
return
}

contract := mappings.MapToAccessKeyContract(accessKey)

// Return response
apirouter.ReturnResponse(w, req, http.StatusOK, contract)
c.JSON(http.StatusOK, contract)
}
7 changes: 7 additions & 0 deletions actions/access_keys/models.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package accesskeys

import "github.com/bitcoin-sv/spv-wallet/engine"

type CreateAccessKey struct {
Metadata engine.Metadata `json:"metadata"`
}
24 changes: 9 additions & 15 deletions actions/access_keys/revoke.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package accesskeys

import (
"github.com/bitcoin-sv/spv-wallet/server/auth"
"github.com/gin-gonic/gin"
"net/http"

"github.com/bitcoin-sv/spv-wallet/engine"
"github.com/bitcoin-sv/spv-wallet/mappings"
"github.com/julienschmidt/httprouter"
apirouter "github.com/mrz1836/go-api-router"
)

// revoke will revoke the intended model by id
Expand All @@ -19,31 +19,25 @@ import (
// @Success 201
// @Router /v1/access-key [delete]
// @Security x-auth-xpub
func (a *Action) revoke(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
reqXPub, _ := engine.GetXpubFromRequest(req)

// Parse the params
params := apirouter.GetParams(req)
id := params.GetString("id")
func (a *Action) revoke(c *gin.Context) {
reqXPub := c.GetString(auth.ParamXPubKey)

id := c.Query("id")
if id == "" {
apirouter.ReturnResponse(w, req, http.StatusExpectationFailed, engine.ErrMissingFieldID)
c.JSON(http.StatusBadRequest, engine.ErrMissingFieldID)
return
}

// Create a new accessKey
accessKey, err := a.Services.SpvWalletEngine.RevokeAccessKey(
req.Context(),
c.Request.Context(),
reqXPub,
id,
)
if err != nil {
apirouter.ReturnResponse(w, req, http.StatusUnprocessableEntity, err.Error())
c.JSON(http.StatusUnprocessableEntity, err.Error())
return
}

contract := mappings.MapToAccessKeyContract(accessKey)

// Return response
apirouter.ReturnResponse(w, req, http.StatusCreated, contract)
c.JSON(http.StatusCreated, contract)
}
32 changes: 15 additions & 17 deletions actions/access_keys/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,28 @@ package accesskeys
import (
"github.com/bitcoin-sv/spv-wallet/actions"
"github.com/bitcoin-sv/spv-wallet/config"
apirouter "github.com/mrz1836/go-api-router"
"github.com/bitcoin-sv/spv-wallet/server/routes"
"github.com/gin-gonic/gin"
)

// Action is an extension of actions.Action for this package
type Action struct {
actions.Action
}

// RegisterRoutes register all the package specific routes
func RegisterRoutes(router *apirouter.Router, appConfig *config.AppConfig, services *config.AppServices) {
// NewHandler creates the specific package routes
func NewHandler(appConfig *config.AppConfig, services *config.AppServices) routes.ApiEndpointsFunc {
action := &Action{actions.Action{AppConfig: appConfig, Services: services}}

// Use the authentication middleware wrapper - this will only check for a valid xPub
a, require := actions.NewStack(appConfig, services)
require.Use(a.RequireAuthentication)

// Load the actions and set the services
action := &Action{actions.Action{AppConfig: a.AppConfig, Services: a.Services}}

// V1 Requests
router.HTTPRouter.GET("/"+config.APIVersion+"/access-key", action.Request(router, require.Wrap(action.get)))
router.HTTPRouter.POST("/"+config.APIVersion+"/access-key/count", action.Request(router, require.Wrap(action.count)))
router.HTTPRouter.GET("/"+config.APIVersion+"/access-key/search", action.Request(router, require.Wrap(action.search)))
router.HTTPRouter.POST("/"+config.APIVersion+"/access-key/search", action.Request(router, require.Wrap(action.search)))
router.HTTPRouter.POST("/"+config.APIVersion+"/access-key", action.Request(router, require.Wrap(action.create)))
router.HTTPRouter.DELETE("/"+config.APIVersion+"/access-key", action.Request(router, require.Wrap(action.revoke)))
apiEndpoints := routes.ApiEndpointsFunc(func(router *gin.RouterGroup) {
accessKeyGroup := router.Group("/access-key")
accessKeyGroup.POST("", action.create)
accessKeyGroup.GET("", action.get)
accessKeyGroup.DELETE("", action.revoke)
accessKeyGroup.POST("/count", action.count)
accessKeyGroup.GET("/search", action.search)
accessKeyGroup.POST("/search", action.search)
})

return apiEndpoints
}
47 changes: 25 additions & 22 deletions actions/access_keys/routes_test.go
Original file line number Diff line number Diff line change
@@ -1,35 +1,38 @@
package accesskeys

import (
"net/http"
"github.com/stretchr/testify/assert"
"testing"

"github.com/bitcoin-sv/spv-wallet/config"
"github.com/stretchr/testify/assert"
)

// TestBaseRegisterRoutes will test routes
func (ts *TestSuite) TestRegisterRoutes() {
ts.T().Run("test routes", func(t *testing.T) {

// gey key
handle, _, _ := ts.Router.HTTPRouter.Lookup(http.MethodGet, "/"+config.APIVersion+"/access-key")
assert.NotNil(t, handle)

// search key
handle, _, _ = ts.Router.HTTPRouter.Lookup(http.MethodGet, "/"+config.APIVersion+"/access-key/search")
assert.NotNil(t, handle)

// search key
handle, _, _ = ts.Router.HTTPRouter.Lookup(http.MethodPost, "/"+config.APIVersion+"/access-key/search")
assert.NotNil(t, handle)

// create key
handle, _, _ = ts.Router.HTTPRouter.Lookup(http.MethodPost, "/"+config.APIVersion+"/access-key")
assert.NotNil(t, handle)

// delete key
handle, _, _ = ts.Router.HTTPRouter.Lookup(http.MethodDelete, "/"+config.APIVersion+"/access-key")
assert.NotNil(t, handle)
testCases := []struct {
method string
url string
}{
{"GET", "/" + config.APIVersion + "/access-key"},
{"POST", "/" + config.APIVersion + "/access-key"},
{"DELETE", "/" + config.APIVersion + "/access-key"},
{"POST", "/" + config.APIVersion + "/access-key/search"},
{"GET", "/" + config.APIVersion + "/access-key/search"},
}

ts.Router.Routes()

for _, testCase := range testCases {
found := false
for _, routeInfo := range ts.Router.Routes() {
if testCase.url == routeInfo.Path && testCase.method == routeInfo.Method {
assert.NotNil(t, routeInfo.HandlerFunc)
found = true
break
}
}
assert.True(t, found)
}
})
}
Loading

0 comments on commit 7a262c9

Please sign in to comment.