From e27a85067ad8316f1e536160e7c147f84e76d8fa 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/models/types.go | 7 +++++++ 2 files changed, 14 insertions(+), 2 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/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"`