Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(jwt): Add user information in jwt for showing UI according to user permission level #69

Merged
merged 1 commit into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
GMishx marked this conversation as resolved.
Show resolved Hide resolved
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
Loading