Skip to content
Merged
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
14 changes: 12 additions & 2 deletions api/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ package api

import (
"database/sql"
"errors"
"net/http"

"github.com/gin-gonic/gin"
"github.com/lib/pq"
db "github.com/sinachaichi/gault/db/sqlc"
"github.com/sinachaichi/gault/token"
)


type createAccountRequest struct {
Owner string `json:"owner" binding:"required"`
Currency string `json:"currency" binding:"required,currency"`
}

Expand All @@ -31,8 +32,9 @@ func (server *Server) createAccount(ctx *gin.Context){
return
}

authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload)
arg := db.CreateAccountParams{
Owner: req.Owner,
Owner: authPayload.Username,
Currency: req.Currency,
Balance: 0,
}
Expand Down Expand Up @@ -72,6 +74,12 @@ func (server *Server) getAccount(ctx *gin.Context){
return
}

authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload)
if account.Owner != authPayload.Username {
err := errors.New("account doesn't belong to the authenticated user")
ctx.JSON(http.StatusUnauthorized, errorResponse(err))
return
}
ctx.JSON(http.StatusOK, account)
}

Expand All @@ -83,7 +91,9 @@ func (server *Server) listAccount(ctx *gin.Context) {
return
}

authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload)
arg := db.ListAccountsParams{
Owner: authPayload.Username,
Limit: req.PageSize,
Offset: (req.PageID - 1) * req.PageSize,
}
Expand Down
138 changes: 98 additions & 40 deletions api/account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,22 @@ import (
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/gin-gonic/gin"
"github.com/lib/pq"
mockdb "github.com/sinachaichi/gault/db/mock"
db "github.com/sinachaichi/gault/db/sqlc"
"github.com/sinachaichi/gault/token"
"github.com/sinachaichi/gault/util"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
)


func randomAccount() db.Account {
func randomAccount(owner string) db.Account {
return db.Account{
ID: util.RandomInt(1, 1000),
Owner: util.RandomOwner(),
Owner: owner,
Balance: util.RandomMoney(),
Currency: util.RandomCurrency(),
}
Expand All @@ -41,94 +42,89 @@ func requireBodyMatchAccount(t *testing.T, body *bytes.Buffer, account db.Accoun
}

func TestCreateAccountAPI(t *testing.T) {
account := randomAccount()
user, _ := randomUser(t)
account := randomAccount(user.Username)

testCases := []struct {
name string
body gin.H
setupAuth func(t *testing.T, request *http.Request, tokenMaker token.Maker)
buildStubs func(store *mockdb.MockStore)
checkResponse func(t *testing.T, recorder *httptest.ResponseRecorder)
checkResponse func(recoder *httptest.ResponseRecorder)
}{
{
name: "OK",
body: gin.H{
"owner": account.Owner,
"currency": account.Currency,
},
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
arg := db.CreateAccountParams{
Owner: account.Owner,
Currency: account.Currency,
Balance: 0,
}

store.EXPECT().
CreateAccount(gomock.Any(), gomock.Eq(arg)).
Times(1).
Return(account, nil)
},
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) {
checkResponse: func(recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusOK, recorder.Code)
requireBodyMatchAccount(t, recorder.Body, account)
},
},
{
name: "InternalError",
name: "NoAuthorization",
body: gin.H{
"owner": account.Owner,
"currency": account.Currency,
},
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
CreateAccount(gomock.Any(), gomock.Any()).
Times(1).
Return(db.Account{}, sql.ErrConnDone)
Times(0)
},
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusInternalServerError, recorder.Code)
checkResponse: func(recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusUnauthorized, recorder.Code)
},
},
{
name: "DuplicateOwnerCurrency",
name: "InternalError",
body: gin.H{
"owner": account.Owner,
"currency": account.Currency,
},
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
CreateAccount(gomock.Any(), gomock.Any()).
Times(1).
Return(db.Account{}, &pq.Error{Code: "23505"})
Return(db.Account{}, sql.ErrConnDone)
},
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusForbidden, recorder.Code)
checkResponse: func(recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusInternalServerError, recorder.Code)
},
},
{
name: "InvalidCurrency",
body: gin.H{
"owner": account.Owner,
"currency": "XYZ",
"currency": "invalid",
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
CreateAccount(gomock.Any(), gomock.Any()).
Times(0)
},
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusBadRequest, recorder.Code)
},
},
{
name: "MissingOwner",
body: gin.H{
"currency": account.Currency,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
CreateAccount(gomock.Any(), gomock.Any()).
Times(0)
},
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) {
checkResponse: func(recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusBadRequest, recorder.Code)
},
},
Expand All @@ -147,39 +143,47 @@ func TestCreateAccountAPI(t *testing.T) {
server := newTestServer(t, store)
recorder := httptest.NewRecorder()

// Marshal body data to JSON
data, err := json.Marshal(tc.body)
require.NoError(t, err)

request, err := http.NewRequest(http.MethodPost, "/accounts", bytes.NewReader(data))
url := "/accounts"
request, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
require.NoError(t, err)
request.Header.Set("Content-Type", "application/json")

tc.setupAuth(t, request, server.tokenMaker)
server.router.ServeHTTP(recorder, request)
tc.checkResponse(t, recorder)
tc.checkResponse(recorder)
})
}
}

