2023-07-14 10:16:58 +08:00
package middleware
import (
"log"
"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"
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 ,
}
}
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
}
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
}
2023-07-14 16:47:59 +08:00
func ParseContextUserId ( c * gin . Context ) int32 {
claims := jwt . ExtractClaims ( c )
return int32 ( claims [ IdentityKey ] . ( float64 ) )
}