'use client';
import React, { useContext, createContext, useState, useEffect } from 'react';
import {
setPersistence,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged,
User,
browserSessionPersistence,
} from 'firebase/auth';
import Loading from '../components/pages/Loading';
import { doc, collection, getDocs, setDoc, deleteDoc, orderBy, limit, query } from 'firebase/firestore';
import { auth, firestore } from '../firebase-config';
export interface AuthContextType {
user: User | null;
emailSignIn: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | null>(null);
export const AuthContextProvider = ({ children }: Readonly<{ children: React.ReactNode }>) => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const emailSignIn = async (email: string, password: string) => {
try {
await setPersistence(auth, browserSessionPersistence);
const userCredential = await signInWithEmailAndPassword(auth, email, password);
setUser(userCredential.user);
const sessionsRef = collection(firestore, 'users', userCredential.user.uid, 'sessions');
const sessionsSnapshot = await getDocs(sessionsRef);
if (sessionsSnapshot.size >= 2) {
console.log('More than two sessions found, removing the oldest one.');
await removeOldestSession(sessionsRef);
} else {
console.log('Less than two sessions found, no need to remove.');
}
const sessionId = generateDeviceId();
await setDoc(doc(sessionsRef, sessionId), {
deviceId: sessionId,
timestamp: new Date(),
});
} catch (error) {
console.error('Error signing in with email: ', error);
throw error;
}
};
const removeOldestSession = async (sessionsRef: any) => {
const sessionsQuery = query(sessionsRef, orderBy('timestamp', 'asc'), limit(1));
const querySnapshot = await getDocs(sessionsQuery);
if (!querySnapshot.empty) {
const oldestSession = querySnapshot.docs[0];
console.log('Removing oldest session:', oldestSession.id);
await deleteDoc(oldestSession.ref);
}
};
const generateDeviceId = () => {
return Math.random().toString(36).substring(2);
};
const logout = async () => {
try {
if (user) {
const sessionsRef = collection(firestore, 'users', user.uid, 'sessions');
const sessionQuery = query(sessionsRef, orderBy('timestamp', 'desc'), limit(1));
const querySnapshot = await getDocs(sessionQuery);
if (!querySnapshot.empty) {
const sessionDoc = querySnapshot.docs[0];
await deleteDoc(sessionDoc.ref);
}
}
await signOut(auth);
setUser(null);
} catch (error) {
console.error('Error signing out: ', error);
throw error;
}
};
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
setLoading(true);
if (currentUser) {
setUser(currentUser);
} else {
setUser(null);
}
setLoading(false);
});
return () => unsubscribe();
}, []);
if (loading) {
return <Loading />;
}
return (
<AuthContext.Provider value={{ user, emailSignIn, logout }}>
{children}
</AuthContext.Provider>
);
};
export const UserAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthContextProvider');
}
return context;
};
I’m using Firebase for authentication and want to ensure that if a user is logged in on two browsers, any attempt to log in from a third browser should log out the oldest session. In my Firestore database, the setup works as intended: when a third browser logs in, the oldest session is removed and replaced with the new one. However, the user remains logged in on the browser. How can I ensure that the user is also logged out from the oldest session?
I’ve added console logs to track the process, and they confirm that the flow is working correctly: once more than two browsers are detected, the oldest session is removed as expected. However, despite this, the user remains logged in, which should not be the case.
Akbar Khawaja is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.