简体   繁体   中英

Getting password from mongodb c#

I am trying to create a login method and I need to get a password from the corresponding user. This is my database layer code:

public int loginUser(string userName, string pass)
    {
        int result = 0;
        var credentials = MongoCredential.CreateMongoCRCredential("SearchForKnowledge", userName, pass);
        var settings = new MongoClientSettings
        {
            Credentials = new[] { credentials }
        };
        try
        {
            var mongoClient = new MongoClient(settings);
            var database = mongoClient.GetDatabase("SearchForKnowledge");
            var coll = database.GetCollection<BsonDocument>("Users");

            var filter = Builders<BsonDocument>.Filter.Eq("userName", userName);
            var query = coll.Find(filter);
            //??????????
        }
        catch (Exception ex) {
            result = 0;
        }
        return result;
    }

as you can see if the login is success im trying to return 1 and if it fails, 0 (for redirecting purposes). I am struggling to check if the username matches password set to it. At the moment I just made a filter, passed it to the method Find and im dead stuck at this point. How do I return that user's password from mongodb and compare it to the one passed as a parameter?

Try something like this:

public int loginUser(string userName, string pass)
    {
        int result = 0;
        //Here you use credentials for the connection, not the one passed
        //to the method:
        var credentials = MongoCredential.CreateMongoCRCredential("SearchForKnowledge", connectionUsername, connectionPass);
        var settings = new MongoClientSettings
        {
            Credentials = new[] { credentials }
        };
        try
        {
            var mongoClient = new MongoClient(settings);
            var database = mongoClient.GetDatabase("SearchForKnowledge");
            var coll = database.GetCollection<BsonDocument>("Users");

            var filter = Builders<BsonDocument>.Filter.Eq("userName", userName);
            var result = await coll.Find(filter).ToListAsync().First();
            if(result["Password"] == pass)
            {
               result = 1;
            }
        }
        catch (Exception ex) {
            result = 0;
        }
        return result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM