Creating a JSON file(MongoDb Collection) of User Info for a Node.js application that uses Bcrypt and passport for login - node.js

I'll try and word this question as short and clear as possible. I have a node.js project that connects to a non local instance of MongoDB using mongoose. I have written code for a user to login using passport module. I create a JSON file as a users collection. When I go to sign in I get this error
throw "Not a valid BCrypt hash."
So If I wanted to just create a JSON file of Users to work with this how would I go about it? My end goal is to convert RDBMS to MongoDB. Just starting with the users table. I understand that if I was registering new users I could just make a function that would hash their password like
newUser.password= createHash(password)
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
}
or something along those lines. Summary: How do I make a JSON file of user info for MongoDB that'll work with bcrypt hash and passport?

var fs = require('fs');
var bc = require('bcrypt-nodejs')
fs.readFile('users.txt',function(err,data){
var x = [];
if(err) throw err;
var buf = new Buffer(data);
x = buf.toString();
x = JSON.parse(x);
//console.log(x);
for(var a in x){
x[a].password=createHash(x[a].password);
}
x = JSON.stringify(x);
fs.writeFile('users.txt',x,callback()); //or just push directly to db?
});
var createHash = function(password){
return bc.hashSync(password, bc.genSaltSync(10), null);
}
function callback(){
console.log('finished');
}
Just read in my User Info , Bcrypted the passwords and made a new file. Put it in Mongo. Hopefully this helps someone else. If anyone has a better solution for me I'd appreciate it.

Related

How to check the collection is exist using MongoJS and Node.js

I need to check if the collection is exist in the DB using Node.js and MongoDB. Here I am using mongoJS as node driver. My code is below:
var mongoJs=require('mongojs');
var md5 = require('md5');
var dateTime = require('node-datetime');
var collections=['f_users'];
var MONGOLAB_URI="mongodb://user:*****123%40#ds127153.mlab.com:27153/fgdp";
var db=mongoJs(MONGOLAB_URI,collections);
exports.userSignup=function(req,res){
var email=req.body.email;
var password=req.body.password;
var dob=req.body.dob;
var dt = dateTime.create();
var createdDate=dt.format('Y-m-d H:M:S');
var updateDate=dt.format('Y-m-d H:M:S');
db.f_user_login
db.f_user_login.insert()
}
Here I need if collection f_user_login exist inside db or not. If not exist it will insert the required document.
I suppose that you first need to add the collection to your db.
var db=mongoJs(MONGOLAB_URI,['f_user_login', 'f_users']);
And then you can try running this
var fUserLoginExist = db.f_user_login.findOne();
if (fUserLoginExist) {
// the collection exists
} else {
// the collection does not exist
}
Hope it helps
When I wish to check an existence of collection, I use an easy piece of code below
var nmColl = "MyCollection";
if(db.getCollectionNames().find(function(el) {return el == nmColl;}) == null)
{
//do something
}
It is good for MongoDB up 3.0. At first, there is function db.getCollectionNames() to return all exists collections, when I look up specified name of collection. If there is no necessary collection, for example, I will create it.

How to store documents in an ArangoDb graph using ArangoJs?

