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
|
|
|
|
)
|
2021-06-01 08:19:40 +00:00
|
|
|
if s, exist := c.GetQuery("Authorization"); exist {
|
2021-05-31 09:40:47 +00:00
|
|
|
token = s
|
|
|
|
} else {
|
2021-06-01 08:19:40 +00:00
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|