package db import ( "context" "log" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "golang.org/x/crypto/bcrypt" ) // SeedBroker inserts a default broker account if no users exist. // Credentials are taken from environment variables SEED_USERNAME and // SEED_PASSWORD; if unset they fall back to dev defaults and a warning // is printed. This function must not run in production without those vars set. func (c *Client) SeedBroker(ctx context.Context, username, password string) error { count, err := c.Users().CountDocuments(ctx, bson.D{}) if err != nil { return err } if count > 0 { return nil // already seeded } hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { return err } _, err = c.Users().InsertOne(ctx, bson.D{ {Key: "username", Value: username}, {Key: "password_hash", Value: string(hash)}, {Key: "role", Value: "broker"}, }) if err != nil && !mongo.IsDuplicateKeyError(err) { return err } log.Printf("db: seeded broker user %q", username) return nil }