Meteor Server: ReferenceError: calcMD5 is not defined - javascript

Due to some existing mongodb structure. I cant use Meteors Meteor.user. So when I try to insert new user calcMD5 says is not defined. How do I convert Md5 in meteor server? I dont know weather my approach is good or not. correct me if am wrong.
if (Meteor.isServer) {
newUser: function(email, password){
Users.insert({"emailid":email,"password":calcMD5(password)});
}
});
Here the template code
Template.signInWithEmail.events({
'click .btn-create-account': function(event, template) {
email = $('[name="emailAddress"]').val();
password = $('[name="password"]').val();
//Create new user
Meteor.call("newUser", email, password, function(error, result) {});
}

Problem is, the calcMD5 function does not exist in Meteor as it is. (nor JavaScript, nor NodeJS) I will assume you want to use this library or another one for your project.
If you want to be able to use an external library, you have to first add it into your Meteor project. You can do this by simply putting the javascript file in a folder such as server/lib/.
Or, if this gets too complicated, just add the crypto-md5 meteor package using:
meteor add jparker:crypto-md5
and call CryptoJS.MD5(password) instead of your calcMD5(password) function call.

Related

Is this way to access mongodb in node.js acceptable?

I am new to programming and trying to experiment a bit, still struggling with the best way to access mongoDB from within my code. I've seen a few posts here on stack overflow but they more or less all require that the code required to load mongo is included in each and every .js file. I would like to avoid that in order to keep the code for accessing my DB in only one file.
Note that I am using the "mongo-factory" module.
Would the code below be acceptable?
I've created what I would call a "producer" of database objects, database.js
var mongoFactory = require('mongo-factory');
function Database(close,callback) {
mongoFactory.getConnection(<connection string>).then(function (database) {
callback(database.db(<db name>));
if(close) database.close();
}).catch(function (err) {
console.error(err);
});
}
module.exports = Database;
Then when I want to access the database from any of my files I could do the below, avoiding to introduce db-specific parameters and the mongo-factory requirement in here:
var Database = require('./database');
var callback_actOnDatabase = function (db) {
db.collection..... do something here
};
var d = new Database(false, callback_actOnDatabase);
instead of mongo-factoy use mongoose module to connect the database,model declaration also we dont intalise the db parameters again,please go through the link
https://www.npmjs.com/package/mongoose

Update context variables using .js. Its possible?

i'm trying to send a user name to my WCS but i not sure how can i do that using a request. My consersation ask for the user email and use a js script to return a json from my sql server...
I'm doing something like that:
What's your email? // WCS
caique.rodrigues#test.com //USER
Just a minute.<script>getUserInformation('caique.rodrigues#test.com');</script> // WCS
nodeTrue //USER (I sent this after confirmated if the user exist and got the user name.)
Hi <span id='myText'></span><script>document.getElementById('myText').innerHTML = userName;</script>! //WCS
I know this is not the best way to do that but it is working. I'm trying to call my js functions using something like "output:{'action':}" (And handle it in my node.js like the 'car dashboard sample'), but, it's possible send a varible from my .js to a conversation context?
I had the same problem a few months ago. In this case, I used functions for access the context variables on the client side (Using this example from Ashley and accessing the context), but, for security issues of some company data, I did need to use custom code in the server-side... And, for this case, you can use the method call for Watson Conversation, and access the context variables and creates values with custom code in your favor.
Something like this:
conversation.message(payload, function (err, data) {
data.context.yourValue = returnFromYourDatabase;
if (err) {
return res.status(err.code || 500).json(err);
}
updateMessage(payload, data, req, res);
});
});
You can see the function updateMessage, this call is one example from IBM Developers, and this function is used to update the message in every request. You can use this function to set too, because this function get the parameters from the call.
For example:
function updateMessage(input, response) {
response.context.yourValue = returnFromYourDatabase;
var responseText = null;
if (!response.output) {
response.output = {};
}
}
See API Reference for Watson Conversation Service using Node.js.
See the Project with Node.js by IBM Developers.

Node.js and mongodb access mongodb

I'm trying to set up mongodb on Windows 8 using node.js, Does anyone know why im getting this error. C:\users\phill\node_modules\mongodb\lib\mongodb\mongo_client.js:359 it also says at collection = db collection,,, can't call method 'collection' of null. I'm having a hard time setting it up. My goal is to be able to add to mongo db, and see that I add or pull up what I added, but adding something is good enough for me for now. I'm trying every thing I can find, even straight from the website, I tried everything I see on here as well. Think it maybe it's the way I have things set up. My node.js is saved in my c: drive there is a file that says, program files(86x) in there I have node_modules, npm and such. The path ends up being, computer > windows (C:) > program files(86x) > nodejs. My Mongodb is saved right on my C: drive the path end up being windows (C:) > mongodb-win32-x86_64-2008plus-2.4.8. In my C: I also created a file data and in it created another db. I have been told i should just use mongoose, I'm just learning so i open to any advice, links or anything that will help. I have one last question as well, i learned php and then found out about sql injections and stuff like that, i am not seeing anything about security at all, should i expect the same as well. For this i get text not defined, but i have been getting errors with everthing i have done, best i did was get stuck on a right concern screen.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, db) {
test.equal(null, err);
test.ok(db != null);
db.collection("replicaset_mongo_client_collection").update({a:1},
{b:1}, {upsert:true}, function(err, result) {
test.equal(null, err);
test.equal(1, result);
db.close();
test.done();
});
});
Tried this as well and getting a error,C:\users\phill\node_modules\mongodb\lib\mongodb\mongo_client.js:359.... at collection = db collection,,, can't call method 'collection' of null. im calling it in command prompt node filename.js I'm saving it where my node.js file is, I have pulled up files before and created a server.
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
var db = new Db('test', new Server('localhost', 27017));
// Fetch a collection to insert document into
db.open(function(err, db) {
var collection = db.collection("simple_document_insert_collection_no_safe");
// Insert a single document
collection.insert({hello:'world_no_safe'});
// Wait for a second before finishing up, to ensure we have written the item to disk
setTimeout(function() {
// Fetch the document
collection.findOne({hello:'world_no_safe'}, function(err, item) {
assert.equal(null, err);
assert.equal('world_no_safe', item.hello);
db.close();
})
}, 100);
});
In your first code example, you said:
For this i get text not defined
I assume you meant "test not defined?" Your script only requires the mongodb library, and I don't believe test is a core nodejs function, so that would explain the error.
To reference the driver documentation for db.collection(), an assert library is used, but also properly imported (as you did in your second example).
Within your callback to db.open(), you don't check if an error occurred. That might shed some light on why db is null in that function.
Regarding your question about the equivalent of SQL injection with MongoDB, the main areas of concern are places where you might pass untrusted input into evaluated JavaScript, or using such input to construct free-form query objects (not simply using a string, but more like dropping an object into your BSON query). Both of these links should provide more information on the subject:
What type of attacks can be used vs MongoDB?
How does MongoDB address SQL or Query injection?

Meteor collection not updating subscription on client

