NodeJS and Passport signup not working - no error - javascript

I have published the current version on github: https://github.com/rcbgit/boiler
The user seems to be "logging in". At least the successful redirect happens with valid username/pw and the failure redirect happens with a bad combo. The problem I'm having is that I don't know how to store the user information after the login or validate a page against it (restrict access). I created a basic 'Auth' service that stores the user information but i'm not sure how to use it properly.
I'm also having trouble figuring out how to handle messages back from the server such as "Username already exists!".
Any advice is appreciated!

A couple of things:
1) I assume the flash messages not showing up so well. I had issues with that too, so I reverted to using the session itself to pass the messages. Here is what I did instead that worked just fine:
I changed the req.flash to this:
req.session.signUpMessages.push('That email is already taken.');
then changed in my template to display this variable if it exists, works like a charm.
2) I think you can and should remove the process.nextTick, it's great when you're doing authentication against external APIs that might take a long time, in this case it's more of an overkill IMO. I would remove it.
3) and last but not least, I think you're missing curley brackets..
if (err)
console.log(err);
return done(err);
^^^^^^^^^^^^^^^^
this get's called each time, that's not what you want...:)
should be turned to this:
if (err) {
console.log(err);
return done(err);
}
Try these changes, see if that solves the problems?

Related

Proper & Sustainable way of Error Handling in Node/Express API Routes

