Socket.IO - Callback to user who emited only - javascript

I am making a chat application which requires users to log in, I have so far managed to get the login system working by using UserApp.io, but I cant seem to find a way which would send a "Callback" back to the user who has emited the information to the server.
So for index.html, when a login form is submitted, it would gather the values of the two fields and emit the data to the backend.
$('form#login').submit(function() {
var data = {};
data.email = $("#login_email").val();
data.password = $("#login_password").val();
socket.emit('user login', data);
});
In the index.js file, it receives the details and checks using the UserApp API that the user is valid and all the details are correct. It also retrieves information like the first and last name.
socket.on('user login', function (user) {
logger.info('Receiving login info for "' + user.email + '"...');
UserApp.User.login({"login": user.email, "password": user.password}, function (error, result) {
if (error) {
logger.error('Login failed: ' + error.message);
} else {
var userToken = result.token;
var userID = result.user_id;
console.log("User has logged in.");
UserApp.User.get({
"user_id": userID
}, function (error, result) {
if (error) {
logger.error(error.message);
} else {
logger.info(result[0]['first_name'] + " " + result[0]['last_name'] + " Has logged in!")
}
});
}
});
});
So here is my issue. I cant seem to find a way of giving a callback to index.html so it can show errors like "Incorrect username".
So is there a way of giving a callback to one person, more specificly, the person who submitted the login form?
Any help would be appreciated.
Thanks.

socket.io has acknowledgement callbacks, here are the docs
http://socket.io/docs/#sending-and-getting-data-(acknowledgements)
Add a callback function as the third argument when emitting
$('form#login').submit(function() {
var data = {};
data.email = $("#login_email").val();
data.password = $("#login_password").val();
socket.emit('user login', data, function (result) {
console.log(result);
});
});
and then the callback function server side can have an additional parameter which is the callback you defined when emitting
socket.on('user login', function (user, callback) {
logger.info('Receiving login info for "' + user.email + '"...');
UserApp.User.login({"login": user.email, "password": user.password}, function (error, result) {
if (error) {
logger.error('Login failed: ' + error.message);
} else {
var userToken = result.token;
var userID = result.user_id;
console.log("User has logged in.");
UserApp.User.get({
"user_id": userID
}, function (error, result) {
if (error) {
logger.error(error.message);
} else {
logger.info(result[0]['first_name'] + " " + result[0]['last_name'] + " Has logged in!")
return callback('your results');
}
});
}
});
});

Related

Can't get user stored in Express.js session

