Firebase User Already Logged In - javascript

I have a firebase app that I can log into from various devices, but I'd like to disconnect the other connections if I make a new one using the same account.
I saw this bit of code but I think this might be for the old version:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
This looks like the right idea - if this gets called I could show a graphic saying, "Oops looks like you signed in on another device." then fire a disconnect while allowing the other connection to proceed?

This isn't something you'll be able to handle with auth alone, as the tokens are generated and stored independently and there's no concept of "device sessions" that can be queried against. However, you could do something like this:
var deviceId = generateARandomDeviceIDAndStoreItInLocalStorage();
firebase.auth().signInWithPopup(/* ... */).then(function(user) {
var userRef = firebase.database().ref('users').child(user.uid);
return userRef.update({
deviceId: deviceId
});
});
firebase.auth().onAuthStateChanged(function(user) {
var userRef = firebase.database().ref('users').child(user.uid);
userRef.child('deviceId').on('value', function(snap) {
if (snap.val() !== deviceId) {
// another device has signed in, let's sign out
firebase.auth().signOut();
}
});
});
IMPORTANT CAVEAT: This is not a secure, enforceable way to guarantee only one device is logged in at once. Rather it is a client-driven way to generally achieve the goal of only one device being signed in.

Related

What is preferred way to show DOM elements conditioned on firebase authentication

I'm trying to build a small web-page where sign-in is controlled by Firebase Google Auth and is popped up with profile page. What is the secured and preferred way to show the profile page?
Currently I am using onAuthStateChanged to manipulate particular div which holds profile data when user is signed-in. If the user is not logged in I am using removeChild() method to remove that div from DOM and when logged in appendChild() adds back the div.
Supposing you're using firebase's native firebase.auth().onAuthStateChanged function
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
As well as firebase.auth().currentUser to check if the user is currently logged in or not.
In that case, it's perfectly fine to use removeChild and appendChild and they do not hold any security threats, as if a user is not logged, after a page refresh all of the information will vanish.
Here's a small firebase application that shows that when the connection to the firebase is closed and removeChild is used, appendChild stops working as firebase is disconnected, thus proving the point that it's safe to use.
https://jsfiddle.net/vh9xay6e/
Note that in this example I'm not testing any authentification, just the use of firebase with removeChild and appendChild.
You can see that once the connection to Firebase is over, nothing on the frontend side can happen to change that.
Using onAuthStateChanged method we can act upon state change (sign in or Sign out)
As an example :
firebase.auth().onAuthStateChanged(user=>{
if(user){
document.getElementById("id").classList.remove('hide')
//this will populate your class which associate with above id.
} else{
document.getElementById("id_of_your_div").classList.add('hide')
}
})
I think it's okay to use removeChild and appendChild method based on firebase auth state changes in your application.
try to wire around your code by:
var userCurrent = firebase.auth().currentUser; in a function.
NOTE: Make sure you need to be sure first you signed in (as its an async operation), followed by the update user data as:
var authenticationRef = firebase.auth();
authenticationRef.onAuthStateChanged(function(user) {
if (user) {
console.log('onAuthStateChanged : '+user.displayName);
_updateUser();
} else {
console.log('Not login');
}
});
fucntion _updateUser(){
var userCurrent = firebase.auth().currentUser;
userCurrent.updateProfile({
displayName: "Karthik.S",
}).then(function() {
var displayName = userCurrent.displayName;
}, function(error) {
});
}

Firebase Ondisconnect

I am new to firebase backend. I want to implement firebase onDisconnect functionality on backend. I have 100 or so authorised firebase users and each one will have a unique id generated by firebase. How can I know which user is not connected right now. I have seen examples and everyone is telling this code;
admin.database().ref().child(".info/connected").on("value", function (snap) {
connected = snap.val() === true;
if (connected) {
} else {
}
});
How can I get that unique firebase id associated with each user using above code or how i can know which is disconnected?
First of all while user open application at that time set one entry with their current state like
users :
{
"784823468sugfsdjf":"online",
"3223232fdfdfdffdf":"online",
"y32y32y32y32y3y23":"online",
"3b2jg434jg343g4h3":"offline"
}
Now update all user's status using
admin.database().ref().child(".info/connected").on("value", function (snap) {
connected = snap.val() === true;
if (connected) {
updated(uid,"Online");
} else {
updated(uid,"offline");
}
});
By this way you will get all user's current state.

How to get User Details after Google Authentication in web app using firebase?

I have a web-app that allows users to sign in using their gmail account.Once the user is signed in, I am able to see it's details using result.user object like this-
function signInWithGoogle(){
var provider=new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result){
var user=result.user;
console.log("user_provider="+user.displayName+" user_email="+user.email+" user_dp="+user.photoURL+" user_verification="+user.emailVerified+" uid="+user.uid);
}).catch(function(error){
console.log("error="+error);
});
}
After signing in, I want to keep user details in page even after reloading and refreshing for that I used User object of auth() like this-
$(document).ready(function(){
var user=firebase.auth().currentUser;
console.log(user);
});
But it's showing user as null although I can see user email address in authentication console in firebase.
P.S. I have also used onAuthStateChanged instead of currentUser , but still it's not working.
onAuthStateChanged should work. You have to listen to it correctly.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// currentUser should be available now.
} else {
// No user logged in.
}
});
Keep in mind that the state is stored in single host origin web storage. So if you navigate to a page with a different domain, the state will not propagate.

Meteor: onConnection, check if user is logged in

