rts-sim-testing-service/middleware/jwt.go
2023-08-30 13:25:57 +08:00

86 lines
2.3 KiB
Go

package middleware
import (
"log"
"strconv"
"time"
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
"joylink.club/bj-rtsts-server/db/dbquery"
"joylink.club/bj-rtsts-server/db/model"
"joylink.club/bj-rtsts-server/dto"
)
const IdentityKey = "id"
const CentrifugoKey = "sub" // centrifugo 消息传递服务器token验证需要的主键
func InitGinJwtMiddleware() (authMiddleware *jwt.GinJWTMiddleware) {
// the jwt middleware
authMiddleware, err := jwt.New(&jwt.GinJWTMiddleware{
Realm: "joylink.club",
Key: []byte("joylink"),
Timeout: time.Hour,
// MaxRefresh: time.Hour,
IdentityKey: IdentityKey,
PayloadFunc: func(data interface{}) jwt.MapClaims {
if v, ok := data.(*model.User); ok {
return jwt.MapClaims{
IdentityKey: v.ID,
CentrifugoKey: strconv.Itoa(int(v.ID)),
}
}
return jwt.MapClaims{}
},
IdentityHandler: func(c *gin.Context) interface{} {
claims := jwt.ExtractClaims(c)
return &model.User{
ID: int32(claims[IdentityKey].(float64)),
}
},
Authenticator: func(c *gin.Context) (interface{}, error) {
var loginVals dto.LoginDto
if err := c.ShouldBind(&loginVals); err != nil {
return "", jwt.ErrMissingLoginValues
}
account := loginVals.Account
password := loginVals.Password
user, err := dbquery.User.Where(dbquery.User.Mobile.Eq(account)).Where(dbquery.User.Password.Eq(password)).First()
if err != nil {
return nil, jwt.ErrFailedAuthentication
}
// 清理权限
ClearUserPermission(user.ID)
return user, nil
},
// Authorizator: func(data interface{}, c *gin.Context) bool {
// if v, ok := data.(*model.User); ok && v.Name == "sheng" {
// return true
// }
// return false
// },
// Unauthorized: func(c *gin.Context, code int, message string) {
// c.JSON(code, gin.H{
// "code": code,
// "message": message,
// })
// },
TokenLookup: "header: Authorization, query: token",
// TokenHeadName is a string in the header. Default value is "Bearer"
TokenHeadName: "Bearer",
// TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
TimeFunc: time.Now,
})
if err != nil {
log.Fatal("JWT Error:" + err.Error())
}
return
}