How can I save that password in a variable so that I can check it with user input and authenticate.
Below is my code.
app.post('/check-user',(req,res)=>{
var user=req.body.n1;
var pass=req.body.n2;
MongoClient.connect(url,{ useNewUrlParser: true, useUnifiedTopology: true},function(err,db){
if(err) throw err;
var dbase = db.db("db");
//var query = { username: user };
dbase.collection("users").find({"username":user},{projection:{_id:0,Name:0,username:0}}).toArray(function(err, result) {
if(err) throw err;
console.log(result);
db.close();
});
});
})
app.listen(8080,()=>{})
output is [{password:'keshav'}]
If I understood you question correctly,
You should not store actual password in database. Instead you should use a module like crypto to encrypt your password and then store it. You should google for it. There are tons of articles/tutorials about authentication in NodeJS.
About checking password, you are using this line to store user's given password in the pass variable (var pass=req.body.n2;), right? So, I believe a simple comparison operator should work in your case. Example:
if (result[0].password === pass) {
console.log('Loggedin');
} else {
console.log('Login failed');
}
Related
I was wondering if there is a way I can get a part of an object in mongo using node. For example, it would be great if I could log say the email that is being added, by using something like console.log(result.email) to get the email part of my response. Does anyone know how to do this?
Ok so I have found a way to do this. It will not work on the .find function for some reason, but will work on .findOne and .sort
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("db");
let query = {
username: "username",
key: "key"
};
dbo.collection("keys").findOne(query, (function(err, result) {
var lengthboi = result.length;
console.log(result)
if (lengthboi === 1) {
//do stuff
} else {
}
}));
});
I am trying to allow a user to input criteria (i.e. Client) for my application to query a mySQL database and return all matching results. My connection is established and I am able to hardcode my query (connection.query("select * from ACHLookerUpper where Client = ?", ["ex."]) and return expected results. I can also simply run the Prompt command and intake and console.log my input.
However, when I try to combine the two -- intake user input via Prompt and query -- I cannot successfully pass input into my query. I am somewhat new to node so I'm sure there's an issue in my nesting, however the error is not very helpful other than telling me "Cannot enqeue Query after invoking Quit".
I'm sure I need to store results.Client as a var or param then call it in my query but can't figure out how.
var mysql = require("mysql");
var prompt = require('prompt');
var connection = mysql.createConnection({
host: "<host>",
user: "<user>",
password: "<pw>",
database: "<db>",
port: "<port>"
});
connection.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
});
prompt.start();
prompt.get(['Client'], function (err, result) {
if (err) { console.log("Error");
return;
};
connection.query("select * from ACHLookerUpper where Client = ?", [result.Client], exports.MyHandler = function(err, rows){
if (err) {
console.log(err);
return;
}
rows.forEach(function(result) {
console.log(result.ID, result.Name, result.Client, result.ACH);
})
})
});
connection.end(function(err) {
});
prompt.get() is asynchronous, so connection.end() is getting called first and then later on you try to execute the query when input has been received for the prompt, but the connection has already ended at that point.
I am using mongodb driver for nodejs.
I am getting below error while updating a record.
{"name":"MongoError","message":"selector must be a valid JavaScript
object","driver":true}
Here is my script :
MongoClient.connect(url, function (err, db) {
if (err)
{
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collName = "bank";
var SelectParas = {"name":"ABC"};
var UpdateValues = {"name":"PQR"};
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated){
if(err)
{
console.log('err');
console.log(err);
return;
}
if(numUpdated)
{
console.log('Updated Successfully %d document(s).', numUpdated);
}
db.close();
});
});
I can write the below line in mongo console & it works.
db.bank.update({"name":"ABC"},{$set:{"name":"PQR"}})
You are passing collecion name i.e. a string as find query of the update. Need not pass collecton name there.
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated)
// collName need not pass in the update function.
Need to use
db.collection(collName).update(SelectParas,{$set:UpdateValues},function (err,numUpdated) instead.
I am trying to obtain a column name value or multiple column name values but I am not obtaining it. I am pretty new to Nodejs but debugging it is even difficult. Here is my code:
var express = require('express');
var app = express();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect', err);
} else {
console.log('Connected');
var collection = db.collection('users');
app.get('/db', function (request, response) {
collection.find({username: request.query.username, password: request.query.password}).toArray(function(err, docs) {
docs.forEach(function(doc) {
console.log(doc.toArray());
});
});
});
}
db.close();
});
I am basically authenticating if the username and password entered in db matches to my REST query and if yes then print success or redirect to a new page or something.
For starters, unless you are actually expecting more than one "user" to share the same "username" and "password" then you are better off using .findOne() for the singular response.
Then what is returned is just a plain JavaScript object, so just reference the properties:
collection.findOne(
{
username: request.query.username,
password: request.query.password
},
function(err,doc) {
if (err) throw err;
console.log( doc.username ); // Just the username value
}
);
If course if "nothing" is returned and there is no "error" then you didn't match anything with your criteria, so either "username" or "password" is wrong.
That's as the basic excercise, but really, authentication is a wheel that was built long ago and you would likely be better of implementing an existing module to handle it.
And get rid of db.close(). The functions here are asynchronous and this will execute before anything else completes. You basically never want to call this in real world applications.
I am trying to save a new Document (user) in my MongoDb and I use callback. The code runs and goes until save the user, but after that I get an error.So I can save user. I have the following code:
function saveUser(userName, socialMediaType, socialMediaID, setDocNumber, callback){
var user;
if(socialMediaType == "fbUID"){
user = new users({
userName: userName,
userEmail: 'userEmail',
teams:[],
fbUID : socialMediaID
});
}else
if(socialMediaType =="google"){
//do the same
}
var query = {}
query["'"+ socialMediaType +"'" ] = socialMediaID
users.findOne(query, function(err, userFound){
if (err) { // err in query
log.d("Error in query FoundUser", err)
log.d("User Found", userFound)
}else
if(userFound == undefined){ //if user does not exist
user.save(function(err, user){
if(err) return console.error(err);
log.d("user saved", user);
currentSession = sessionOBJ.login(user._id, socialMediaID);
callback(currentSession,"created")
});
}else{
currentSession = sessionOBJ.login(userFound._id, socialMediaID);
callback(currentSession,"logged")
}
});
}
I call the function above through this code:
f(fbUID !== undefined){
userModelOBJ.saveUser(userName,"fbUID", fbUID, function(currentSession, status) {
res.send({"status":status,
"sessionID": currentSession.sessionID,
"expires" : currentSession.date});
});
I am getting this error :
The error is in the line :
callback(currentSession,"created")
What could be the problem?
I already did many researchers but this is a specific case.
Your saveUser() call is missing the setDocNumber argument. It looks like you're not using it in your code though, so you might be able to safely remove it. If you are using it somewhere else (that you haven't shown) then you need to do some argument checking at the top of saveUser() to support optional arguments.