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.

131 lines
2.5 KiB

2 months ago
package user
import (
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"net/http"
"product/backend/models"
"product/backend/moo/db"
"product/backend/moo/log"
"strings"
"time"
)
func AuthJWT(ctx *gin.Context) {
if strings.HasPrefix(ctx.Request.RequestURI, "/assets") {
return
}
if strings.HasPrefix(ctx.Request.RequestURI, "/open/") {
return
}
if ctx.Request.RequestURI == "/user/login" {
return
}
ss := ctx.GetHeader("Authorization")
ss = strings.Replace(ss, "Bearer ", "", -1)
if ss == "" {
log.Error("jwt token is empty")
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": "token 错误",
})
ctx.Abort()
return
}
token, err := jwt.ParseWithClaims(ss, &jwt.RegisteredClaims{}, func(token *jwt.Token) (interface{}, error) {
return models.UserSigningKey, nil
}, jwt.WithLeeway(5*time.Second))
if err != nil {
log.Error(err)
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": "token 错误",
})
ctx.Abort()
return
}
claims, ok := token.Claims.(*jwt.RegisteredClaims)
if !ok {
log.Error("token type error")
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": "token 错误",
})
ctx.Abort()
return
}
user := models.User{}
if err := db.DB.First(&user, claims.ID).Error; err != nil {
log.Error(err)
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": "用户错误",
})
ctx.Abort()
return
}
//if user.AuthToken != ss {
// log.Error("user token changed")
// ctx.JSON(http.StatusOK, gin.H{
// "code": 1,
// "message": "用户错误",
// })
// ctx.Abort()
// return
//}
_ = db.DB.Model(&user).Association("Role").Find(&user.Role)
ctx.Set("user", user)
//ctx.Next()
}
func PrivCheck(ctx *gin.Context) {
if strings.HasPrefix(ctx.Request.RequestURI, "/assets") {
return
}
if strings.HasPrefix(ctx.Request.RequestURI, "/open/") {
return
}
if ctx.Request.RequestURI == "/user/login" {
return
}
userValue, exists := ctx.Get("user")
if !exists {
log.Error("no auth")
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": "用户错误",
})
ctx.Abort()
return
}
user := userValue.(models.User)
if user.RoleID == 1 {
// super admin
return
}
privs := user.Role.Privs
need := strings.TrimLeft(ctx.Request.URL.Path, "/") + "/" + strings.ToLower(ctx.Request.Method)
if !strings.Contains(privs, need) {
log.Error("no priv")
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": "权限错误",
})
ctx.Abort()
return
}
}