Good afternoon I need to implement user verification email and I am using mongo driver, as below I have User entity and ConfirmationToken Embeddable.
I want ConfirmationToken to die after some period of time, as in redis ttl I use Index https://www.mongodb.com/docs/manual/core/index-ttl/#timing-of-the-delete-operation - documentation. But I have a problem, the token stays, even after time, how can I make the ConfirmationToken die after say an hour?
User entity
type User struct {
ID string `json:"id" bson:"id"`
VerifyEmail ConfirmationToken `json:"verifyemail,omitempty" bson:"verifyemail"`
ConfirmedMail bool `json:"confirmedMail" json:"confirmedMail"`
}
type ConfirmationToken struct {
Value string `json:"value,omitempty" bson:"value"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
ExpireOn int64 `json:"expireon,omitempty" bson:"expires"`
}
My request to mongodb
init repository
func NewMongo(client *mongo.Client) *Mongo {
m := &Mongo{
col: client.Database("data").Collection("user"),
}
// create ttl index
_, _ = m.col.Indexes().CreateOne(context.Background(), mongo.IndexModel{
Keys: bson.D{{
Key: "verifyemail.created_at",
Value: 1,
}},
Options: options.Index().SetExpireAfterSeconds(int32(time.Now().Add(time.Minute * 4).Unix())),
})
return m
}
func (r *Mongo) CreateVerifyEmailToken(ctx context.Context, user *domain.User) (*domain.User, error) {
oid, err := primitive.ObjectIDFromHex(user.ID)
if err != nil {
return user, err
}
data := bson.M{
"verifyemail": user.VerifyEmail,
}
u := &domain.User{}
err = r.col.FindOneAndUpdate(
ctx,
bson.M{"_id": oid},
bson.M{"$set": data},
options.FindOneAndUpdate().SetReturnDocument(options.After),
).Decode(u)
fmt.Print(u)
return u, err
}
Again I repeat my question: How can I make the ConfirmationToken live for a while and then automatically delete it?