Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit concurrent logins by an authenciated user in Firebase

I have been looking and playing with Firebase and I found it really interesting.

So far I have tried some simple authentication and security policy setting but now I have a problem which does not seem to be covered in the documentation and I couldn't find anything on Google or here.

The problem is that I cannot find a way to limit the number of concurrent logins per email/password.

I would like to have an option where paid customers can only login from 1 IP at a time. In other words I don't want people to be able to purchase an account and then share the same with friends and family and then all connect to the system at the same time using the same credentials.

Thank you in advance.

like image 722
Reza Avatar asked Dec 01 '25 05:12

Reza


1 Answers

You will control access by writing to a path in Firebase whenever a user logs in. Then you can check that path to ensure only one user exists at a time:

  • write a value to a path each time a user logs in (e.g. logged_in_users/$user_id)
  • use onDisconnect() to delete that value when user disconnects
  • check that path for a value on an additional login attempt
  • show an error if the value exists or allow login if not

This takes care of the UX portion. To secure it against exploits, you will take advantage of Firebase's comprehensive security rules:

  • generate your own authentication tokens using the custom login strategy
  • include the IP address as part of the data inside the token
  • reject login attempts if the logged_in_users/$user_id is set to a different IP address
  • write security rules to prevent read/write from other IPs

Assuming you've generated tokens containing an IP address, your security rules could look something like the following:

".read": "root.child('logged_in_users/'+auth.uid).val() === auth.ip_address"
like image 97
Kato Avatar answered Dec 07 '25 03:12

Kato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!