common/validate/common.go

105 lines
2.3 KiB
Go
Raw Normal View History

2024-12-02 08:52:38 +00:00
package validate
import (
"context"
"fmt"
"gitea.pena/PenaSide/common/mongo"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"regexp"
"time"
)
type t struct {
ID string `bson:"_id,omitempty"`
I int `bson:"i"`
}
// todo в будущем в монге будут запрещены некоторые операции, надо будет обновлять
func ValidateMongo(cfg mongo.Configuration) error {
if cfg.URL == "" {
return fmt.Errorf("mongo URL is empty")
}
if cfg.DatabaseName == "" {
return fmt.Errorf("mongo database name is empty")
}
cfg.DatabaseName = "testDBName"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
database, err := mongo.Connect(ctx, &mongo.ConnectDeps{
Configuration: &cfg,
Timeout: 10 * time.Second,
})
if err != nil {
return err
}
defer database.Drop(ctx)
testCollection := database.Collection(cfg.DatabaseName)
receivedChannel := make(chan string, 10)
errorChannel := make(chan error, 1)
go func() {
defer close(receivedChannel)
defer close(errorChannel)
for i := 0; i <= 100; i++ {
d := t{
ID: primitive.NewObjectID().Hex(),
I: i,
}
_, err = testCollection.InsertOne(ctx, d)
if err != nil {
errorChannel <- err
}
receivedChannel <- d.ID
}
}()
timeout := time.After(30 * time.Second)
for {
select {
case err = <-errorChannel:
if err != nil {
return fmt.Errorf("error document insert: %w", err)
}
case id := <-receivedChannel:
result := t{}
err := testCollection.FindOne(ctx, bson.M{"_id": id}).Decode(&result)
if err != nil {
return fmt.Errorf("mongo error finding document: %v", err)
}
if id != result.ID {
return fmt.Errorf("invalid id received")
}
if result.I == 100 {
return nil
}
case <-timeout:
return fmt.Errorf("timeout")
}
}
}
func ValidateTgToken(token string) error {
if token == "" {
return fmt.Errorf("tg token is empty")
}
// todo обдумать еще регулярку
pattern := `^\d+:.+$`
ok, err := regexp.MatchString(pattern, token)
if err != nil {
return fmt.Errorf("error validating tg token - %s: %w", token, err)
}
if !ok {
return fmt.Errorf("invalid tg token format: %s", token)
}
return nil
}