Reputation: 121
So I've been creating a simple chat app, and I'm using the more recent socket.io version, specifically [email protected], which has access to socket.data, which is really helpful, but I'm stuck in trying to apply it. I looked through the docs, but the best I found was this: socket.data docs
the code layout is like this:
function loginuser(socket, username,password){
if (authenticated()) {
socket.data.loggedin = true
}else{
console.log("fail")
}
}
and the io.on is like this:
io.on("connection", (socket) => {
socket.data.loggedin = false
socket.on('login', function(data) {
console.log("logged in?: "+ JSON.stringify(socket.data.loggedin))
if(!socket.data.loggedin){
loginuser(socket, data.username, data.password)
//should return true here afterwards in socket.data.loggedin, but it doesn't
}else{
console.log("logged in already")
}
});
so I was trying to pass socket through, which I thought would then allow me to change it across all of it, and not just the function. Has anyone done something simpler, or even let me know if this is possible? if not, what are some other options?
Upvotes: 0
Views: 319
Reputation: 36
Something like this might work for you.
function loginuser(socket, username, password) {
if (authenticated()) {
return true;
}
return false;
}
io.on("connection", (socket) => {
socket.data.loggedin = false;
socket.on('login', function(data) {
if (socket.data.loggedin === false && (socket.data.loggedin = loginuser(socket, data.username, data.password)) === false) {
console.log("Failed to log in.");
} else {
console.log("The user is logged in.");
}
});
});
In the above example, on a new connection, the default value of the socket.data.loggedin
property is false
.
If the socket emits the login
event, you do the following:
socket.data.loggedin
property's value equals to false
. If it doesn't equal false
, we jump to the else
block, our user is logged in. If the condition is false
, we go to the 2nd step.socket.data.loggedin
property's value to the return value of the loginuser
function, and check if the newly assigned value equals false
. If it's false
, then the user is not logged in and it couldn't log in either. If the new value is true
, we jump to the else
block, because our user has logged in successfully.Upvotes: 2