0

The following C# code accepts two parameter username and password from API using ajax

public Login[] checkLogin(models.Login log)
{
    Boolean flag = false;
    connection obj = new connection();
    IMongoDatabase server = obj.getConnection();
    var collection = server.GetCollection<models.Login>("login");
    string param = "{'username':'" + log.username + "','password':'"+ log.password +"'}";
    List<Login> result = new List<Login>();
    var check =  collection.Find(param);
    foreach(var emp in check.ToList())
    {
        result.Add(emp);
    }    
    if(result == null)  
        flag = false;   
    else
        flag = true;

    return result.ToArray();
}

I want to check the username and password from my MongoDB database. I am trying to find method but don't know how to check the value if it is available or not.

Rahul Hendawe
  • 902
  • 1
  • 14
  • 39
  • check [Using MongoDB and Mongoose for User Registration, Login and Logout in a Mobile Application](https://dzone.com/articles/using-mongodb-and-mongoose) this might help you – Rahul Hendawe Jan 02 '18 at 06:27

1 Answers1

0

In order to test whether provided credentials are valid, your method should simply return a boolean value.

You might do something like this.

public IMongoCollection<models.Login> GetLoginCollection()
{
    var client = new MongoClient();
    var database = client.GetDatabase("dbName");
    var collection = database.GetCollection<models.Login>("login");

    return collection;
}

public bool CheckLogin(models.Login log)
{
    var collection = this.GetLoginCollection();

    var authSuccessful = collection
        .Count(login =>
            login.username == log.username &&
            login.password == log.password) > 0;

    return authSuccessful;
}

As an alternative, CheckLogin() method might be implemented using explictly-defined filters.

public bool CheckLogin(models.Login log)
{
    var collection = GetLoginCollection();

    var filter = Builders<models.Login>.Filter
        .And(
            Builders<models.Login>.Filter.Eq(login => login.username, log.username),
            Builders<models.Login>.Filter.Eq(login => login.password, log.password));

    var authSuccessful = collection.Count(filter) > 0;

    return authSuccessful;
}

Note that storing clear text password within the database is a bad practice. Nobody but the user should know the actual password. One solution is storing the hashed password in the database. On authentication you can compare the hash of the provided password with your stored value. One of the most common hash functions is md5.

Marcello
  • 879
  • 6
  • 20