I’m using Firebase for authentication in my application and I need to restrict each user to being logged in on a max of two browsers at any given time

'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.

New contributor

Akbar Khawaja is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật