1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| var identityKey = "id"
type login struct { Username string `form:"username" json:"username" binding:"required"` Password string `form:"password" json:"password" binding:"required"` }
type User struct { Id int UserName string NickName string }
func JwtMiddleware() (authMiddleware *jwt.GinJWTMiddleware, err error) { authMiddleware, err = jwt.New(&jwt.GinJWTMiddleware{ Realm: "test zone", Key: []byte("secret key"), Timeout: time.Hour, MaxRefresh: time.Hour, IdentityKey: identityKey, PayloadFunc: func(data interface{}) jwt.MapClaims { if v, ok := data.(*User); ok { return jwt.MapClaims{ identityKey: v.UserName, } } return jwt.MapClaims{} }, IdentityHandler: func(c *gin.Context) interface{} { claims := jwt.ExtractClaims(c) return &User{ UserName: claims[identityKey].(string), } }, Authenticator: func(c *gin.Context) (interface{}, error) { var loginVals login if err := c.ShouldBind(&loginVals); err != nil { return "", jwt.ErrMissingLoginValues } userID := loginVals.Username password := loginVals.Password
user, err := http_service.FindUser(userID) if err != nil { return nil, jwt.ErrFailedAuthentication }
encrypt := utils.PasswordEncrypt(password, userID) if encrypt != user.Password.String { return nil, jwt.ErrFailedAuthentication }
return &User{ Id: user.Id, UserName: user.Username.String, NickName: user.Nickname.String, }, nil }, Authorizator: func(data interface{}, c *gin.Context) bool { if v, ok := data.(*User); ok && v.UserName == "admin" { 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, cookie: jwt_middleware", TokenHeadName: "Bearer", TimeFunc: time.Now, }) return }
|