You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.2 KiB
64 lines
1.2 KiB
package middleware
|
|
|
|
import (
|
|
"expenses/common"
|
|
"expenses/model"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// AuthMiddleWare
|
|
//
|
|
// @Description: 认证中间件
|
|
// @return gin.HandlerFunc
|
|
func AuthMiddleWare() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// 获取 authorization header
|
|
tokenString := c.GetHeader("Authorization")
|
|
|
|
// 验证token
|
|
if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"code": http.StatusUnauthorized,
|
|
"message": "请求未授权",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
tokenString = tokenString[7:]
|
|
|
|
token, claims, err := common.ParseToken(tokenString)
|
|
if err != nil || !token.Valid {
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"code": http.StatusUnauthorized,
|
|
"message": "请求未授权",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
// 验证通过后获取Claim中的UserId
|
|
userId := claims.UserId
|
|
DB := common.GetDB()
|
|
var user model.User
|
|
DB.First(&user, userId)
|
|
|
|
// 用户不存在
|
|
if user.ID == 0 {
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"code": http.StatusUnauthorized,
|
|
"message": "请求未授权",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// 用户信息存在,则将用户信息存入上下文
|
|
c.Set("user", user)
|
|
|
|
c.Next()
|
|
}
|
|
}
|