-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseService.js
More file actions
276 lines (239 loc) · 7.75 KB
/
DatabaseService.js
File metadata and controls
276 lines (239 loc) · 7.75 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import { Platform } from 'react-native';
// Database service for managing user data, verification codes, and progress
class DatabaseService {
constructor() {
this.users = new Map();
this.verificationCodes = new Map();
this.userProgress = new Map();
this.loadFromStorage();
}
// Load data from localStorage on web or AsyncStorage on mobile
async loadFromStorage() {
try {
if (Platform.OS === 'web') {
const usersData = localStorage.getItem('mindcandy_users');
const codesData = localStorage.getItem('mindcandy_verification_codes');
const progressData = localStorage.getItem('mindcandy_user_progress');
if (usersData) this.users = new Map(JSON.parse(usersData));
if (codesData) this.verificationCodes = new Map(JSON.parse(codesData));
if (progressData) this.userProgress = new Map(JSON.parse(progressData));
} else {
const AsyncStorage = require('@react-native-async-storage/async-storage').default;
const usersData = await AsyncStorage.getItem('mindcandy_users');
const codesData = await AsyncStorage.getItem('mindcandy_verification_codes');
const progressData = await AsyncStorage.getItem('mindcandy_user_progress');
if (usersData) this.users = new Map(JSON.parse(usersData));
if (codesData) this.verificationCodes = new Map(JSON.parse(codesData));
if (progressData) this.userProgress = new Map(JSON.parse(progressData));
}
} catch (error) {
console.error('Error loading from storage:', error);
}
}
// Save data to storage
async saveToStorage() {
try {
if (Platform.OS === 'web') {
localStorage.setItem('mindcandy_users', JSON.stringify([...this.users]));
localStorage.setItem('mindcandy_verification_codes', JSON.stringify([...this.verificationCodes]));
localStorage.setItem('mindcandy_user_progress', JSON.stringify([...this.userProgress]));
} else {
const AsyncStorage = require('@react-native-async-storage/async-storage').default;
await AsyncStorage.setItem('mindcandy_users', JSON.stringify([...this.users]));
await AsyncStorage.setItem('mindcandy_verification_codes', JSON.stringify([...this.verificationCodes]));
await AsyncStorage.setItem('mindcandy_user_progress', JSON.stringify([...this.userProgress]));
}
} catch (error) {
console.error('Error saving to storage:', error);
}
}
// Generate verification code
generateVerificationCode() {
return Math.floor(100000 + Math.random() * 900000).toString();
}
// Send verification email (simulated)
async sendVerificationEmail(email, code) {
// In a real app, this would send an actual email
// For now, we'll simulate it and store the code
this.verificationCodes.set(email, {
code,
timestamp: Date.now(),
verified: false
});
await this.saveToStorage();
// Simulate email delay and return the code
return new Promise(resolve => {
setTimeout(() => {
resolve(code);
}, 1000);
});
}
// Verify email code
async verifyEmailCode(email, code) {
const storedCode = this.verificationCodes.get(email);
if (!storedCode) return false;
// Check if code is still valid (5 minutes)
const isExpired = Date.now() - storedCode.timestamp > 5 * 60 * 1000;
if (isExpired) {
this.verificationCodes.delete(email);
await this.saveToStorage();
return false;
}
if (storedCode.code === code) {
storedCode.verified = true;
await this.saveToStorage();
return true;
}
return false;
}
// Check if email is verified
isEmailVerified(email) {
const storedCode = this.verificationCodes.get(email);
return storedCode && storedCode.verified;
}
// Register new user
async registerUser(userData) {
const { email, username, password, name } = userData;
// Check if email already exists
for (let [key, user] of this.users) {
if (user.email === email) {
throw new Error('Email already registered');
}
if (user.username === username) {
throw new Error('Username already taken');
}
}
// Check if email is verified
if (!this.isEmailVerified(email)) {
throw new Error('Email not verified');
}
const userId = Date.now().toString();
const newUser = {
id: userId,
email,
username,
password, // In real app, this would be hashed
name,
profilePic: null,
joinDate: new Date().toISOString(),
lastLogin: null,
isActive: true
};
this.users.set(userId, newUser);
// Initialize user progress
this.userProgress.set(userId, {
moodEntries: [],
journalEntries: [],
flashcardProgress: {
completedCards: [],
score: { correct: 0, total: 0 },
streak: 0,
bestStreak: 0,
level: 1,
xp: 0,
},
studySessions: [],
achievements: [],
settings: {
notifications: true,
theme: 'candy',
hapticFeedback: true,
}
});
await this.saveToStorage();
return newUser;
}
// Login user
async loginUser(loginData) {
const { username, password } = loginData;
// Find user by username or email
let user = null;
for (let [key, u] of this.users) {
if (u.username === username || u.email === username) {
user = u;
break;
}
}
if (!user) {
throw new Error('User not found');
}
if (user.password !== password) {
throw new Error('Invalid password');
}
if (!user.isActive) {
throw new Error('Account is deactivated');
}
// Update last login
user.lastLogin = new Date().toISOString();
this.users.set(user.id, user);
await this.saveToStorage();
return user;
}
// Get user by ID
getUserById(userId) {
return this.users.get(userId);
}
// Get user progress
getUserProgress(userId) {
return this.userProgress.get(userId) || {
moodEntries: [],
journalEntries: [],
flashcardProgress: {
completedCards: [],
score: { correct: 0, total: 0 },
streak: 0,
bestStreak: 0,
level: 1,
xp: 0,
},
studySessions: [],
achievements: [],
settings: {
notifications: true,
theme: 'candy',
hapticFeedback: true,
}
};
}
// Update user progress
async updateUserProgress(userId, progressData) {
const currentProgress = this.getUserProgress(userId);
// Deep merge the progress data, especially for nested objects like flashcardProgress
const updatedProgress = {
...currentProgress,
...progressData,
flashcardProgress: {
...currentProgress.flashcardProgress,
...progressData.flashcardProgress,
}
};
this.userProgress.set(userId, updatedProgress);
await this.saveToStorage();
return updatedProgress;
}
// Update user profile
async updateUserProfile(userId, profileData) {
const user = this.getUserById(userId);
if (!user) throw new Error('User not found');
const updatedUser = { ...user, ...profileData };
this.users.set(userId, updatedUser);
await this.saveToStorage();
return updatedUser;
}
// Logout user (just update last activity)
async logoutUser(userId) {
const user = this.getUserById(userId);
if (user) {
user.lastLogin = new Date().toISOString();
this.users.set(userId, user);
await this.saveToStorage();
}
}
// Delete verification code after successful registration
async deleteVerificationCode(email) {
this.verificationCodes.delete(email);
await this.saveToStorage();
}
}
// Export singleton instance
export default new DatabaseService();