Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

807
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda