Skip to content

Commit

Permalink
More reliable pubkey deletion.
Browse files Browse the repository at this point in the history
  • Loading branch information
ro-tex committed Mar 24, 2022
1 parent 7a76f66 commit d40e0c9
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
12 changes: 7 additions & 5 deletions database/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"crypto/subtle"
"fmt"
"net/mail"
"strings"
"sync"
"time"

Expand Down Expand Up @@ -504,16 +503,19 @@ func (db *DB) UserPubKeyAdd(ctx context.Context, u User, pk PubKey) (err error)

// UserPubKeyRemove removes a PubKey from the given user's set.
func (db *DB) UserPubKeyRemove(ctx context.Context, u User, pk PubKey) error {
filter := bson.M{"_id": u.ID}
filter := bson.M{
"_id": u.ID,
"pub_keys": bson.M{"$ne": nil},
}
update := bson.M{
"$pull": bson.M{"pub_keys": pk},
}
opts := options.UpdateOptions{
Upsert: &False,
}
_, err := db.staticUsers.UpdateOne(ctx, filter, update, &opts)
if err != nil && strings.Contains(err.Error(), "Cannot apply $pull to a non-array value") {
return mongo.ErrNoDocuments
ur, err := db.staticUsers.UpdateOne(ctx, filter, update, &opts)
if err == nil && ur.MatchedCount == 0 {
err = mongo.ErrNoDocuments
}
return err
}
Expand Down
3 changes: 1 addition & 2 deletions test/database/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"gitlab.com/NebulousLabs/errors"
"gitlab.com/NebulousLabs/fastrand"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.sia.tech/siad/crypto"
)

Expand Down Expand Up @@ -462,7 +461,7 @@ func TestUserPubKey(t *testing.T) {
copy(pk1[:], fastrand.Bytes(database.PubKeySize))
// Try to remove a pubkey. Expect this to fail.
err = db.UserPubKeyRemove(ctx, *u, pk)
if err == nil || !errors.Contains(err, mongo.ErrNoDocuments) {
if err == nil {
t.Fatal(err)
}
// Add a pubkey.
Expand Down

0 comments on commit d40e0c9

Please sign in to comment.