I have this code:
app.post('/api/command', function (req, res, next) {
var clientCommand = req.body.command;
console.log("ClientCommand: ", clientCommand);
if (!req.session.step || req.session.step === EMAIL) {
// find user in db with email
users.findOne({email: clientCommand}, function (err, result) {
if (err) {
return console.log("error: ", err);
}
console.log("result: ", result.email);
// if user exists add user in session
if (result != null) {
req.session.user = result;
}
});//.catch(console.log);
console.log("session outside: ", req.session.user);
// change step to password
req.session.step = PASSWORD;
}
The problem is I want to access req.session.user outside users.findOne(...). But the output is:
ClientCommand: example#gmail.com
session outside: undefined
Any help will be appreciated.
P.S. Also, I would like to know how express-session works and how it stores data in cookies (or on server-side).
Findone is a async command due to which you are getting undefined.
Even if you will notice
"session outside:" is coming first
only after that "result: " console will come.
So if you have to move code inside findone or use custom middleware where you can execute query.
use this type of code in app js before calling routes
app.use(function(req,res,next){
users.findOne({email: clientCommand}, function (err, result) {
if (err) {
return console.log("error: ", err);
}
console.log("result: ", result.email);
// if user exists add user in session
if (result != null) {
req.session.user = result;
next(); // After setting user , route will call
}else{
next(); // will allow to go to route even if no user found
}
});//.catch(console.log);
})
if you want to call it at particular url then use
app.use("[your url]",function(req,res,next){

parse-server js can't login user, even though registration goes through and logs user in

I'm currently building a parse-server app with vuejs + vuex on the front end.
I am able to register an account(and once registered the user is logged in) with this code:
REGISTER_USER (state, username, email, password) {
var user = new Parse.User()
user.set('username', username)
user.set('password', password)
user.set('email', email)
user.signUp(null, {
success: function (user) {
state.currentUser = user
},
error: function (user, error) {
state.registerError = error
}
})
}
but if I log the user out and try to log them in with:
LOGIN_USER (state, email, password) {
Parse.User.logIn(email, password, {
success: function (user) {
state.currentUser = user
},
error: function (user, error) {
state.loginError = error
console.log('error logging in: ' + JSON.stringify(error) + ' userobject: ' + JSON.stringify(user))
console.log('current user: ' + JSON.stringify(Parse.User.current()))
}
})
}
I get {"code":101,"error":"Invalid username/password."}
I've confirmed that the proper username and password is reaching the function, but then it goes south somehow. any help would be greatly appreciated.
Finally figured it out. There are 2 available methods for login, tried the other one and worked perfectly
https://parse.com/docs/js/api/classes/Parse.User.html#methods_logIn
var user = new Parse.User()
user.set('username', username)
user.set('password', password)
user.logIn({
success: function (user) {
this.username = ''
this.password = ''
dispatch('SET_CURRENT_USER', user)
},
error: function (user, error) {
// console.log('login errors: ' + JSON.stringify(error) + 'for user: ' + JSON.stringify(user))
// state.loginErrors = error
}
})

Phonegap Facebook Connect - Getting User's Birthday and Name

My app is in the early development stage. I'm using the latest PhoneGap Build and Facebook Connect plugin. I managed to get the login working - you tap the Login With Facebook button, it switches to the Facebook app, Facebook passes my app an object with the basic login key/token & userID, and then my app tries to reach out for the user's full name and age.
I can't seem to get Facebook to give me any information other than the user's ID and full name. I need the user's age! For some reason, adding a projection isn't working... What's wrong with my code?
var fbLoginSuccess = function (userData) {
facebookConnectPlugin.getAccessToken(function(token) {
if(userData['status'] == 'connected'){
getBasicUserInfo_fb(userData);
}
}, function(err) {
alert("Could not get access token: " + err);
});
}
function getBasicUserInfo_fb(userData){
facebookConnectPlugin.api(userData['authResponse']['userID'] + "/?fields=id,birthday", ["user_birthday"], function (response) {
if (response && !response.error) {
alert("response: " + JSON.stringify(response));
console.log(response);
var user_name = response['name'];
var user_age = response['birthday'];
var user_picture = response['picture'];
}
},
function (error) {
console.log(error);
alert("Failed: " + JSON.stringify(error));
});
}
The Github page (https://github.com/Wizcorp/phonegap-facebook-plugin) says:
Getting a User's Birthday
Using the graph api this is a very simple task:
facebookConnectPlugin.api("<user-id>/?fields=id,email", ["user_birthday"],
function (result) {
alert("Result: " + JSON.stringify(result));
/* alerts:
{
"id": "000000123456789",
"email": "myemail#example.com"
}
*/
},
function (error) {
alert("Failed: " + error);
});
I might be losing my mind but the example on Github is saying how to get the birthday, and the scope is set up to get that, BUT then the parameters are set up to get the email address. Basically all I've done is changed "id,email" to "id,birthday"... What am I doing wrong?!
Apparently I was wrong to have "user_profile" in my initial login request... I guess it only accepts one parameter?
The bad version:
facebookConnectPlugin.login(["public_profile","user_birthday"],
fbLoginSuccess,
function (error) { alert("" + error) }
);
The good version:
facebookConnectPlugin.login(["user_birthday"],
fbLoginSuccess,
function (error) { alert("" + error) }
);

Parse.com: Signup user to role

How do you add a user to an existing role when they're signing up? My code below doesn't work, I don't get any errors or any prints in the logs (not sure what I'm doing wrong):
Parse.User.signUp(req.body.email, req.body.password, {
"name": req.body.name,
"email": req.body.email,
}, {
success: function(user) {
var query = new Parse.Query(Parse.Role);
query.equalTo("name", 'Basic User');
query.find({
success: function(roles) {
alert("HELLO" + roles);
if (roles.length < 1) {
alert("HELLO");
console.log("Error Signing Up: No roles for " + signUpRoleGroup + " were found");
} else {
alert("HERE");
roles[0].getUsers().add(user);
roles[0].save();
}
},
error: function(error) {
alert("Could not add users to the account " + accountName + " error: " + error.message);
}
});
},
error: function(user, error) {
alert("Error signing up user");
}
});
I think what's going on is the caller isn't giving this function a chance to finish saving the role. The cloud function should wait until the role is saved before invoking response.success() or error().
Here's a promise-returning rewrite of the same code. Easier on the eyes, I think, and clearer about asynch tasks done serially. This puts you in more firm control of the response.
Parse.Cloud.define("signupAsBasicUser", function(request, response) {
signupAsBasicUser(request.params.name, request.params.password, request.params.email).then(function(user) {
response.success(user);
}, function(error) {
response.error(error);
});
});
// return a promise fulfilled with a signed-up user who is added to the 'Basic User" role
//
function signupAsBasicUser(name, password, email) {
Parse.Cloud.useMasterKey();
var user = new Parse.User();
user.set("username", name);
user.set("password", password);
user.set("email", email);
return user.signUp().then(function() {
var query = new Parse.Query(Parse.Role);
query.equalTo("name", 'Basic User');
return query.find();
}).then(function(roles) {
if (roles.length < 1) return Parse.Promise.error("no such role");
roles[0].getUsers().add(user);
return roles[0].save();
}).then(function() {
return user;
});
}

XMLHttpRequestError issue when signing up user using parse

I'm trying to use Parse.com to sign users up to my application I'm developing. However I seem to get an error when firing my function.
Parse.initialize("APP ID", "JS KEY");
function signUp() {
var user = new Parse.User();
// Get user inputs from form.
var username = document.login.username.value;
var password = document.login.password.value;
user.set("username", username);
user.set("password", password);
user.signUp(null, {
success: function (user) {
// Hooray! Let them use the app now.
alert("Success");
},
error: function (user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
};
The error:
Error: 100 XMLHttpRequest failed: {"statusText":"","status":0,"response":"","responseType":"","responseXML":null,"responseText":"","upload":{"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null},"withCredentials":false,"readyState":4,"timeout":0,"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null}
Any help here would be great, i'm unsure what's causing the error. Seems to work correctly when i'm not passing form data through it. Thanks.
I think you instead should use:
user.setUsername(username);
user.setPassword(password);
Also, these can be combined:
Parse.User.signUp(username, password, { ACL: new Parse.ACL() }, {
success: function (user) {
// Hooray! Let them use the app now.
alert("Success");
},
error: function (user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});

Categories