using Microsoft.Extensions.Configuration; using MongoDB.Driver; using Users_API.Helpers; using Users_API.Models; namespace Users_API.Database { public class MongoDatabaseConnection : IDatabaseConnection { private readonly string _connectionString; private readonly IMongoDatabase _usersDatabase; private readonly MongoClient mongoClient; public MongoDatabaseConnection(IConfiguration configuration) { _connectionString = FileSystem.GetAllTextFromFile(configuration.GetSection("ConnectionStrings:MongoCredentials").Value); mongoClient = new MongoClient(_connectionString); _usersDatabase = mongoClient.GetDatabase("Main"); } public UserModel GetUserByUsernameAndPassword(UserModel userModel) { var collection = _usersDatabase.GetCollection("users"); var builder = Builders.Filter; var usernameAndPasswordOnlyFilter = builder.Eq("username", userModel.Username) & builder.Eq("password", userModel.Password); return collection.Find(usernameAndPasswordOnlyFilter).FirstOrDefault(); } public bool DoesUsernameExist(UserModel userModel) { var collection = _usersDatabase.GetCollection("users"); var builder = Builders.Filter; var usernameOnlyFilter = builder.Eq("username", userModel.Username); return collection.Find(usernameOnlyFilter).FirstOrDefault() != null; } public bool DoesUserExist(UserModel userModel) { var collection = _usersDatabase.GetCollection("users"); var builder = Builders.Filter; var usernameOnlyFilter = builder.Eq("username", userModel.Username); return collection.Find(usernameOnlyFilter).FirstOrDefault() != null; } public string CreateUser(UserModel userModel) { var collection = _usersDatabase.GetCollection("users"); collection.InsertOne(userModel); return GetUserIdByUsername(userModel); } private string GetUserIdByUsername(UserModel userModel) { var collection = _usersDatabase.GetCollection("users"); var builder = Builders.Filter; var usernameFilter = builder.Eq("username", userModel.Username) & builder.Eq("password", userModel.Password); var result = collection.Find(usernameFilter).FirstOrDefault(); return result.Uid.ToString(); } } }