veza/veza-backend-api/internal/common/context.go

44 lines
1,011 B
Go
Raw Normal View History

2025-12-03 19:29:37 +00:00
package common
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
const (
UserIDContextKey = "user_id"
UsernameContextKey = "username"
)
// GetUserIDFromContext retrieves user ID from gin context
func GetUserIDFromContext(c *gin.Context) (uuid.UUID, bool) {
userID, exists := c.Get(UserIDContextKey)
if !exists {
return uuid.Nil, false // Return uuid.Nil for non-existent UUID
}
id, ok := userID.(uuid.UUID)
return id, ok
}
// SetUserIDInContext sets user ID in gin context
func SetUserIDInContext(c *gin.Context, userID uuid.UUID) {
c.Set(UserIDContextKey, userID)
}
// GetUsernameFromContext retrieves username from gin context
func GetUsernameFromContext(c *gin.Context) (string, bool) {
username, exists := c.Get(UsernameContextKey)
if !exists {
return "", false
}
name, ok := username.(string)
return name, ok
}
// SetUsernameInContext sets username in gin context
func SetUsernameInContext(c *gin.Context, username string) {
c.Set(UsernameContextKey, username)
}