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

chore(BUX-223): replace current router with gin #468

Merged
merged 18 commits into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
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
Expand Up @@ -3,8 +3,9 @@ package accesskeys
import (
"testing"

"github.com/bitcoin-sv/spv-wallet/config"
"github.com/bitcoin-sv/spv-wallet/tests"
apirouter "github.com/mrz1836/go-api-router"
"github.com/gin-gonic/gin"
"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
Expand Up @@ -4,10 +4,8 @@ import (
"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"
"github.com/bitcoin-sv/spv-wallet/server/auth"
"github.com/gin-gonic/gin"
)

// 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
Expand Up @@ -5,8 +5,8 @@ import (

"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"
"github.com/bitcoin-sv/spv-wallet/server/auth"
"github.com/gin-gonic/gin"
)

// 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)
}
25 changes: 10 additions & 15 deletions actions/access_keys/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (

"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"
"github.com/bitcoin-sv/spv-wallet/server/auth"
"github.com/gin-gonic/gin"
)

// 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)
}
8 changes: 8 additions & 0 deletions actions/access_keys/models.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package accesskeys

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

// CreateAccessKey is the model for creating an access key
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
Expand Up @@ -5,8 +5,8 @@ import (

"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"
"github.com/bitcoin-sv/spv-wallet/server/auth"
"github.com/gin-gonic/gin"
)

// 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
}
45 changes: 24 additions & 21 deletions actions/access_keys/routes_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package accesskeys

import (
"net/http"
"testing"

"github.com/bitcoin-sv/spv-wallet/config"
Expand All @@ -11,25 +10,29 @@ import (
// 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
Loading