|
| 1 | +package jwt |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/gin-gonic/gin" |
| 5 | + "github.com/go-playground/assert/v2" |
| 6 | + "io/ioutil" |
| 7 | + "net/http" |
| 8 | + "net/http/httptest" |
| 9 | + "testing" |
| 10 | +) |
| 11 | + |
| 12 | +func TestVerifyEmptyToken(t *testing.T) { |
| 13 | + res := httptest.NewRecorder() |
| 14 | + c, _ := gin.CreateTestContext(res) |
| 15 | + |
| 16 | + c.Request, _ = http.NewRequest("GET", "/", nil) |
| 17 | + |
| 18 | + Verify(c) |
| 19 | + |
| 20 | + assert.Equal(t, res.Code, http.StatusUnauthorized) |
| 21 | +} |
| 22 | + |
| 23 | +func TestVerifyInvalidToken(t *testing.T) { |
| 24 | + pemBytes, err := ioutil.ReadFile("private.key") |
| 25 | + if err != nil { |
| 26 | + panic(err) |
| 27 | + } |
| 28 | + |
| 29 | + if err := SetUp(pemBytes, Option{}); err != nil { |
| 30 | + panic(err) |
| 31 | + } |
| 32 | + |
| 33 | + res := httptest.NewRecorder() |
| 34 | + c, _ := gin.CreateTestContext(res) |
| 35 | + |
| 36 | + c.Request, _ = http.NewRequest("GET", "/", nil) |
| 37 | + c.Request.Header.Add("Authorization", "test") |
| 38 | + |
| 39 | + Verify(c) |
| 40 | + |
| 41 | + assert.Equal(t, res.Code, http.StatusUnauthorized) |
| 42 | +} |
| 43 | + |
| 44 | +func TestVerifyValidToken(t *testing.T) { |
| 45 | + pemBytes, err := ioutil.ReadFile("private.key") |
| 46 | + if err != nil { |
| 47 | + panic(err) |
| 48 | + } |
| 49 | + |
| 50 | + if err := SetUp(pemBytes, Option{}); err != nil { |
| 51 | + panic(err) |
| 52 | + } |
| 53 | + |
| 54 | + res := httptest.NewRecorder() |
| 55 | + c, _ := gin.CreateTestContext(res) |
| 56 | + |
| 57 | + c.Request, _ = http.NewRequest("GET", "/", nil) |
| 58 | + |
| 59 | + token, err := GetToken(map[string]interface{}{}) |
| 60 | + |
| 61 | + c.Request.Header.Add("Authorization", "bearer "+string(token)) |
| 62 | + |
| 63 | + Verify(c) |
| 64 | + |
| 65 | + assert.Equal(t, res.Code, http.StatusOK) |
| 66 | +} |
0 commit comments