File size: 4,745 Bytes
eeaa556
 
 
12f0507
 
eeaa556
 
8d5289f
eeaa556
 
 
 
 
 
 
 
8d5289f
 
 
 
eeaa556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
eeaa556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
 
eeaa556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
 
 
 
 
 
 
eeaa556
 
8d5289f
 
eeaa556
 
 
 
 
 
 
 
12f0507
 
 
8d5289f
 
 
 
eeaa556
 
 
 
 
 
 
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeaa556
12f0507
 
 
 
 
 
 
 
 
 
 
eeaa556
12f0507
 
 
 
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// ===== Authentication Module (v3 - cookie + storage fallback) =====
// Uses cookies as primary storage (works in HF Spaces iframe)
// Falls back to sessionStorage if available

const Auth = {
    _memoryToken: null,
    _memoryUser: null,
    _sessionLockedUntil: 0,

    _setCookie(name, value, days) {
        let expires = '';
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = '; expires=' + date.toUTCString();
        }
        // SameSite=None + Secure required for iframe embedding (HF Spaces)
        const isHttps = window.location.protocol === 'https:';
        const sameSite = isHttps ? '; SameSite=None; Secure' : '; SameSite=Lax';
        document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/' + sameSite;
    },

    _getCookie(name) {
        const nameEQ = name + '=';
        const ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i].trim();
            if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length));
        }
        return null;
    },

    _deleteCookie(name) {
        document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    },

    getToken() {
        // Try memory first (fastest)
        if (this._memoryToken) return this._memoryToken;
        // Try cookie
        const cookieToken = this._getCookie('mm_token');
        if (cookieToken) {
            this._memoryToken = cookieToken;
            return cookieToken;
        }
        // Try sessionStorage as fallback
        try {
            const ssToken = sessionStorage.getItem('mm_token');
            if (ssToken) {
                this._memoryToken = ssToken;
                return ssToken;
            }
        } catch(e) {}
        return null;
    },

    getUser() {
        // Try memory first
        if (this._memoryUser) return this._memoryUser;
        // Try cookie
        const cookieUser = this._getCookie('mm_user');
        if (cookieUser) {
            try {
                this._memoryUser = JSON.parse(cookieUser);
                return this._memoryUser;
            } catch(e) {}
        }
        // Try sessionStorage as fallback
        try {
            const data = sessionStorage.getItem('mm_user');
            if (data) {
                this._memoryUser = JSON.parse(data);
                return this._memoryUser;
            }
        } catch(e) {}
        return null;
    },

    isAdmin() {
        const user = this.getUser();
        return user && user.role === 'admin';
    },

    setSession(token, user) {
        this._memoryToken = token;
        this._memoryUser = user;
        // Lock session for 15s to prevent any race-condition clearSession()
        this._sessionLockedUntil = Date.now() + 15000;
        // Save to cookie (1 day expiry)
        this._setCookie('mm_token', token, 1);
        this._setCookie('mm_user', JSON.stringify(user), 1);
        // Also try sessionStorage
        try {
            sessionStorage.setItem('mm_token', token);
            sessionStorage.setItem('mm_user', JSON.stringify(user));
        } catch(e) {}
    },

    clearSession() {
        if (Date.now() < this._sessionLockedUntil) {
            console.warn('[Auth] clearSession blocked by lock', new Error().stack);
            return;
        }
        this._memoryToken = null;
        this._memoryUser = null;
        this._deleteCookie('mm_token');
        this._deleteCookie('mm_user');
        try {
            sessionStorage.removeItem('mm_token');
            sessionStorage.removeItem('mm_user');
        } catch(e) {}
    },

    async login(email, password) {
        const res = await fetch('/api/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email, password })
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Erro no login');
        this.setSession(data.token, data.user);
        return data;
    },

    async logout() {
        try {
            await fetch('/api/auth/logout', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + this.getToken(),
                    'Content-Type': 'application/json'
                }
            });
        } catch (e) { /* ignore */ }
        this.clearSession();
        window.location.hash = '#/login';
        window.location.reload();
    },

    headers() {
        return {
            'Authorization': 'Bearer ' + this.getToken(),
            'Content-Type': 'application/json'
        };
    }
};