draincloud-core/internal/reqcontext/auth.go

39 lines
947 B
Go

package reqcontext
import (
"context"
"fmt"
"git.optclblast.xyz/draincloud/draincloud-core/internal/storage/models"
"github.com/google/uuid"
)
type CtxKey string
const (
UserIDCtxKey CtxKey = "_ctx_user_id"
SessionCtxKey CtxKey = "_ctx_session"
)
func WithUserID(parent context.Context, userID uuid.UUID) context.Context {
return context.WithValue(parent, UserIDCtxKey, userID)
}
func GetUserID(ctx context.Context) (uuid.UUID, error) {
if id, ok := ctx.Value(UserIDCtxKey).(uuid.UUID); ok {
return id, nil
}
return uuid.Nil, fmt.Errorf("userID not passed with context")
}
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")
}