2023-07-14 10:16:58 +08:00
package middleware
import (
"log"
2023-07-27 16:59:55 +08:00
"strconv"
2023-07-14 10:16:58 +08:00
"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"
2023-07-27 16:59:55 +08:00
const CentrifugoKey = "sub" // centrifugo 消息传递服务器token验证需要的主键
2023-07-14 10:16:58 +08:00
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 {
2023-07-27 16:59:55 +08:00
IdentityKey : v . ID ,
CentrifugoKey : strconv . Itoa ( int ( v . ID ) ) ,
2023-07-14 10:16:58 +08:00
}
}
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
// 清理权限
2023-08-30 13:25:57 +08:00
ClearUserPermission ( user . ID )
2023-07-14 10:16:58 +08:00
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
}