File size: 1,599 Bytes
ea81969
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { db } from '@/backend/services/firebase';

export const AuthService = {
    async saveCustomKey(sessionId, apiKey) {
        const snapshot = await db.ref('users').orderByChild('Active_Session_ID').equalTo(sessionId).once('value');
        if (!snapshot.exists()) throw new Error("User not found.");
        const userKey = Object.keys(snapshot.val())[0];
        await db.ref(`users/${userKey}`).update({ Private_API_Key: apiKey });
        return { success: true };
    },

    async updateActiveSession(userId, newSessionId) {
        if (!userId) throw new Error("Membership ID is required.");

        // Find user by their PERMANENT Login_Key first
        let snapshot = await db.ref('users').orderByChild('Login_Key').equalTo(userId).once('value');
        
        // Fallback: If not found, try searching by Active_Session_ID (for legacy users)
        if (!snapshot.exists()) {
            snapshot = await db.ref('users').orderByChild('Active_Session_ID').equalTo(userId).once('value');
        }

        if (!snapshot.exists()) throw new Error("Membership ID not found in records.");
        
        const userKey = Object.keys(snapshot.val())[0];
        const userData = snapshot.val()[userKey];
        
        const updates = { Active_Session_ID: newSessionId };
        
        // If this was a legacy user without a Login_Key, set it now to stabilize their account
        if (!userData.Login_Key) {
            updates.Login_Key = userId;
        }
        
        await db.ref(`users/${userKey}`).update(updates);
        
        return { success: true };
    }
};