package app import ( "context" "fmt" "net/http" "git.farahty.com/nimer/go-mongo/models" ) type contextKey struct { name string } var ( UserKey = &contextKey{"user"} StatusKey = &contextKey{"status"} ExpiryKey = &contextKey{"expiry"} LoadersKey = &contextKey{"dataLoaders"} WriterKye = &contextKey{"writer"} RequestKey = &contextKey{"request"} ) // LoaderFor retrieves the dataLoaders from context func LoaderFor(ctx context.Context) *Loaders { if loaders, ok := ctx.Value(LoadersKey).(*Loaders); ok { return loaders } panic("dataloader not found in context") } func WriterFor(ctx context.Context) *http.ResponseWriter { if writer, ok := ctx.Value(WriterKye).(*http.ResponseWriter); ok { return writer } panic("no writer found in context") } func RequestFor(ctx context.Context) *http.Request { if req, ok := ctx.Value(RequestKey).(*http.Request); ok { return req } panic("no request found in context") } // Retrieves the current user from the context func CurrentUser(ctx context.Context) (*models.UserJWT, error) { user, _ := ctx.Value(UserKey).(*models.UserJWT) status, _ := ctx.Value(StatusKey).(string) if status != "ok" { return nil, fmt.Errorf("%s", status) } return user, nil } // Check if the token was marked as expired func IsTokenExpired(ctx context.Context) bool { if expired, ok := ctx.Value(ExpiryKey).(bool); ok { return expired } return false } // Sets the status in context (e.g., "ok" or error message) func SetStatus(ctx context.Context, data any) context.Context { return context.WithValue(ctx, StatusKey, data) } // Sets the authenticated user into the context func SetCurrentUser(ctx context.Context, user *models.UserJWT) context.Context { return context.WithValue(ctx, UserKey, user) } // Marks the token as expired in the context func SetTokenExpired(ctx context.Context, expiry bool) context.Context { return context.WithValue(ctx, ExpiryKey, expiry) }