package user import ( "context" "git.1in9.net/raider/wroofauth/internal/database" "git.1in9.net/raider/wroofauth/internal/logger" "github.com/spf13/viper" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) var collection *mongo.Collection func SetupCollection() { collection = database.Mongo.Collection(viper.GetString("mongo.collection.users")) } func (u *User) Persist(ctx context.Context) error { return Persist(ctx, u) } func Persist(ctx context.Context, user *User) error { if user == nil { logger.Logger.Panic("trying to persist null-pointer") } // TODO: Validate? upsert := true _, err := collection.ReplaceOne(ctx, bson.M{"_id": user.ID}, user, &options.ReplaceOptions{Upsert: &upsert}) if err != nil { return err } return nil } func GetById(ctx context.Context, id primitive.ObjectID) (*User, error) { res := collection.FindOne(ctx, bson.M{"_id": id}) if res.Err() != nil { return nil, res.Err() } var user User err := res.Decode(&user) if err != nil { return nil, err } return &user, nil } func GetByIdentification(ctx context.Context, identification string) (*User, error) { res := collection.FindOne(ctx, bson.D{ {Key: "$or", Value: bson.A{ bson.D{{Key: "username", Value: identification}}, bson.D{{Key: "email", Value: identification}}, }, }, }) if res.Err() != nil { return nil, res.Err() } var user User err := res.Decode(&user) if err != nil { return nil, err } return &user, nil }