40 lines
1.3 KiB
Go
40 lines
1.3 KiB
Go
// Package indexes declares the MongoDB indexes more than one Vantage service
|
|
// depends on.
|
|
package indexes
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
|
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
|
)
|
|
|
|
// EnsureCoreIndexes declares the unique indexes on users.email and orgs.slug.
|
|
//
|
|
// These are a security property, not an optimisation. GetUserByEmail does an
|
|
// unscoped FindOne, so a duplicate email would let the OIDC cross-org guard
|
|
// compare against an arbitrary user. Every caller must treat a failure here as
|
|
// fatal.
|
|
//
|
|
// Creating an index that already exists with the same specification is a no-op,
|
|
// so this is safe to call at every boot from every service.
|
|
func EnsureCoreIndexes(ctx context.Context, db *mongo.Database) error {
|
|
if _, err := db.Collection("users").Indexes().CreateOne(ctx, mongo.IndexModel{
|
|
Keys: bson.D{{Key: "email", Value: 1}},
|
|
Options: options.Index().SetUnique(true),
|
|
}); err != nil {
|
|
return fmt.Errorf("users.email index: %w", err)
|
|
}
|
|
|
|
if _, err := db.Collection("instances").Indexes().CreateOne(ctx, mongo.IndexModel{
|
|
Keys: bson.D{{Key: "slug", Value: 1}},
|
|
Options: options.Index().SetUnique(true),
|
|
}); err != nil {
|
|
return fmt.Errorf("instances.slug index: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|