Mongoose + Everyauth weird behavior - mongodb

Using everyauth, when I login with a never autenticated before user on my website, the following code is launched. Checks if the user is already in my mongodb, if not it writes it. The issue right now is that works for the first authenticated user, then if a second user logins, my joiningUser._id parameters is properly initiated, but all the other parameters of my schema are from the first ever saved user, its like my parameters are never reinitialised... weird, my console.log shows the right new parameters, and not what is actually written in the database. My authentication is done via the everyauth module, I use the express framework.
exports.findOrCreateFacebookUser = function(fbUserData, promise){
User.findOne({_id:fbUserData.id}, function(err, user) {
if(err) {
console.log("Error in finding user for auth. Check Db");
promise.fail(err);
return;
}
else if(user){
console.log("User found ");
promise.fulfill(user);
}
else{
var joiningUser = new User();
joiningUser._id = fbUserData.id;
joiningUser.firstName = fbUserData.first_name;
joiningUser.lastName = fbUserData.last_name;
joiningUser.email = fbUserData.email;
//console.log(JSON.stringify(joiningUser));
joiningUser.save(function(err){
if(err){
console.log("Couldnt save new user: " + err);
promise.fail(err);
return;
}
else{
console.log("User wasnt existant, it is now created: " + JSON.stringify(joiningUser));
promise.fulfill(joiningUser);
}
});
}
});
};

Use mongoose-auth. It takes care of the combination of mongoose and everyauth for you.

There seems to be an issue with assigning _id with a forced value. So I created another id for the profile specific id (ex: facebookId).

Related

jsforce ignoring callback functions?

