-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add authorization logic for all api
- Loading branch information
1 parent
e3e94a0
commit b3bf75a
Showing
11 changed files
with
259 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
package api | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"github.com/cukhoaimon/SimpleBank/token" | ||
"github.com/gin-gonic/gin" | ||
"net/http" | ||
"strings" | ||
) | ||
|
||
const ( | ||
authorizationHeaderKey = "authorization" | ||
authorizationTypeBearer = "bearer" | ||
authorizationPayloadKey = "authorization_payload" | ||
) | ||
|
||
var ( | ||
errAuthHeaderNotProvided = errors.New("authorization header is not provided") | ||
errAuthHeaderInvalidFormat = errors.New("invalid authorization header format") | ||
) | ||
|
||
func authMiddleware(tokenMaker token.Maker) gin.HandlerFunc { | ||
return func(ctx *gin.Context) { | ||
authorizationHeader := ctx.GetHeader(authorizationHeaderKey) | ||
if len(authorizationHeader) == 0 { | ||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse(errAuthHeaderNotProvided)) | ||
return | ||
} | ||
|
||
fields := strings.Fields(authorizationHeader) | ||
if len(fields) < 2 { | ||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse(errAuthHeaderInvalidFormat)) | ||
return | ||
} | ||
|
||
authorizationType := strings.ToLower(fields[0]) | ||
if authorizationType != authorizationTypeBearer { | ||
err := fmt.Errorf("authorization type %s is not supported", authorizationType) | ||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse(err)) | ||
return | ||
} | ||
|
||
accessToken := fields[1] | ||
payload, err := tokenMaker.VerifyToken(accessToken) | ||
if err != nil { | ||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse(err)) | ||
return | ||
} | ||
|
||
ctx.Set(authorizationPayloadKey, payload) | ||
ctx.Next() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
package api | ||
|
||
import ( | ||
"fmt" | ||
"github.com/cukhoaimon/SimpleBank/token" | ||
"github.com/cukhoaimon/SimpleBank/utils" | ||
"github.com/gin-gonic/gin" | ||
"github.com/stretchr/testify/require" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
"time" | ||
) | ||
|
||
func addAuthorization( | ||
t *testing.T, | ||
request *http.Request, | ||
tokenMaker token.Maker, | ||
authorizationType string, | ||
username string, | ||
duration time.Duration, | ||
) { | ||
accessToken, err := tokenMaker.CreateToken(username, duration) | ||
require.Nil(t, err) | ||
require.NotEmpty(t, accessToken) | ||
|
||
authorizationHeader := fmt.Sprintf("%s %s", authorizationType, accessToken) | ||
request.Header.Set(authorizationHeaderKey, authorizationHeader) | ||
} | ||
|
||
func Test_authMiddleware(t *testing.T) { | ||
tests := []struct { | ||
name string | ||
setupAuth func(*testing.T, *http.Request, token.Maker) | ||
checkResponse func(*testing.T, *httptest.ResponseRecorder) | ||
}{ | ||
{ | ||
name: "200 OK", | ||
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) { | ||
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, "user", time.Minute) | ||
}, | ||
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { | ||
require.Equal(t, http.StatusOK, recorder.Code) | ||
}, | ||
}, | ||
{ | ||
name: "401 - Authorization not provide", | ||
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) | ||
}, | ||
}, | ||
{ | ||
name: "401 invalid authorization header format", | ||
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) { | ||
request.Header.Set("hehe", "hehe") | ||
}, | ||
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { | ||
require.Equal(t, http.StatusUnauthorized, recorder.Code) | ||
}, | ||
}, | ||
{ | ||
name: "401 unsupported authorization type ", | ||
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) { | ||
addAuthorization(t, request, tokenMaker, "sieu cap vo dich", "user", time.Minute) | ||
}, | ||
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { | ||
require.Equal(t, http.StatusUnauthorized, recorder.Code) | ||
}, | ||
}, | ||
{ | ||
name: "401 invalid token", | ||
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) { | ||
// provide JWT token, but server is using Paseto token => invalid token | ||
jwtMaker, err := token.NewJWTMaker(utils.RandomString(32)) | ||
require.Nil(t, err) | ||
addAuthorization(t, request, jwtMaker, authorizationTypeBearer, "user", time.Minute) | ||
}, | ||
checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { | ||
require.Equal(t, http.StatusUnauthorized, recorder.Code) | ||
}, | ||
}, | ||
} | ||
for _, tc := range tests { | ||
t.Run(tc.name, func(t *testing.T) { | ||
server := newTestServer(t, nil) | ||
authPath := "/auth" | ||
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.Nil(t, err) | ||
|
||
tc.setupAuth(t, request, server.tokenMaker) | ||
server.router.ServeHTTP(recorder, request) | ||
tc.checkResponse(t, recorder) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.