2023-03-15 15:00:36 +07:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"git.nochill.in/nochill/naice_pos/token"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
|
|
|
func addAuthorization(
|
|
|
|
t *testing.T,
|
|
|
|
request *http.Request,
|
|
|
|
tokenMaker token.Maker,
|
|
|
|
authorizationType string,
|
|
|
|
email string,
|
|
|
|
merchantID string,
|
|
|
|
duration time.Duration,
|
|
|
|
) {
|
2023-03-16 12:21:41 +07:00
|
|
|
token, payload, err := tokenMaker.CreateToken(email, merchantID, duration)
|
2023-03-15 15:00:36 +07:00
|
|
|
require.NoError(t, err)
|
|
|
|
require.NotEmpty(t, token)
|
2023-03-16 12:21:41 +07:00
|
|
|
require.NotEmpty(t, payload)
|
2023-03-15 15:00:36 +07:00
|
|
|
|
|
|
|
authorizationHeader := fmt.Sprintf("%s %s", authorizationType, token)
|
|
|
|
request.Header.Set(authorizationHeaderKey, authorizationHeader)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestAuthMiddleware(t *testing.T) {
|
|
|
|
testCases := []struct {
|
|
|
|
name string
|
|
|
|
setupAuth func(t *testing.T, request *http.Request, tokenMaker token.Maker)
|
|
|
|
checkResponse func(t *testing.T, recorder *httptest.ResponseRecorder)
|
|
|
|
}{
|
|
|
|
{
|
|
|
|
name: "OK",
|
|
|
|
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
|
|
|
|
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, "email", uuid.New().String(), time.Minute)
|
|
|
|
},
|
|
|
|
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) {
|
|
|
|
require.Equal(t, http.StatusOK, recorder.Code)
|
|
|
|
},
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "NoAuthorization",
|
|
|
|
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {},
|
|
|
|
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) {
|
|
|
|
require.Equal(t, http.StatusUnauthorized, recorder.Code)
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := range testCases {
|
|
|
|
tc := testCases[i]
|
|
|
|
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
|
|
server := newTestServer(t, nil)
|
|
|
|
authPath := "/user/login"
|
|
|
|
server.router.GET(
|
|
|
|
authPath,
|
|
|
|
authMiddleware(server.tokenMaker),
|
|
|
|
func(ctx *gin.Context) {
|
|
|
|
ctx.JSON(http.StatusOK, gin.H{})
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
recorder := httptest.NewRecorder()
|
|
|
|
request, err := http.NewRequest(http.MethodGet, authPath, nil)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
tc.setupAuth(t, request, server.tokenMaker)
|
|
|
|
server.router.ServeHTTP(recorder, request)
|
|
|
|
tc.checkResponse(t, recorder)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|