-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathUserLogin.tsx
More file actions
234 lines (210 loc) · 6.06 KB
/
UserLogin.tsx
File metadata and controls
234 lines (210 loc) · 6.06 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import React, { useState, useEffect, useCallback } from "react";
import type { User } from "../db/database";
import { useDatabase } from "../context/DatabaseContext";
import { SQLiteSync } from "../SQLiteSync";
interface UserSession {
userId: string;
name: string;
}
interface UserLoginProps {
users: User[];
currentSession: UserSession | null;
onLogin: (session: UserSession) => void;
onLogout: () => Promise<void>;
onUsersLoad: () => void;
onRefresh: () => void;
onError?: (error: string) => void; // Optional error handler
}
const UserLogin: React.FC<UserLoginProps> = ({
users,
currentSession,
onLogin,
onLogout,
onUsersLoad,
onRefresh,
onError
}) => {
const { db } = useDatabase();
const [selectedUserId, setSelectedUserId] = useState<string>("");
const [sqliteSyncEnabled, setSqliteSyncEnabled] = useState<boolean>(false);
const [sqliteSync, setSqliteSync] = useState<SQLiteSync | null>(null);
const [isRefreshing, setIsRefreshing] = useState<boolean>(false);
const [isLoggingOut, setIsLoggingOut] = useState<boolean>(false);
useEffect(() => {
onUsersLoad();
}, [onUsersLoad]);
useEffect(() => {
if (db) {
setSqliteSync(new SQLiteSync(db));
}
}, [db]);
// Initialize sync state when user logs in
useEffect(() => {
// No user logged in - disable sync
if (!currentSession) {
setSqliteSyncEnabled(false);
return;
}
// Check if there's a valid token available
const hasValidToken = SQLiteSync.hasValidToken();
if (hasValidToken) {
console.log(
"Valid token found in localStorage for user:",
currentSession.name
);
} else {
console.log(
"No valid token found in localStorage for user:",
currentSession.name
);
}
setSqliteSyncEnabled(false);
}, [currentSession]);
// Handle SQLite Sync enable/disable toggle
const handleSyncToggle = async (checked: boolean) => {
setSqliteSyncEnabled(checked);
if (checked) {
console.log("SQLite Sync enabled for user:", currentSession?.name);
} else {
console.log("SQLite Sync disabled");
}
};
const handleLogin = () => {
const selectedUser = users.find((user) => user.id === selectedUserId);
if (selectedUser) {
const session: UserSession = {
userId: selectedUser.id,
name: selectedUser.name,
};
onLogin(session);
}
};
const formatUserDisplay = (user: User) => {
const shortId = user.id ? user.id.slice(0, 6) : "no-id";
const display = `${user.name} [${shortId}]`;
return display;
};
const handleRefreshClick = async () => {
setIsRefreshing(true);
try {
// If SQLite Sync is enabled, sync with cloud before refreshing
if (sqliteSyncEnabled && sqliteSync && currentSession) {
try {
await sqliteSync.setupWithToken(currentSession);
console.log("SQLite Sync - Starting sync...");
await sqliteSync.sync();
console.log("SQLite Sync - Sync completed successfully");
} catch (error) {
console.error(
"SQLite Sync - Failed to sync with SQLite Cloud:",
error
);
console.warn("SQLite Sync: Falling back to local refresh only");
if(onError) onError("SQLite Sync - Failed to sync with SQLite Cloud: " + error);
}
} else {
console.log(
"SQLite Sync disabled - refreshing from local database only"
);
}
// Refresh data from database
onRefresh();
} finally {
setIsRefreshing(false);
}
};
const handleLogout = async () => {
setIsLoggingOut(true);
try {
// If SQLite Sync is enabled, perform complete logout
if (sqliteSyncEnabled && sqliteSync) {
try {
console.log("Performing SQLite Sync logout...");
await sqliteSync.logout();
} catch (error) {
console.error("SQLite Sync logout error:", error);
alert("Logout: " + error);
return;
}
}
// Clear tokens from localStorage
if (currentSession) {
localStorage.clear();
}
// Reset SQLite Sync state
setSqliteSyncEnabled(false);
await onLogout();
} finally {
setIsLoggingOut(false);
}
};
if (currentSession) {
return (
<div className="user-login logged-in">
<div className="user-header">
<span className="logged-user">
Logged in as: {currentSession.name} [
{currentSession.userId
? currentSession.userId.slice(0, 6)
: "no-id"}
]
</span>
<button
className="btn-logout"
onClick={handleLogout}
disabled={isLoggingOut}
>
{isLoggingOut ? "Logging out..." : "Logout"}
</button>
</div>
<div className="sync-controls">
<label className="sync-checkbox">
<input
type="checkbox"
checked={sqliteSyncEnabled}
onChange={(e) => handleSyncToggle(e.target.checked)}
/>
SQLite Sync
</label>
<button
className="btn-secondary"
onClick={handleRefreshClick}
disabled={isRefreshing}
>
{isRefreshing
? "Refreshing..."
: sqliteSyncEnabled
? "Sync & Refresh"
: "Refresh"}
</button>
</div>
</div>
);
}
return (
<div className="user-login">
<select
value={selectedUserId}
onChange={(e) => setSelectedUserId(e.target.value)}
className="user-selector"
>
<option value="">Select a user...</option>
{users.map((user) => {
return (
<option key={user.id} value={user.id}>
{formatUserDisplay(user)}
</option>
);
})}
</select>
<button
className="btn-login"
onClick={handleLogin}
disabled={!selectedUserId}
>
Login
</button>
</div>
);
};
export default UserLogin;