draincloud-core/internal/reqcontext/auth.go
2024-11-23 03:52:06 -05:00

37 lines
902 B
Go

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