56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"opencatd-open/internal/auth"
|
|
"opencatd-open/internal/consts"
|
|
"opencatd-open/internal/dto"
|
|
"opencatd-open/internal/model"
|
|
"opencatd-open/pkg/store"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func Auth(c *gin.Context) {
|
|
authToken := c.GetHeader("Authorization")
|
|
if authToken == "" {
|
|
dto.Fail(c, http.StatusUnauthorized, "未提供认证信息")
|
|
return
|
|
}
|
|
authToken = authToken[7:]
|
|
claim, err := auth.ValidateToken(authToken, consts.SecretKey)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
|
"code": http.StatusUnauthorized,
|
|
"error": "无效的认证信息",
|
|
})
|
|
return
|
|
}
|
|
var user model.User
|
|
if err := store.GetDB().Model(&model.User{ID: int64(claim.UserID)}).First(&user).Error; err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
|
"code": http.StatusUnauthorized,
|
|
"error": "无效的认证信息",
|
|
})
|
|
return
|
|
}
|
|
c.Set("user", &user)
|
|
c.Set("user_id", claim.UserID)
|
|
c.Set("user_role", user.Role)
|
|
c.Next()
|
|
}
|
|
func CheckRole(role consts.UserRole) func(c *gin.Context) {
|
|
fmt.Println("CheckRoleMiddleware")
|
|
return func(c *gin.Context) {
|
|
userRole := c.GetInt("user_role") // 操作者
|
|
fmt.Println("userRole", userRole)
|
|
// if userRole < int(role) {
|
|
// dto.Fail(c, http.StatusForbidden, "permission denied")
|
|
// return
|
|
// }
|
|
|
|
c.Next()
|
|
}
|
|
}
|