Skip to content

Commit

Permalink
fix(jwt): Add user information in jwt for showing UI according to use…
Browse files Browse the repository at this point in the history
…r permission level
  • Loading branch information
deo002 committed Jun 7, 2024
1 parent 3bbf2d8 commit f722ce0
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
9 changes: 7 additions & 2 deletions pkg/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pkg/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
7 changes: 7 additions & 0 deletions pkg/models/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down

0 comments on commit f722ce0

Please sign in to comment.