func TestListAccountAPI(t *testing.T) {
user, _ := randomUser(t)
n := 5
accounts := make([]db.Account, n)
for i := 0; i < n; i++ {
accounts[i] = randomAccount()
accounts[i] = randomAccount(user.Username)
}

testCases := []struct {
name string
pageID int
pageSize int
setupAuth func(t *testing.T, request *http.Request, tokenMaker token.Maker)
buildStubs func(store *mockdb.MockStore)
checkResponse func(t *testing.T, recorder *httptest.ResponseRecorder)
}{
{
name: "OK",
pageID: 1,
pageSize: 5,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
arg := db.ListAccountsParams{
Owner: user.Username,
Limit: 5,
Offset: 0,
}
Expand All @@ -196,6 +200,9 @@ func TestListAccountAPI(t *testing.T) {
name: "InternalError",
pageID: 1,
pageSize: 5,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
ListAccounts(gomock.Any(), gomock.Any()).
Expand All @@ -210,6 +217,9 @@ func TestListAccountAPI(t *testing.T) {
name: "InvalidPageID",
pageID: 0,
pageSize: 5,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
ListAccounts(gomock.Any(), gomock.Any()).
Expand All @@ -223,6 +233,9 @@ func TestListAccountAPI(t *testing.T) {
name: "InvalidPageSize",
pageID: 1,
pageSize: 2,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
ListAccounts(gomock.Any(), gomock.Any()).
Expand Down Expand Up @@ -251,24 +264,30 @@ func TestListAccountAPI(t *testing.T) {
request, err := http.NewRequest(http.MethodGet, url, nil)
require.NoError(t, err)

tc.setupAuth(t, request, server.tokenMaker)
server.router.ServeHTTP(recorder, request)
tc.checkResponse(t, recorder)
})
}
}

func TestGetAccountAPI(t *testing.T) {
account := randomAccount()
user, _ := randomUser(t)
account := randomAccount(user.Username)

testCases := []struct {
name string
accountID int64
setupAuth func(t *testing.T, request *http.Request, tokenMaker token.Maker)
buildStubs func(store *mockdb.MockStore)
checkResponse func(t *testing.T, recoder *httptest.ResponseRecorder)
}{
{
name: "OK",
accountID: account.ID,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker){
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
GetAccount(gomock.Any(), gomock.Eq(account.ID)).
Expand All @@ -279,10 +298,42 @@ func TestGetAccountAPI(t *testing.T) {
require.Equal(t, http.StatusOK, recorder.Code)
requireBodyMatchAccount(t, recorder.Body, account)
},
},
{
name: "UnauthorizedUser",
accountID: account.ID,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker){
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, "unauthorized_user", time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
GetAccount(gomock.Any(), gomock.Eq(account.ID)).
Times(1).
Return(account, nil)
},
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusUnauthorized, recorder.Code)
},
},
{
name: "NoAuthorization",
accountID: account.ID,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker){},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
GetAccount(gomock.Any(), gomock.Any()).
Times(0)
},
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusUnauthorized, recorder.Code)
},
},
{
name: "NotFound",
accountID: account.ID,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker){
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
GetAccount(gomock.Any(), gomock.Eq(account.ID)).
Expand All @@ -296,6 +347,9 @@ func TestGetAccountAPI(t *testing.T) {
{
name: "InternalError",
accountID: account.ID,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker){
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
GetAccount(gomock.Any(), gomock.Eq(account.ID)).
Expand All @@ -309,6 +363,9 @@ func TestGetAccountAPI(t *testing.T) {
{
name: "InvalidID",
accountID: 0,
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker){
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
GetAccount(gomock.Any(), gomock.Any()).
Expand Down Expand Up @@ -336,7 +393,8 @@ func TestGetAccountAPI(t *testing.T) {
url := fmt.Sprintf("/accounts/%d", tc.accountID)
request, err := http.NewRequest(http.MethodGet, url, nil)
require.NoError(t, err)


tc.setupAuth(t, request, server.tokenMaker)
server.router.ServeHTTP(recorder, request)
tc.checkResponse(t, recorder)
})
Expand Down
Loading
Loading