Skip to content

Commit

Permalink
Merge pull request #2 from tgunsch/jwt-handler
Browse files Browse the repository at this point in the history
Jwt handler
  • Loading branch information
tgunsch authored Apr 24, 2021
2 parents 985ae19 + cdb88bc commit 604ca4b
Show file tree
Hide file tree
Showing 11 changed files with 239 additions and 49 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
- name: Set up Go 1.x
uses: actions/setup-go@v2
with:
go-version: ^1.13
go-version: ^1.16

- name: Check out code into the Go module directory
uses: actions/checkout@v2
Expand Down
3 changes: 3 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/tgunsch/httpod/internal/cookies"
"github.com/tgunsch/httpod/internal/docs"
"github.com/tgunsch/httpod/internal/http"
"github.com/tgunsch/httpod/internal/jwt"
"github.com/tgunsch/httpod/internal/status"
"github.com/tgunsch/httpod/internal/util"
"html"
Expand Down Expand Up @@ -69,6 +70,8 @@ func main() {
api.POST("/cookies/:cookieName", cookies.PostHandler)
api.DELETE("/cookies/:cookieName", cookies.DeleteHandler)

api.GET("/jwt", jwt.GetHandler)

println(banner("http://localhost:" + port + SWAGGER_PATH + "/index.html"))
server.Logger.Fatal(server.Start(":" + port))
}
Expand Down
18 changes: 12 additions & 6 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
module github.com/tgunsch/httpod

go 1.15
go 1.16

require (
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751
github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect
github.com/go-openapi/spec v0.20.2 // indirect
github.com/labstack/echo/v4 v4.1.17
github.com/go-openapi/spec v0.20.3 // indirect
github.com/go-openapi/swag v0.19.15 // indirect
github.com/goccy/go-json v0.4.13 // indirect
github.com/labstack/echo/v4 v4.2.2
github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect
github.com/lestrrat-go/jwx v1.1.7
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.8 // indirect
github.com/nxadm/tail v1.4.6 // indirect
github.com/onsi/ginkgo v1.14.2
github.com/onsi/gomega v1.10.1
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/swaggo/echo-swagger v1.1.0
github.com/swaggo/swag v1.7.0
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c // indirect
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b // indirect
golang.org/x/net v0.0.0-20210423184538-5f58ad60dda6 // indirect
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7 // indirect
golang.org/x/tools v0.1.0 // indirect
)
99 changes: 59 additions & 40 deletions go.sum

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions internal/cookies/post_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var _ = Describe("PostHandler", func() {

// response has set-cookie
setCookieHeader := responseRecorder.Result().Header["Set-Cookie"][0]
Expect(setCookieHeader).Should(Equal("testCookie=testValue; Domain=myapp.com; SameSite"))
Expect(setCookieHeader).Should(Equal("testCookie=testValue; Domain=myapp.com"))

// response body contains json cookie
Expect(responseRecorder.Body.String()).To(MatchJSON(`{ "name": "testCookie", "value": "testValue", "domain": "myapp.com" }`))
Expand Down Expand Up @@ -83,7 +83,7 @@ var _ = Describe("PostHandler", func() {

// response has set-cookie
setCookieHeader := responseRecorder.Result().Header["Set-Cookie"][0]
Expect(setCookieHeader).Should(Equal("testCookie=testValue; Domain=myapp.com; Max-Age=1; SameSite"))
Expect(setCookieHeader).Should(Equal("testCookie=testValue; Domain=myapp.com; Max-Age=1"))
// response body contains json cookie
Expect(responseRecorder.Body.String()).To(MatchJSON(`{
"name": "testCookie",
Expand Down
26 changes: 26 additions & 0 deletions internal/docs/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,32 @@ var doc = `{
}
}
},
"/jwt": {
"get": {
"description": "Requests using GET should only retrieve data.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"JWT"
],
"summary": "Get jwt of the request.",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/cookies.GetCookies"
}
}
}
}
}
},
"/patch": {
"patch": {
"description": "The PATCH method is used to apply partial modifications to a resource.",
Expand Down
26 changes: 26 additions & 0 deletions internal/docs/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,32 @@
}
}
},
"/jwt": {
"get": {
"description": "Requests using GET should only retrieve data.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"JWT"
],
"summary": "Get jwt of the request.",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/cookies.GetCookies"
}
}
}
}
}
},
"/patch": {
"patch": {
"description": "The PATCH method is used to apply partial modifications to a resource.",
Expand Down
17 changes: 17 additions & 0 deletions internal/docs/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,23 @@ paths:
summary: Do a GET request.
tags:
- HTTP Methods
/jwt:
get:
consumes:
- application/json
description: Requests using GET should only retrieve data.
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/cookies.GetCookies'
type: array
summary: Get jwt of the request.
tags:
- JWT
/patch:
patch:
consumes:
Expand Down
42 changes: 42 additions & 0 deletions internal/jwt/get_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package jwt_test

import (
"fmt"
"github.com/labstack/echo/v4"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/tgunsch/httpod/internal/jwt"
"net/http"
"net/http/httptest"
)

var _ = Describe("GetHandler", func() {
It("return a jwt", func() {

ctx, _, responseRecorder := mockGetContext("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c")

err := jwt.GetHandler(ctx)
Expect(err).Should(BeNil())

// return 200
Expect(responseRecorder.Code).Should(Equal(200))

// response body contains json cookie
Expect(responseRecorder.Body.String()).To(MatchJSON(`{
"iat": 1516239022,
"name": "John Doe",
"sub": "1234567890"
}`))
})

})

func mockGetContext(token string) (echo.Context, *http.Request, *httptest.ResponseRecorder) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "http://myapp.com/api/jwt", nil)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %s", token))
res := httptest.NewRecorder()
c := e.NewContext(req, res)
return c, req, res
}
38 changes: 38 additions & 0 deletions internal/jwt/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package jwt

import (
"encoding/json"
"fmt"
"github.com/labstack/echo/v4"
"github.com/lestrrat-go/jwx/jwt"
"net/http"
"strings"
)

// @Summary Get jwt passed as authorization bearer token of the request.
// @Tags JWT
// @Description Requests using GET should only retrieve data.
// @Accept json
// @Produce json
// @Success 200 {array} jwt.Token
// @Router /jwt [get]
func GetHandler(context echo.Context) error {

auth := context.Request().Header.Get(echo.HeaderAuthorization)
l := len("Bearer")
if auth[:l] == "Bearer" {
rawToken := auth[l+1:]
token, err := jwt.ParseReader(strings.NewReader(rawToken))
if err != nil {
return context.String(http.StatusBadRequest, fmt.Sprintf("failed to parse payload: %s\n", err))
}

prettyJSON, err := json.MarshalIndent(token, "", " ")
if err != nil {
return context.String(http.StatusBadRequest, fmt.Sprintf("Error parsing cookies: %v", err.Error()))
}
return context.String(http.StatusOK, string(prettyJSON))
}
return context.String(http.StatusBadRequest, "No JWT in request header")

}
13 changes: 13 additions & 0 deletions internal/jwt/jwt_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package jwt_test

import (
"testing"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)

func TestJWT(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "JWT Suite")
}

0 comments on commit 604ca4b

Please sign in to comment.