2024-11-23 08:52:06 +00:00
|
|
|
package reqcontext
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"git.optclblast.xyz/draincloud/draincloud-core/internal/storage/models"
|
2024-12-16 05:08:37 +00:00
|
|
|
"github.com/google/uuid"
|
2024-11-23 08:52:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type CtxKey string
|
|
|
|
|
|
|
|
const (
|
|
|
|
UserIDCtxKey CtxKey = "_ctx_user_id"
|
|
|
|
SessionCtxKey CtxKey = "_ctx_session"
|
|
|
|
)
|
|
|
|
|
2024-12-16 05:08:37 +00:00
|
|
|
func WithUserID(parent context.Context, userID uuid.UUID) context.Context {
|
2024-11-23 08:52:06 +00:00
|
|
|
return context.WithValue(parent, UserIDCtxKey, userID)
|
|
|
|
}
|
|
|
|
|
2024-12-16 05:08:37 +00:00
|
|
|
func GetUserID(ctx context.Context) (uuid.UUID, error) {
|
|
|
|
if id, ok := ctx.Value(UserIDCtxKey).(uuid.UUID); ok {
|
2024-11-23 08:52:06 +00:00
|
|
|
return id, nil
|
|
|
|
}
|
2024-12-16 05:08:37 +00:00
|
|
|
return uuid.Nil, fmt.Errorf("userID not passed with context")
|
2024-11-23 08:52:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func WithSession(parent context.Context, session *models.Session) context.Context {
|
|
|
|
return context.WithValue(parent, SessionCtxKey, session)
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetSession(ctx context.Context) (*models.Session, error) {
|
|
|
|
if ses, ok := ctx.Value(UserIDCtxKey).(*models.Session); ok {
|
|
|
|
return ses, nil
|
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("session not passed with context")
|
2024-12-16 05:08:37 +00:00
|
|
|
}
|