Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

806
Views
Firebase logout user all sessions

I am using Firebase authentication in my iOS app. Is there any way in Firebase when user login my app with Firebase then logout that user all other devices(sessions)? Can I do that with Firebase admin SDK?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

When I had this problem, I solved it with cloud functions. Visit this link for more details https://firebase.google.com/docs/auth/admin/manage-sessions#revoke_refresh_tokens

Do the following;

  1. Configure the web server with firebase cloud functions (if it doesn't exist)
  2. use the admin sdk (that's the only way this method would work) - [Visit this link] ((https://firebase.google.com/docs/admin/setup#initialize_the_sdk ).
  3. Create an API that receives the uid and revokes the current sessions as specified in the first link above
 admin.auth().revokeRefreshTokens(uid) .then(() => { return admin.auth().getUser(uid); }) .then((userRecord) => { return new Date(userRecord.tokensValidAfterTime).getTime() / 1000; }) .then((timestamp) => { //return valid response to ios app to continue the user's login process });

Voila users logged out. I hope this helps you solve the problem.

over 4 years ago · Santiago Trujillo Report

0

Firebase doesn't provide such feature. You need to manage it yourself.

Here is the Firebase Doc and they haven't mentioned anything related to single user sign in.

Here is what you can do for this-

Take one token in User node (Where you save user's other data) in Firebase database and regenerate it every time you logged in into application, Match this token with already logged in user's token (Which is saved locally) in appDidBecomeActive and appDidFinishLaunching or possibly each time you perform any operation with Firebase or may be in some fixed time interval. If tokens are different logged out the user manually and take user to authenticate screen.

over 4 years ago · Santiago Trujillo Report

0

What i have done is:

Created collection in firestore called "activeSessions".User email as an id for object and "activeID" field for holding most recent session id.

in sign in page code:

Generating id for a user session every time user is logging in. Add this id to localstorage(should be cleaned everytime before adding). Replace "activeID" by generated id in collection "activeSessions" with current user email.

function addToActiveSession() {
  var sesID = gen();

  var db = firebase.firestore();
  localStorage.setItem('userID', sesID);
  db.collection("activeSessions").doc(firebase.auth().currentUser.email).set({
    activeID: sesID
  }).catch(function (error) {
      console.error("Error writing document: ", error);
    });

}
function gen() {
  var buf = new Uint8Array(1);
  window.crypto.getRandomValues(buf);
  return buf[0];
}
function signin(){
 firebase.auth().signInWithEmailAndPassword(email, password).then(function (user) {
      
      localStorage.clear();
      addToActiveSession();
      }
    }), function (error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      if (errorCode === 'auth/wrong-password') {
        alert('wrong pass');
      } else {
        alert(errorMessage);
      }
      console.log(error);
    };
}

Then i am checking on each page if the id session in local storage is the same as "activeID" in firestore,if not then log out.

function checkSession(){
  
  var db = firebase.firestore();
  var docRef = db.collection("activeSessions").doc(firebase.auth().currentUser.email);
        docRef.get().then(function (doc) {
          alert(doc.data().activeID);
          alert(localStorage.getItem('userID'));
          if (doc.data().activeID != localStorage.getItem('userID')) {
            alert("bie bie");
            firebase.auth().signOut().then(() => {
        
              window.location.href = "signin.html";
         }).catch((error) => {
           // An error happened.
         });
            window.location.href = "accountone.html";
          } else{alert("vse ok");}
        }).catch(function (error) {
          console.log("Error getting document:", error);
        });
}

PS: window has to be refreshed to log inactive session out.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!