mobility-accounts/storage/mongodb.go

199 lines
5.2 KiB
Go
Executable File

package storage
import (
"context"
"errors"
"fmt"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoDBStorage struct {
*mongo.Client
DbName string
Collections map[string]string
}
func NewMongoDBStorage(cfg *viper.Viper) (MongoDBStorage, error) {
var (
mongodb_uri = cfg.GetString("storage.db.mongodb.uri")
mongodb_host = cfg.GetString("storage.db.mongodb.host")
mongodb_port = cfg.GetString("storage.db.mongodb.port")
mongodb_dbname = cfg.GetString("storage.db.mongodb.db_name")
mongodb_users = cfg.GetString("storage.db.mongodb.collections.users")
)
if mongodb_uri == "" {
mongodb_uri = fmt.Sprintf("mongodb://%s:%s", mongodb_host, mongodb_port)
}
client, err := mongo.NewClient(options.Client().ApplyURI(mongodb_uri))
if err != nil {
return MongoDBStorage{}, err
}
err = client.Connect(context.TODO())
if err != nil {
return MongoDBStorage{}, err
}
storage := MongoDBStorage{
Client: client,
DbName: mongodb_dbname,
Collections: map[string]string{
"users": mongodb_users,
},
}
// usernameIndex := mongo.IndexModel{
// Keys: bson.D{
// {"namespace", 1},
// {"authentication.local.username", 1},
// },
// Options: options.Index().SetUnique(true),
// }
// storage.Client.Database(mongodb_dbname).Collection(mongodb_users).Indexes().CreateOne(context.TODO(), usernameIndex)
return storage, err
}
// LocalAuthentication returns an Account matching with one of username, email or password.
// If username, is provided (not an empty string), it will search by username only
// If username is an empty string and email is provided, it will search by email
// If both username and email are empty strings, phone_number must be provided and it will search by phone number
func (s MongoDBStorage) LocalAuthentication(namespace string, username *string, email *string, phone_number *string) (*Account, error) {
collection := s.Client.Database(s.DbName).Collection(s.Collections["users"])
account := &Account{}
if username != nil {
if err := collection.FindOne(context.TODO(), bson.M{"namespace": namespace, "authentication.local.username": username}).Decode(account); err != nil {
return nil, err
}
} else if email != nil {
if err := collection.FindOne(context.TODO(), bson.M{"namespace": namespace, "authentication.local.email": email}).Decode(account); err != nil {
return nil, err
}
} else if phone_number != nil {
if err := collection.FindOne(context.TODO(), bson.M{"namespace": namespace, "authentication.local.phone_number": phone_number}).Decode(account); err != nil {
return nil, err
}
} else {
return nil, errors.New("missing username, email or password")
}
return account, nil
}
func (s MongoDBStorage) GetAccount(id string) (*Account, error) {
collection := s.Client.Database(s.DbName).Collection(s.Collections["users"])
account := &Account{}
if err := collection.FindOne(context.TODO(), bson.M{"_id": id}).Decode(account); err != nil {
return nil, err
}
return account, nil
}
func (s MongoDBStorage) GetAccounts(namespaces []string) (accounts []Account, err error) {
collection := s.Client.Database(s.DbName).Collection(s.Collections["users"])
var cur *mongo.Cursor
findOptions := options.Find()
if len(namespaces) == 0 {
cur, err = collection.Find(context.TODO(), bson.D{}, findOptions)
if err != nil {
return accounts, err
}
} else {
cur, err = collection.Find(context.TODO(), bson.M{"namespace": bson.M{"$in": namespaces}}, findOptions)
if err != nil {
return accounts, err
}
}
for cur.Next(context.TODO()) {
var account Account
var elem bson.M
err := cur.Decode(&elem)
if err != nil {
return accounts, err
}
bsonBytes, _ := bson.Marshal(elem)
bson.Unmarshal(bsonBytes, &account)
accounts = append(accounts, account)
}
return
}
func (s MongoDBStorage) GetAccountsByIds(accountids []string) (accounts []Account, err error) {
collection := s.Client.Database(s.DbName).Collection(s.Collections["users"])
var cur *mongo.Cursor
findOptions := options.Find()
if len(accountids) == 0 {
return accounts, errors.New("missing account ids")
} else {
cur, err = collection.Find(context.TODO(), bson.M{"_id": bson.M{"$in": accountids}}, findOptions)
if err != nil {
return accounts, err
}
}
for cur.Next(context.TODO()) {
var account Account
var elem bson.M
err := cur.Decode(&elem)
if err != nil {
return accounts, err
}
bsonBytes, _ := bson.Marshal(elem)
bson.Unmarshal(bsonBytes, &account)
accounts = append(accounts, account)
}
return
}
func (s MongoDBStorage) CreateAccount(account Account) error {
collection := s.Client.Database(s.DbName).Collection(s.Collections["users"])
if _, err := collection.InsertOne(context.TODO(), account); err != nil {
return err
}
return nil
}
func (s MongoDBStorage) UpdateAccount(account Account) error {
collection := s.Client.Database(s.DbName).Collection(s.Collections["users"])
if _, err := collection.ReplaceOne(context.TODO(), bson.M{"_id": account.ID}, account); err != nil {
fmt.Println(err)
return err
}
return nil
}
func (s MongoDBStorage) Migrate() error {
fmt.Println("no migration")
return nil
}