I'm quite new on Meteor and Mongo and even if I don't want it, I need some relations.
I have a Collection called Feeds and another called UserFeeds where I have a feedid and a userid, and I publish the user feeds on the server like this:
Meteor.publish('feeds', function(){
return Feeds.find({_id:{$in:_.pluck(UserFeeds.find({user:this.userId}).fetch(),'feedid')}});
});
I find the user on UserFeeds, fetch it (returns an array) and pluck it to have only the feedid field, and then find those feeds on the Feeds collection.
And subscribe on the client like this:
Deps.autorun(function(){
Meteor.subscribe("feeds");
});
The problem is that when I add a new feed and a new userfeed the client doesn't receive the change, but when I refresh the page the new feed does appear.
Any idea of what I'm missing here?
Thanks.
I've run into this, too. It turns out publish functions on the server don't re-run reactively: if they return a Collection cursor, as you're doing (and as most publish functions do), then the publish function will run once and Meteor will store the cursor and send down updates only when the contents of the cursor change. The important thing here is that Meteor will not re-run the publish function, nor, therefore, the Collection.find(query), when query changes. If you want the publish function to re-run, then the way I've done it so far is to set up the publish function to receive an argument. That way the client, whose collections do update reactively, can re-subscribe reactively. The code would look something like:
// client
Meteor.subscribe('user_feeds');
Deps.autorun(function(){
var allFeeds = UserFeeds.find({user: Meteor.userId()}).fetch();
var feedIds = _.pluck(allFeeds,'feedid');
Meteor.subscribe('feeds',feedids);
});
// server
Meteor.publish('feeds',function(feedids) {
return Feeds.find({_id: {$in: feedids}});
});
I believe the Meteorite package publish-with-relations is designed to solve this problem, although I haven't used it.
EDIT: I believe the publish function will re-run when the userId changes, which means that you can have a server-side check to make sure the user is logged in before publishing sensitive data.
I think your problem is that .fetch() which you use here…
UserFeeds.find({user:this.userId}).fetch()
…removes the reactivity.
.fetch() returns an array instead of a cursor, and that array won't be reactive.
http://docs.meteor.com/#fetch
try this ...
Meteor.autosubscribe(function(){
Meteor.subscribe("feeds");
});
and in the Template JS ...
Template.templateName.feeds = function()
return Feeds.find() # or any specific call
};
in the HTML ...
{{#each feeds}}
do some stuff
{{else}}
no feed
{{/each}}
You can use the reactive-publish package (I am one of authors). It allows you to create publish endpoints which depend on the result of another query. In your case, query on UserFeeds.
Meteor.publish('feeds', function () {
this.autorun(function (computation) {
var feeds = _.pluck(UserFeeds.find({user: this.userId}, {fields: {feedid: 1}}).fetch(), 'feedid');
return Feeds.find({_id: {$in: feeds}});
});
});
The important part is that you limit the UserFeeds fields only to feedid to make sure autorun does not rerun when some other field changes in UserFeeds, a field you do not care about.

Can node.js execute JavaScript functions pulled from CouchDB like CouchApp does? How?

The quick overview is this: for my web app I can write most of my functionality using CouchApp and CouchDB views, etc. I love the feature of CouchApp that pushes my code up to the server via replication- this makes the deployment cycle very easy.
However, to do some arbitrary work not supported in couchdb and works around a few limitations, I need to put a web platform in front of CouchDB. I'm considering building this in node.js because it uses JavaScript and I want to continue the easy deployment method of pushing code into the database.
Here's how i imagine it working:
- I write a web server/service in node.js using the normal method and the node command to start it.
- this sevice connects to couch db and gets a virtual list and a URL mapping list. This list is stored in redis for quick lookup. This list will tell the server, when it gets a request, based on host and path, etc, which handler is to be run.
- the server fetches the handler- which is just a document, it could be a design document or an arbitrary json document in couchdb. And then executes that handler to handle the request, as if I'd writte the handler as part of node js.
So the question is, how to get a son data structure that contains a JavaScript function in it, in text form, and execute that function?
This may be blindingly obvious, but i come from a compiled background, so normally there would be a compilation step here that makes this pretty much impossible.
So, what I'm thinking is in pseudo code:
Var string thecode = getValueForMapKey(handlerFunctionIWant);
somehowmagicallyexecute(thecode)
Is there an exec or run function that will do the magical execution step above in JavaScript?
It will run in the node.js context.
You can also use it in node, like this, as a dynamic function:
var cradle = require('cradle');
var db = new(cradle.Connection)().database('db_name');
db.get('_design/node%2Fyour_code', function (err, doc) {
if (!err){
var your_code = new Function(doc['arguments'].join(','), doc.code);
your_code("cool", "also cool");
}else{
console.error('error:', err);
}
});
make your docs look like this:
{
"_id": "_design/node/your_code",
"arguments": [
"nameOfArg1",
"nameOfArg2"
],
"code": "console.log('arg1', nameOfArg1); console.log('arg2', nameOfArg2);"
}
It's in the same scope as where the new Function is called, so you have access to cradle, or you can require other libs, which will be loaded as if it was an anon function in that scope.
Put it in a design doc, then only admin can make changes, out of the box.
Here is a nicer, but similar approach:
// Format, in db:
doc = {
"_id": "_design/node",
"your_function_name": {
"arguments": [
"nameOfArg1",
"nameOfArg2"
],
"code": "console.log('arg1', nameOfArg1); console.log('arg2', nameOfArg2);"
},
"your_other_function_name": {
"arguments": [
"name"
],
"code": "console.log('hello', name, 'how\\'s it going, bro?');"
}
};
var cradle = require('cradle');
var db = new(cradle.Connection)().database('db_name');
function run_from_db(name, args){
db.get('_design/node', function (err, doc) {
if (!err){
if (doc[name] !== undefined){
var fn = new Function(doc[name]['arguments'].join(','), doc[name].code);
fn.apply(fn, args);
}else{
console.error("could not find", name, "in _design/node");
}
}else{
console.error(err);
}
});
}
run_from_db('your_other_function_name', ['konsumer']);
this will output:
hello konsumer how's it going, bro?
eval(handlerFunctionIwant) is the call to execute it. You need to make sure that there's no way for hackers to inject code into that string, of course.
It is not clear to me if this will evaluate it in a context that has access to other javescript resources, such as the rest of node.js or access to your couchdb library.

Categories

Resources