From d6c847117fa7ced059c2c8c54cb7c942a33b6dd4 Mon Sep 17 00:00:00 2001 From: fbonhomm Date: Sun, 25 Aug 2019 17:16:46 +0200 Subject: [PATCH] feat: add auth jwt middleware --- source/middlewares/jwt.go | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 source/middlewares/jwt.go diff --git a/source/middlewares/jwt.go b/source/middlewares/jwt.go new file mode 100644 index 0000000..c39155d --- /dev/null +++ b/source/middlewares/jwt.go @@ -0,0 +1,41 @@ +/** + * Created by fbonhomm + * Email: flo-github@outlook.fr + * Licence: MIT + */ + +package middlewares + +import ( + "fmt" + jwt "github.com/dgrijalva/jwt-go" + "github.com/fbonhomm/api-go/source/libs" + "github.com/fbonhomm/api-go/source/services" + "github.com/gin-gonic/gin" + "net/http" + "os" +) + +func Auth(c *gin.Context) { + tokenString := libs.GetToken(c) + + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok { + return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + } + + return services.PublicKeyAccess, nil + }) + + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{ "error": err }) + c.Abort() + } + + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + c.Set("Token", claims) + } else { + c.JSON(http.StatusUnauthorized, gin.H{ "error": err }) + c.Abort() + } +}