potato/internal/middleware/jwt.go

51 lines
1002 B
Go
Raw Permalink Normal View History

2021-03-23 00:55:26 +08:00
/*
* @Date: 2021-03-21 19:54:57
* @LastEditors: viletyy
2021-06-10 22:41:58 +08:00
* @LastEditTime: 2021-06-10 21:49:20
2021-06-10 15:37:36 +08:00
* @FilePath: /potato/internal/middleware/jwt.go
2021-03-23 00:55:26 +08:00
*/
package middleware
import (
"github.com/gin-gonic/gin"
2022-01-24 17:56:06 +08:00
"github.com/golang-jwt/jwt"
2021-06-10 22:41:58 +08:00
"github.com/viletyy/potato/pkg/app"
"github.com/viletyy/potato/pkg/errcode"
2021-03-23 00:55:26 +08:00
)
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
2021-06-10 22:41:58 +08:00
var (
token string
ecode = errcode.Success
)
if s, exist := c.GetQuery("token"); exist {
token = s
} else {
token = c.GetHeader("token")
}
2021-03-23 00:55:26 +08:00
if token == "" {
2021-06-10 22:41:58 +08:00
ecode = errcode.InvalidParams
2021-03-23 00:55:26 +08:00
} else {
2021-06-10 22:41:58 +08:00
_, err := app.ParseToken(token)
2021-03-23 00:55:26 +08:00
if err != nil {
2021-06-10 22:41:58 +08:00
switch err.(*jwt.ValidationError).Errors {
case jwt.ValidationErrorExpired:
ecode = errcode.UnauthorizedTokenTimeout
default:
ecode = errcode.UnauthorizedTokenError
2021-03-23 00:55:26 +08:00
}
}
}
2021-06-10 22:41:58 +08:00
if ecode != errcode.Success {
response := app.NewResponse(c)
response.ToErrorResponse(ecode)
c.Abort()
return
}
2021-03-23 00:55:26 +08:00
c.Next()
}
}