Skip to content

Commit

Permalink
Merge pull request #8 from jtrw/develop
Browse files Browse the repository at this point in the history
Refactor authentication function to handle JWT tokens
  • Loading branch information
nilBora committed Aug 15, 2023
2 parents 6c587f8 + e7d702d commit af5ea26
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 52 deletions.
2 changes: 1 addition & 1 deletion auth_header_jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require"
)

func TestHeaderTokenAuth(t *testing.T) {
func TestHeaderJwtTokenAuth(t *testing.T) {
jwtToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.WKQfGgHiRhXdkdz6Qy90gMQhYf3uK-GMeyAQBEs1EbQ"
jwtFail := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.1F5StBaWKNe53iB2919Agg3nMcCdwINDWlT0sNBaMbE"

Expand Down
51 changes: 0 additions & 51 deletions auth_header_token.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
package rest

import (
"fmt"
"net/http"
"github.com/golang-jwt/jwt"
)

const TOKEN_NAME = "Api-Token"

func Authentication(headerName, token string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -20,50 +16,3 @@ func Authentication(headerName, token string) func(http.Handler) http.Handler {
return http.HandlerFunc(fn)
}
}

func AuthenticationJwt(secret string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.Header[TOKEN_NAME] == nil {
w.Write([]byte("Can not find token in header"));
w.WriteHeader(http.StatusUnauthorized)
return
}

token, _ := jwt.Parse(r.Header[TOKEN_NAME][0], func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("[ERROR] There was an error in parsing")
}

return []byte(secret), nil
})

if token == nil {
w.Write([]byte("Invalid token"));
w.WriteHeader(http.StatusUnauthorized)
return
}

if !token.Valid {
w.WriteHeader(http.StatusForbidden)
return
}

_, ok := token.Claims.(jwt.MapClaims)

if !ok {
w.Write([]byte("couldn't parse claims"));
w.WriteHeader(http.StatusUnauthorized)
return
}

// if claims["user_id"] == nil {
// w.Write([]byte("user_id not found"));
// w.WriteHeader(http.StatusUnauthorized)
// return
// }
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}

0 comments on commit af5ea26

Please sign in to comment.