gin-blog/internal/middleware/jwt.go

45 lines
841 B
Go
Raw Permalink Normal View History

2021-05-31 09:40:47 +00:00
package middleware
import (
"blog/pkg/app"
"blog/pkg/errorcode"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
var (
token string
ecode = errorcode.Success
)
if s, exist := c.GetQuery("Authorization"); exist {
2021-05-31 09:40:47 +00:00
token = s
} else {
token = c.GetHeader("Authorization")
2021-05-31 09:40:47 +00:00
}
if token == "" {
ecode = errorcode.InvalidParams
} else {
_, err := app.ParseToken(token)
if err != nil {
switch err.(*jwt.ValidationError).Errors {
case jwt.ValidationErrorExpired:
ecode = errorcode.UnauthorizedTokenTimeout
default:
ecode = errorcode.UnauthorizedTokenError
}
}
}
if ecode != errorcode.Success {
response := app.NewResponse(c)
response.ToErrorResponse(ecode)
c.Abort()
return
}
c.Next()
}
}