I tool the code right out of the docs, but it's like it completely ignores the existence is the call back functions:
var jsforce = require('jsforce');
var conn = new jsforce.Connection({
// you can change loginUrl to connect to sandbox or prerelease env.
loginUrl : 'https://ivytechfoundation--ucidev.my.salesforce.com'
});
conn.login('xxxxxx#ivytech.edu.uci.ucidev', 'xxxxxxxxTOjhPejiRZ1KWox4AmYOPzqu', function(err, userInfo) {
console.error('1');
// if (err) { return console.error(err); }
console.error(err);
console.error(userInfo);
// Now you can get the access token and instance URL information.
// Save them to establish connection next time.
console.log(conn.accessToken);
console.log(conn.instanceUrl);
// logged in user property
console.log("User ID: " + userInfo.id);
console.log("Org ID: " + userInfo.organizationId);
// ...
});
Any ideas? It never hits '1'
There seems to be a bug. I couldn't make it work either, but this works:
conn
.login(sfUserName, sfPassword + sfToken)
.then((userInfo) => { // your code here

Check for existing user doesn't go along

As the Waterline's unique attribute is ignored for MongoDB, I take up the decision to make a check for existing model entry in my code:
var username = req.param('username');
var email = req.param('email');
var asd = "";
// Do check if user already exists
User.findOne({username: username}, function (err, user) {
asd = "invalid USERNAME";
console.log(asd);
if(err){
return res.serverError('error creating user' + err);
}
if(user){
asd = "invalid USERNAME";
console.log(asd);
return res.json({status: "INVALID_USERNAME"});
}
});
User.findOne({email: email}, function (err, user) {
asd = "invalid EMAIL";
console.log(asd);
if(err){
return res.serverError('error creating user' + err);
}
if(user){
asd = "invalid EMAIL";
console.log(asd);
res.json({status: "INVALID_EMAIL"});
}
});
// Create the user
User.create({.....});
Nevertheless, I never get in the findOne methods, even though the user with the provided credentials does exist in the database. I tried debugging, and I don't get in the statement. I even put this asd variable, just to check if smth happens, but unsuccessfully. And the user keeps being created again and again, with the same credentials.
Any thoughts on what am I missing?
You need to put the create inside the callback
User.findOne(...).exec(
function(err,user){
if(!user) User.create(...)
});
But as others have commented there might not be a need for this workaround. In the issue you linked, they explain the it only happens with
migrate: safe
set either config/models.js or chosen in the command line interface.
So just set it to something else. It is enough to set it once, run sails lift, and change it back to safe if you prefer

How do I remove a user in mongoDB from the terminal by username?

My question is this: How can I remove a user from the users db by username, or at all even?
I have a meteor application with a custom registration, and when an account is created you can login and manage your account and what have you.. My problem is that, on the local host for testing, I created a few extra user accounts that I want to delete individually (not a complete reset). I am on OS X so I went to terminal, typed in 'show dbs' but users came up empty and when I typed 'show users' nothing came up. If I type 'db.users.findOne()' information appears and I can get a username and _id. I know there is users and this command shows that there is at least one but the rest of the commands indicate that I can't manage them.
Below is some code for the registration page, specifically the Accounts.createUser I'm not sure it will mater for the response but I wanted to be thorough.
Template.SignUp.events({
'submit form': function(event, template){
event.preventDefault();
var UsernameVar = template.find('#username').value;
var emailVar = template.find('#Email').value;
var passwordVar = template.find('#password').value;
var ConfirmPasswordVar = template.find('#Cpassword').value;
if(ConfirmPasswordVar == passwordVar)
{
document.getElementById("NotValid").style.display = 'none';
Accounts.createUser({
username: UsernameVar,
email: emailVar,
password: passwordVar
}, function(err, result){
if(err)
{
document.getElementById("Unavailable").style.display = 'block';
}
else{
document.getElementById("Unavailable").style.display = 'none';
}
});
}
else{
document.getElementById("NotValid").style.display = 'block';
}
}
});
I've done a lot of searching on this issue and all I've found is how to grant users the right to remove profiles but I want to do it from terminal, even when the application launches I will be the only one to be using this feature so I don't want to start giving those rights to users.
If there is anything else I should provide please let me know.
meteor mongo
db.users.find({username: "someusername"}) // ensure that your query returns the correct user that you want to remove
db.users.remove({username: "someusername"})

Logging in to firedrive using casperjs

I'm trying to log in to Firedrive using casperjs 1.1.0-beta3 with phantomjs 1.9.0. The form does not have an id so I use findone to find the form elements.
Here is the code which runs without throwing any exceptions but doesn't log in as can be seen by capturing the output (document html) and searching for the word 'anonymous'.
Any ideas would be welcome.
Run like this:
casperjs firedrive1.js http://www.firedrive.com/myfiles username password
firedrive1.js:
// Expects url, user, and password on command line.
/*jshint strict:false*/
/*global CasperError, console, phantom, require*/
var casper = require("casper").create();
var dump = require("utils").dump;
var url = casper.cli.args[0]
var user = casper.cli.args[1]
var pass = casper.cli.args[2]
// print out all the messages in the headless browser context
casper.on('remote.message', function(msg) {
this.echo('remote message caught: ' + msg);
});
// print out all the messages in the headless browser context
casper.on("page.error", function(msg, trace) {
this.echo("Page Error: " + msg, "ERROR");
});
casper.start(url, function() {
console.log("page loaded");
this.evaluate(function(user, pass) {
console.log("user: " + user);
console.log("pass: " + pass);
__utils__.findOne('#username').value = user;
__utils__.findOne('#password').value = pass;
console.log("user set to: " + __utils__.findOne('#username').value);
console.log("pass set to: " + __utils__.findOne('#password').value);
__utils__.findOne('#header_login_btn').click();
}, {user: user,
pass: pass})
});
casper.thenEvaluate(function(){
console.log("Page Title " + document.title);
console.log('doc: ' + document.documentElement.innerHTML);
});
casper.run();
The trick seems to be to separate the retrieval of the page using casper.start from the filling in of the form by putting that in a separate casper.then.
Here is an outline of what finally worked. Notice that the class of the form is different from the one I thought it was, this is because the page is actually a different page from the one I captured by hand from Firefox:
casper.start(url, function(){
// do nothing or log something
});
casper.then(function() {
this.fill('form.form-horizontal', {
'user': user,
'pass': pass
}, true);
});
casper.thenEvaluate(function(){
// check that the user name appears in the text of a link
});
It is possible that the issue is the click() which is the DOM click and likely does not work in PhantomJS. You should use the casper.click for this after the evaluate call:
this.evaluate(function(user, pass) {...}, {...})
this.click('#header_login_btn');
If this does not solve the problem you may try it with the various casper.fill functions. They work on forms and include the optional submit argument which you would set to true.
this.fillSelectors('form.il_login_form', {
'#username': user,
'#password': pass
}, true);
It looks like the selector for the login form on the firedrive page is form.il_login_form.
It is also possible that you need to include a casper.wait or casper.waitForSelector after login, if it is only an AJAX driven login.
If this still does not work, you may need to update PhantomJS to newest version (currently 1.9.7-15).

verify email using accounts.ui package

I want to send a verification email when some user is created. I use the accounts-password package, so any Accounts methods are called in my code.
I read in documentation that I need to call:
Accounts.sendVerificationEmail(userId, [email])
but the problem is that I don't know when to call it.
I tried to call in the callback function of Accounts.onCreateUser(func) but the user had not been created yet in the database.
Any ideas?
on the serverside:
Accounts.config({sendVerificationEmail: true, forbidClientAccountCreation: false});
got the answer from the comments above.
sendVerificationEmail is only available server-side. What I usually do is to use a setInterval inside onCreateUser to wait for Meteor to create the user before sending an email.
Read More: Verify an Email with Meteor Accounts.
// (server-side)
Accounts.onCreateUser(function(options, user) {
user.profile = {};
// we wait for Meteor to create the user before sending an email
Meteor.setTimeout(function() {
Accounts.sendVerificationEmail(user._id);
}, 2 * 1000);
return user;
});
You need specify mail in enviroment variables.
Then use Accounts.sendVerificationEmail(userId, [email]) in callback of Account.onCreateUser sorry for mistake and delay.
Like this (below is full example js file):
Template.register.events({
'submit #register-form' : function(e, t) {
e.preventDefault();
var email = t.find('#account-email').value
, password = t.find('#account-password').value;
// Trim and validate the input
Accounts.onCreateUser({email: email, password : password}, function(err){
if (err) {
// Inform the user that account creation failed
} else {
// Success. Account has been created and the user
// has logged in successfully.
Accounts.sendVerificationEmail(this.userId, email);
}
});
return false;
} });
if(Meteor.isServer){
Meteor.startup(function(){
process.env.MAIL_URL='smtp://your_mail:your_password#host:port'
}
}
I refered to this pages :
http://blog.benmcmahen.com/post/41741539120/building-a-customized-accounts-ui-for-meteor
http://sendgrid.com/blog/send-email-meteor-sendgrid/
How come my Meteor app with accounts package is not sending a verification email?