I'm using the onConnection hook and some template helpers to do some stuff with statistics. But now, I want't to exclude these operations when I'm a registered user.
The Problem, I can't use Meteor.user() in the onConnection hook, so how can i check if a user is logged in ?
Concerning code, there is not much to show
Meteor.onConnection(function(conn) {
if(Meteor.user()) {
console.log("you are logged in")
} else {
console.log("u are not logged in")
}
});
It's not the true example but it shows simple what i want to do
The Error
err [Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.]
I understand that i can just use Meteor.user() in methods, but how can i find out in the onConnection if a user is logged in ?
For statistics purposes I'd recommend to use publications. They have more sophisticated api which allows you to have more control over your connection.
Meteor.publish('users.trackPresence', function() {
// Both this.userId && this.connection are available to be called from here
this.onStop(function(){
// user went offline
});
this.ready();
});
and on the client you can check if user is present and not even subscribe if this is the case:
Tracker.autorun(function(){
if (!Meteor.userId())
Meteor.subscribe('users.trackPresence');
});
Meteor automatically handles unsubscribe/resubscribe when you subscribe from within a Tracker.autorun
read more about pubsub api here
https://docs.meteor.com/api/pubsub.html
Obviously as you stated, the Meteor docs do not provide any insight for how to achieve this. I spent a decent amount of time going thru the accounts-base source and don't see any way to do what you are asking natively.
With that said, if you could update the Users collection each time they login and save their current IP address, then you could use this as a way to see if the current connection is logged in. Here is an example.
Meteor.onConnection((connection) => {
var user = Meteor.users.findOne({
'user.profile.currentIp': connection.clientAddress
});
if (user) {
console.log("you are logged in")
} else {
console.log("u are not logged in")
}
});
Be sure to add login and logout hooks to set and remove the user's current IP. I have not tested this approach, but in theory it should work.

Picking up meteor.js user logout

Is there any way to pick up when a user logs out of the website? I need to do some clean up when they do so. Using the built-in meteor.js user accounts.
I'll be doing some validation using it, so I need a solution that cannot be trigger on behalf of other users on the client side - preferably something completely server side.
You may use Deps.autorun to setup a custom handler observing Meteor.userId() reactive variable changes.
Meteor.userId() (and Meteor.user()) are reactive variables returning respectively the currently logged in userId (null if none) and the corresponding user document (record) in the Meteor.users collection.
As a consequence one can track signing in/out of a Meteor application by reacting to the modification of those reactive data sources.
client/main.js :
var lastUser=null;
Meteor.startup(function(){
Deps.autorun(function(){
var userId=Meteor.userId();
if(userId){
console.log(userId+" connected");
// do something with Meteor.user()
}
else if(lastUser){
console.log(lastUser._id+" disconnected");
// can't use Meteor.user() anymore
// do something with lastUser (read-only !)
Meteor.call("userDisconnected",lastUser._id);
}
lastUser=Meteor.user();
});
});
In this code sample, I'm setting up a source file local variable (lastUser) to keep track of the last user that was logged in the application.
Then in Meteor.startup, I use Deps.autorun to setup a reactive context (code that will get re-executed whenever one of the reactive data sources accessed is modified).
This reactive context tracks Meteor.userId() variation and reacts accordingly.
In the deconnection code, you can't use Meteor.user() but if you want to access the last user document you can use the lastUser variable.
You can call a server method with the lastUser._id as argument if you want to modify the document after logging out.
server/server.js
Meteor.methods({
userDisconnected:function(userId){
check(userId,String);
var user=Meteor.users.findOne(userId);
// do something with user (read-write)
}
});
Be aware though that malicious clients can call this server method with anyone userId, so you shouldn't do anything critical unless you setup some verification code.
Use the user-status package that I've created: https://github.com/mizzao/meteor-user-status. This is completely server-side.
See the docs for usage, but you can attach an event handler to a session logout:
UserStatus.events.on "connectionLogout", (fields) ->
console.log(fields.userId + " with connection " + fields.connectionId + " logged out")
Note that a user can be logged in from different places at once with multiple sessions. This smart package detects all of them as well as whether the user is online at all. For more information or to implement your own method, check out the code.
Currently the package doesn't distinguish between browser window closes and logouts, and treats them as the same.
We had a similar, though not exact requirement. We wanted to do a bit of clean up on the client when they signed out. We did it by hijacking Meteor.logout:
if (Meteor.isClient) {
var _logout = Meteor.logout;
Meteor.logout = function customLogout() {
// Do your thing here
_logout.apply(Meteor, arguments);
}
}
The answer provided by #saimeunt looks about right, but it is a bit fluffy for what I needed. Instead I went with a very simple approach like this:
if (Meteor.isClient) {
Deps.autorun(function () {
if(!Meteor.userId())
{
Session.set('store', null);
}
});
}
This is however triggered during a page load if the user has not yet logged in, which might be undesirable. So you could go with something like this instead:
if (Meteor.isClient) {
var userWasLoggedIn = false;
Deps.autorun(function (c) {
if(!Meteor.userId())
{
if(userWasLoggedIn)
{
console.log('Clean up');
Session.set('store', null);
}
}
else
{
userWasLoggedIn = true;
}
});
}
None of the solutions worked for me, since they all suffered from the problem of not being able to distinguish between manual logout by the user vs. browser page reload/close.
I'm now going with a hack, but at least it works (as long as you don't provide any other means of logging out than the default accounts-ui buttons):
Template._loginButtons.events({
'click #login-buttons-logout': function(ev) {
console.log("manual log out");
// do stuff
}
});
You can use the following Meteor.logout - http://docs.meteor.com/#meteor_logout

Categories

Resources