I am using latest version of ArangoDb and ArangoJs from a nodejs application. I have got following two vertexes
users
tokens
tokens vertex contain the security tokens issues to one of the user in the users vertex. I have got an edge definition named token_belongs_to connecting tokens to users
How do I store a newly generated token belonging to an existing user using ArangoJs?
I am going to assume you are using ArangoDB 2.7 with the latest version of arangojs (4.1 at the time of this writing) as the API has changed a bit since the 3.x release of the driver.
As you don't mention using the Graph API the easiest way is to simply use the collections directly. Using the Graph API however adds benefits like orphaned edges automatically being deleted when any of their vertices are deleted.
First you need to get a reference to each collection you want to work with:
var users = db.collection('users');
var tokens = db.collection('tokens');
var edges = db.edgeCollection('token_belongs_to');
Or if you are using the Graph API:
var graph = db.graph('my_graph');
var users = graph.vertexCollection('users');
var tokens = graph.vertexCollection('tokens');
var edges = graph.edgeCollection('token_belongs_to');
In order to create a token for an existing user, you need to know the _id of the user. The _id of a document is made up of the collection name (users) and the _key of the document (e.g. 12345678).
If you don't have the _id or _key you can also look up the document by some other unique attribute. For example, if you have a unique attribute email that you know the value of, you could do this:
users.firstExample({email: 'admin#example.com'})
.then(function (doc) {
var userId = doc._id;
// more code goes here
});
Next you'll want to create the token:
tokens.save(tokenData)
.then(function (meta) {
var tokenId = meta._id;
// more code goes here
});
Once you have the userId and tokenId you can create the edge to define the relation between the two:
edges.save(edgeData, userId, tokenId)
.then(function (meta) {
var edgeId = meta._id;
// more code goes here
});
If you don't want to store any data on the edge you can substitute an empty object for edgeData or simply write it as:
edges.save({_from: userId, _to: tokenId})
.then(...);
So the full example would go something like this:
var graph = db.graph('my_graph');
var users = graph.vertexCollection('users');
var tokens = graph.vertexCollection('tokens');
var edges = graph.edgeCollection('token_belongs_to');
Promise.all([
users.firstExample({email: 'admin#example.com'}),
tokens.save(tokenData)
])
.then(function (args) {
var userId = args[0]._id; // result from first promise
var tokenId = args[1]._id; // result from second promise
return edges.save({_from: userId, _to: tokenId});
})
.then(function (meta) {
var edgeId = meta._id;
// Edge has been created
})
.catch(function (err) {
console.error('Something went wrong:', err.stack);
});
Attention - syntax changes:
Edge creation:
const { Database, CollectionType } = require('arangojs');
const db = new Database();
const collection = db.collection("collection_name");
if (!(await collection.exists())
await collection.create({ type: CollectionType.EDGE_COLLECTION });
await collection.save({_from: 'from_id', _to: 'to_id'});
https://arangodb.github.io/arangojs/7.1.0/interfaces/_collection_.edgecollection.html#create

Cannot verify Hashed password in Express using Node js

This is how i Hash and store my password in the Database.
NEWUSER FUNCTION
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(password, salt);
var query="INSERT into user(email,firstname,lastname,logintime,gender,password) VALUES('"+email+"','"+firstname+"','"+lastname+"','"+logintime+"','"+gender+"','"+hash+"')";
This is how i retrieve and check to authenticate
VALIDATE FUNCTION
var query = "SELECT password from user where email='" + email + "'";
connection.query(query,function(err,result){
if(err)
{
console.log("ERROR:"+err.message);
}
else
{
if(result.length!==0)
{
var hash=JSON.stringify(result[0].password); console.log(hash);
console.log(bcrypt.compareSync(password,hash ));
if(bcrypt.compareSync(password, hash)) { callback(err, result); }
This always shows false but if i do it this way it shows the expected result
var hash = bcrypt.hashSync("sacjap", 8);
//var hash=JSON.stringify(result[0].password);
console.log(hash);
console.log(bcrypt.compareSync(password,hash ));
if(bcrypt.compareSync(password, hash))
{
callback(err, result);
}
So the problem is that whenever i get the password from the database its not working. PLZ Help
First of all, my answer is based on the documentation I found here:
https://github.com/davidwood/node-password-hash
It seems that the password-hash module tries to call the 'split' function on the second argument you provided to the 'verify' function, assuming it is a string (JavaScript String split function on MDN). I think you should check the type of your 'result' variable, it looks to me like a more complex query result object returned by your database. Your provided code doesn't give me more information about what type of connection you are using here, so I can't give you a more specific answer. My approach would be to find out how to get a plain string from your 'result' variable, which then would represent the hashed password you can hand over to 'verify'. This is just a wild guess, I hope this little hint helps you to solve your problem.
Side note: The module you are using for password hashing appears to be deprecated, maybe you should look out for an alternative.

How do I generate a session ID in Node.js?

Im trying to learn Node.js without using any third party modules or frameworks. I'm getting to the point where I got to figure out how to give session ids to users who login...
So far I know I can set the session id by writing it in the headers, setting the cookies:
writeHead(200, {'set-cookie':'Math.random() ' } );
and then I can retrieve the session id and later compare it to the database.
request.headers.cookie(request.url);
But how do I GENERATE the session ID value? I am new to programming. The first thing I thought of was using Javascript's Math.random(); and using that value to set the cookie ( session id ). In my mind it feels stupid but that is how far I can think.
How am I suppose to generate the session id using Node.js, no third party modules, barebones please!
Note: You should probably use a session manager for whatever framework you go with.. be it connect, express, koa or any number of others.
This will give you a UUID version 4 (random) using crypto.randomBytes.
var crypto = require('crypto');
module.exports = genUuid;
function genUuid(callback) {
if (typeof(callback) !== 'function') {
return uuidFromBytes(crypto.randomBytes(16));
}
crypto.randomBytes(16, function(err, rnd) {
if (err) return callback(err);
callback(null, uuidFromBytes(rnd));
});
}
function uuidFromBytes(rnd) {
rnd[6] = (rnd[6] & 0x0f) | 0x40;
rnd[8] = (rnd[8] & 0x3f) | 0x80;
rnd = rnd.toString('hex').match(/(.{8})(.{4})(.{4})(.{4})(.{12})/);
rnd.shift();
return rnd.join('-');
}
You could also use the UUID module from npm. The crypto package is not an in-browser option, though you could use Browserify's crypto shim.

why client.smembers is not returning any members?

im currently working on a chat application for the backend.here once we do /chat we are shown our friend list, from which we can start a conversation with anyone.in order to display the list of friends, i used smembers but its not returning any members even when i have friends added to my account.
app.get('/chat', utils.restrict, function(req,res){
client.smembers('appname:users' + req.user.id + ':friends', function(err, members) {
if (members && members.length > 0) {
res.render('chat', {user: req.user, users : members});
}
else{
res.send("No Friends Found!");
}
});
});
when i debug this, i see that the client.smembers line of code is hit but after that the value of members is given 0.i have required all of these too:
var app = module.parent.exports.app
, ACS = module.parent.exports.acs
, client = module.parent.exports.client
, passport = require('passport')
, config = require('../config')
, utils = module.parent.exports.utils;
what am i doing wrong?
At last, after spending a lot of time i found out that the problem was with the database instance i was querying.I created a new instance of redis which did not have the data i wanted. i used redis-cli which is the command line interface utility to talk with Redis.

Resources