I've written a few MEAN Stack applications and set up API's but I've always had some level on confusion on whats the best way to handle errors inside an API Routes.
Please do correct me if I explained something wrong or my thinking/concept are flawed. I am explaining what I think is right. just trying to be a better programmer.
When I say errors I mean the following scenarios:
A General error, something you did not predict has happened and needs to be handled, maybe the server is down or the server is overloaded, basically anything that we can't predict that might happen. This type of error mostly is handled here "I think" (see comments below in code):
app.get('/user', isLoggedIn, function(req, res){
User.find(_id, function(err, user){
// HERE I am not sure how to handle this, Maybe we can't reach the DB or anything else could have happened. How do you handle this error so no matter what kind of error it is we can handle it gracefully and the app doesnt crash and we don't lose value data and the user is made aware of the issue.
if(err)
I have seen different ways how people have managed the above error here are a few examples:
if(err)
// I think this is wrong! Maybe okay for development but not for deployment
console.log("The Error is " + err);
if(err)
// Again I think not a good way of handling error because doesn't provide the system or the front-end user with any useful data.
throw err;
if(err)
// Not Sure
res.send(err);
if(err)
res.json(err);
So the above was when we can't predict what kind or when error might occurs but there also another type see below
So lets says we passed the above if(err) stage and went to the else, this is where we CAN predict the errors because this is where User interaction comes into play. For example continuing the example above (see comments in code):
app.get('/user',isLoggedIn,function(req, res) {
User.find(_id, function(err, user) {
if (err){
// NOT SURE WHAT TO DO HERE
}
// HERE lets say the user we are trying to get does not exist, now this is something we can predict, how to handle this not only gracefully so we don't crash the app but also provide the front end user with some useful information.
else if(!user){
}
else if(user){//Do what you were meant to do!}
});
})
Now how I usually manage this type of error is by sending back some information to the front-end user like so:
return(res.json({message: "The user you are trying to find does not exist, contact the system admin please."}));
I send back some JSON data and display on the front end inside a div or an alert box etc.
So these are the two "kinds" or a better word "situations" of errors I deal with. Whats the best way of dealing with them so they the app can manage itself without crashing but also making sure the front-end user knows whats going on so they know their next step. And what are the best practices for handling errors in API's.
I prefer use next and custom Error
Next
app.get('/user', isLoggedIn, function(req, res, next){
User.find(_id, function(err, user){
if (err)
return next(err); // Forwarding error to error-middleware
...or...
throw new Error('Cause'); // If error is critical for app and app must be stopped
...
});
In Error-middleware we can choose how much info send to console/user and how present info
// Detect current environment
if (req.app.get('env') != 'development') {
...
}
// Detect request type
if (req.xhr)
req.json(...)
else
res.render('error.html', ...);
Custom Error
In example above you can throw AuthorizeError and forwarding it by next. More about custom error read here. Imho it's excessively for small application.

Meteor Twilio SMS functionality issue and animate percentile JS query

Please see attached and kindly assist. Trying to add SMS functionality to a project but I'm getting a "Twilio is not defined error". What am I missing? Also, in terms of the code for the send button, where to I add my user ID, inside the Meteor call?
Then, as a completely unrelated query, with reference to the animated percentile code example, I was wondering if one could use different kinds of custom classes for this effect, say, a glass that appears to "fill up" based on % completeness out of a 100%. Further, could one state that multiple conditions had to be met before this percentage changes? i.e. X amount of forms filled out and X types of tasks assigned to another user in like a project management type app? (hope I'm being clear enough on this)
Your assistance is appreciated.
Twilio developer evangelist here.
Quick bit of StackOverflow advice first. It's best to stick to one question per question. I'm not sure of the percentcircle question you're asking, but I can help with Twilio! I'd recommend editing this question to just the Twilio one and asking the other question in a new question on SO.
Anyway, onto helping you!
Meteor doesn't play nicely with normal npm modules, so you can't just require the Twilio npm module. However, you are in luck as sending an SMS with Twilio is pretty straightforward without the library too.
This code is adapted from Chris Hranj's blog post on the Twilio site about creating a group messaging app with Twilio and Meteor. It uses the HTTP module from Meteor to make a POST request to the Twilio API. Chris also recommends keeping your Twilio credentials in the environment so that they don't get exposed by your Meteor front end.
Meteor.startup(function() {
Meteor.methods({
'sendSMS': function(phoneNumber, message) {
HTTP.call(
"POST",
'https://api.twilio.com/2010-04-01/Accounts/' +
process.env.TWILIO_ACCOUNT_SID + '/SMS/Messages.json', {
params: {
From: process.env.TWILIO_NUMBER,
To: phoneNumber,
Body: message
},
// Set your credentials as environment variables
// so that they are not loaded on the client
auth:
process.env.TWILIO_ACCOUNT_SID + ':' +
process.env.TWILIO_AUTH_TOKEN
},
// Print error or success to console
function (error) {
if (error) {
console.log(error);
}
else {
console.log('SMS sent successfully.');
}
}
);
}
})
})
Check out the post for more details.

BreezeJs: SaveChanges() server response getting dropped

I have breezeJs running in an angular app on mobile device (cordova), which talks to .Net WebApi.
Everything works great, except once in a while the device will get PrimaryKey violations (from my SQL Server).
I think I narrowed it down to only happening when data connection is shakey on the device.
The only way I can figure these primary key violations are happening is somehow the server is Saving Changes, but the mobile connection drops out before the response can come back from server that everything saved OK.
What is supposed to happen when BreezeJS doesn't hear back from server after calling SaveChanges?
Anyone familiar with BreezeJS know of a way to handle this scenario?
I've had to handle the same scenario in my project. The approach I took was two part:
Add automatic retries to failed ajax requests. I'm using breeze with jQuery, so I googled "jQuery retry ajax". There's many different implementations, mine is somewhat custom, all center around hijacking the onerror callback as well as the deferred's fail handler to inject retry logic. I'm sure Angular will have similar means of retrying dropped requests.
In the saveChanges fail handler, add logic like this:
...
function isConcurrencyException(reason: any) {
return reason && reason.message && /Store update, insert, or delete statement affected an unexpected number of rows/.test(reason.message);
}
function isConnectionFailure(reason: any): boolean {
return reason && reason.hasOwnProperty('status') && reason.status === 0
}
entityManager.saveChanges()
.then(... yay ...)
.fail(function(reason) {
if (isConnectionFailure(reason)) {
// retry attempts failed to reach server.
// notify user and save to local storage....
return;
}
if (isConcurrencyException(reason)) {
// EF is not letting me save the entities again because my previous save (or another user's save) moved the concurrency stamps on the record. There's also the possibility that a record I'm try to save was deleted by another user.
// recover... in my case I kept it simple and simply attempt to reload the entity. If nothing is returned I know the entity was deleted. Otherwise I now have the latest version. In either case a message is shown to the user.
return;
}
if (reason.entityErrors) {
// We have an "entityErrors" property... this means the saved failed due to server-side validation errors.
// do whatever you do to handle validation errors...
return;
}
// an unexpected exception. let it bubble up.
throw reason;
})
.done(); // terminate the promise chain (may not be an equivalent in Angular, not sure).
One of the ways you can test spotty connections is to use Fiddler's AutoResponder tab. Set up a *.drop rule with a regex that matches your breeze route and check the "Enable Automatic Responses" box when you want to simulate dropped requests.
This is a somewhat messy problem to solve- no one size fits all answer, hope this helps.
NOTE
Ward makes a good point in the comments below. This approach is not suitable in situations where the entity's primary key is generated on the server (which would be the case if your db uses identity columns for PKs) because the retry logic could cause duplicate inserts.

Firebase error after logout

I'm currently developing a little Website with Firebase. I got a couple of HTML files and each file contains a logout button which calls the function
function logout(){
auth.logout();
console.log("logout successfull");
location.href="index.html";
}
After getting redirected I tried to login again but it always failed with the following error message:
Error: FirebaseSimpleLogin: An unknown server error occurred.
It took me some time to realise that the redirection to the index page caused the problem. When I delte the location.href="index.html"; line, everything works fine.
Problem is, I really need something that redirects me to the front page, when the user isn´t loged in. Is this a known problem and/or can someone come up with a solution to this problem?
Thanks in advance :)
PS.: I realised that I could "fix" the problem (after getting redirected to the index page) when I cause an error (f.e. calling a undefined function). Idk if this information helps...
Ok, thanks for your reply Kato!
I changed quite a lot, since I started the "project". Instead of using mutliple HTML files I copied everything into the index.html and work now with mutliple (hidden) DIVs.
But unfortunatly, the problem still exists.
I offer two different Login possibilites. One with Facebook (works 100% of the time for me) and one with the SimpleLogin (works barely).
I´m pretty sure I did the initialization the same way like it´s done in the tutorials on firebase.com.
This is how I connect to the Firebase DB
var ref = new Firebase('https://partyfinder-db.firebaseio.com/');
var auth = new FirebaseSimpleLogin(ref, function(error, user) {
if (error) {
// an error occurred while attempting login
alert(error);
} else if (user) {
// Here I work with user.id etc.
} else {
// user is logged out
}
});
And that is how I try to login the user...
function login() {
//I probably should use jQuery here...
var _email = document.getElementById("emailLogin").value;
var _pw1 = document.getElementById("passwordLogin").value;
var _rememberMe = document.getElementById("rememberMe").checked;
auth.login('password', {
email: _email,
password: _pw1,
rememberMe: _rememberMe
});
showMain(); //Hide and show DIVs and stuff...
}
I call this function on the SignIn Button. The whole Javascript file is linked in the head part of the HTML file.
So, calling this function is normally causing the following error
Error: FirebaseSimpleLogin: An unknown server error occurred.
I already figured out that this message only shows up when the connection to the DB already was successful. For example, when I type in an invalide email adress, the following message appears:
Error: FirebaseSimpleLogin: The specified user does not exist.
There are a few things that can "fix" the problem. For example, when I use the Facebook Login and logout after this was successful, I can sign in using firebase simpleLogin. Sometimes (unfortunatly not always) it helps when I`m causing an error, f.e. calling a non existing function. After the error message is displayed in the console, I can continue logging in (successfully).
But to be honest I`ve absolutly no idea what this tells me about the error and if this is somehow a hint to the solution. I also tried to set some breaking points and debug through the relevant code (using google chrome) but didn´t find anything.
I uploaded the page to a free webspace, where you can test this whole thing by yourself.
But please note, this project is just for testing purpos. I´m not planning to release it somehow, it´s just for me to figure out multiple things and I find it easier to learn something when I can set it in a context. I´m pretty sure it´s quite bad coded and contains many mistakes, etc. But I´m always grateful for feedback beside the actual problem :)
For the login you can use
email: user#email.com
password: user
If you use the FB-Login, your Name and your email adress will be saved to the Database (but I can delete this section of the code if you want/need to use it and feel uncomfortable about it).
http://partyfinder.lima-city.de/
Most of the comments are in german, sorry for that...

Facebook Connect Javascript API failing to maintain connected state after page reloads

I have a Facebook Connect site using the Javascript API - I'm not using any FBML tags. It was working fine until a couple of days ago and now I have a problem with reloading the page while the user is logged in.
The user can log in fine, and I can get the user's Facebook ID. They can refresh the page and they're still logged in (and I still get the ID). But if they refresh the page again (and subsequently), then FB.Connect.get_loggedInUser() always returns 'None', rather than the Facebook ID, even though FB.Connect.get_status().waitUntilReady() has said they're logged in.
Here's my basic code... can anyone see anything wrong?
FB_RequireFeatures(['Api'], function() {
FB.init('MY_API_KEY', '/xd_receiver.htm', {});
FB.ensureInit(function() {
FB.Connect.get_status().waitUntilReady( function( status ) {
switch (status) {
case FB.ConnectState.connected:
FB.Connect.requireSession(function() {
if (FB.Connect.get_loggedInUser()) {
var uid = FB.Connect.get_loggedInUser();
// Some more stuff here with the user's ID, displaying info in the page, etc.
}
}
break;
case FB.ConnectState.appNotAuthorized:
case FB.ConnectState.userNotLoggedIn:
// Display FB Connect button in page.
}
});
});
});
Is there something wrong with that? I can't work out how to ensure I get the user's logged in ID. Many thanks.
So, after much testing with various apps and domains and... it seems there was some conflict going on between the JavaScript Facebook code and some pyFacebook code in the Django back-end. Some confusion between the sessions stuff (yet to be figured out) was causing Safari to throw errors. So, we don't know the solution, but the JavaScript code above should, on its own, work fine.

Categories

Resources