45 lines
841 B
Go
45 lines
841 B
Go
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 {
|
|
token = s
|
|
} else {
|
|
token = c.GetHeader("Authorization")
|
|
}
|
|
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()
|
|
}
|
|
}
|