rts-sim-testing-service/middleware/jwt.go

94 lines
2.6 KiB
Go
Raw Permalink Normal View History

package middleware
import (
"log"
"strconv"
2023-09-07 14:36:23 +08:00
"strings"
"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"),
2023-09-07 13:57:41 +08:00
Timeout: 5 * 24 * 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
}
2023-08-30 09:28:21 +08:00
// 清理权限
ClearUserPermission(user.ID)
return user, nil
},
2023-09-07 14:19:50 +08:00
Unauthorized: func(c *gin.Context, code int, message string) {
2023-09-07 14:36:23 +08:00
if strings.Contains(message, "token") {
c.JSON(code, gin.H{"code": code, "title": "token过期", "message": message})
} else {
c.JSON(code, gin.H{"code": code, "title": "登录认证失败", "message": message})
}
2023-09-07 14:19:50 +08:00
},
// 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
}