draincloud-core/internal/reqcontext/auth.go

39 lines
946 B
Go
Raw Permalink Normal View History

2024-11-23 08:52:06 +00:00
package reqcontext
import (
"context"
"fmt"
2025-01-10 23:09:37 +00:00
"git.optclblast.xyz/draincloud/draincloud-core/internal/storage/models/auth"
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
}
2025-01-10 23:09:37 +00:00
func WithSession(parent context.Context, session *auth.Session) context.Context {
2024-11-23 08:52:06 +00:00
return context.WithValue(parent, SessionCtxKey, session)
}
2025-01-10 23:09:37 +00:00
func GetSession(ctx context.Context) (*auth.Session, error) {
if ses, ok := ctx.Value(UserIDCtxKey).(*auth.Session); ok {
2024-11-23 08:52:06 +00:00
return ses, nil
}
return nil, fmt.Errorf("session not passed with context")
2024-12-16 05:08:37 +00:00
}