From f722ce0878049fc7a808e91d6cbb5ee80ee9a6d7 Mon Sep 17 00:00:00 2001 From: deo002 Date: Thu, 6 Jun 2024 16:01:04 +0530 Subject: [PATCH] fix(jwt): Add user information in jwt for showing UI according to user permission level --- pkg/auth/auth.go | 9 +++++++-- pkg/middleware/middleware.go | 2 +- pkg/models/types.go | 7 +++++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/pkg/auth/auth.go b/pkg/auth/auth.go index cbc285c..4f01eaa 100644 --- a/pkg/auth/auth.go +++ b/pkg/auth/auth.go @@ -307,13 +307,18 @@ func encryptUserPassword(user *models.User) error { // generateToken generates a JWT token for the user. func generateToken(user models.User) (string, error) { tokenLifespan, err := strconv.Atoi(os.Getenv("TOKEN_HOUR_LIFESPAN")) - if err != nil { return "", err } + jwtUser := models.JWTUser{ + Id: user.Id, + Username: user.Username, + Userlevel: user.Userlevel, + } + claims := jwt.MapClaims{} - claims["id"] = user.Id + claims["user"] = jwtUser claims["nbf"] = time.Now().Unix() claims["exp"] = time.Now().Add(time.Hour * time.Duration(tokenLifespan)).Unix() token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) diff --git a/pkg/middleware/middleware.go b/pkg/middleware/middleware.go index b5d25d5..a7574e6 100644 --- a/pkg/middleware/middleware.go +++ b/pkg/middleware/middleware.go @@ -79,7 +79,7 @@ func AuthenticationMiddleware() gin.HandlerFunc { return } - userId := int64(claims["id"].(float64)) + userId := int64(claims["user"].(map[string]interface{})["id"].(float64)) var user models.User if err := db.DB.Where(models.User{Id: userId}).First(&user).Error; err != nil { diff --git a/pkg/models/types.go b/pkg/models/types.go index a4f1e9c..f8782f6 100644 --- a/pkg/models/types.go +++ b/pkg/models/types.go @@ -258,6 +258,13 @@ type User struct { Userpassword *string `json:"password,omitempty" binding:"required"` } +// JWTUser struct is representation of user information in JWT. +type JWTUser struct { + Id int64 `json:"id"` + Username string `json:"username"` + Userlevel string `json:"userlevel"` +} + type UserInput struct { Username string `json:"username" gorm:"unique;not null" binding:"required" example:"fossy"` Userlevel string `json:"userlevel" binding:"required" example:"admin"`