-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
463 lines (394 loc) ยท 17.1 KB
/
Copy pathserver.js
File metadata and controls
463 lines (394 loc) ยท 17.1 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
const express = require('express');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const path = require('path');
const fs = require('fs').promises;
const https = require('https');
const app = express();
const PORT = process.env.PORT || 3001;
const JWT_SECRET = 'spellbloc-secret-key-2024'; // In production, use environment variable
const RESEND_API_KEY = process.env.RESEND_API_KEY;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('.'));
// Simple in-memory database (in production, use a real database)
let users = [];
let userIdCounter = 1;
// Load users from file if exists
async function loadUsers() {
try {
const data = await fs.readFile('users.json', 'utf8');
const userData = JSON.parse(data);
users = userData.users || [];
userIdCounter = userData.counter || 1;
console.log(`๐ Loaded ${users.length} users from database`);
} catch (error) {
console.log('๐ No existing user database found, starting fresh');
}
}
// Save users to file
async function saveUsers() {
try {
await fs.writeFile('users.json', JSON.stringify({
users,
counter: userIdCounter
}, null, 2));
} catch (error) {
console.error('โ Failed to save users:', error);
}
}
// Email service
async function sendEmail(emailData) {
return new Promise((resolve, reject) => {
const postData = JSON.stringify(emailData);
const options = {
hostname: 'api.resend.com',
port: 443,
path: '/emails',
method: 'POST',
headers: {
'Authorization': `Bearer ${RESEND_API_KEY}`,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const result = JSON.parse(data);
if (res.statusCode === 200) {
resolve({ success: true, id: result.id, data: result });
} else {
resolve({ success: false, error: result, statusCode: res.statusCode });
}
} catch (error) {
resolve({ success: false, error: error.message });
}
});
});
req.on('error', (error) => {
reject({ success: false, error: error.message });
});
req.write(postData);
req.end();
});
}
// Welcome email template
function generateWelcomeEmail(parentName, childName, childAge) {
return {
from: 'SpellBloc <onboarding@resend.dev>',
subject: `๐ Welcome to SpellBloc, ${childName}!`,
html: `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome to SpellBloc!</title>
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px; text-align: center; border-radius: 15px; margin-bottom: 30px; }
.content { background: #f8f9fa; padding: 30px; border-radius: 15px; margin-bottom: 20px; }
.emoji { font-size: 2em; margin: 10px; }
.button { display: inline-block; background: #28a745; color: white; padding: 15px 30px; text-decoration: none; border-radius: 25px; margin: 20px 0; font-weight: bold; }
.features { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 25px 0; }
.feature { background: white; padding: 20px; border-radius: 10px; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.stats { background: linear-gradient(135deg, #28a745 0%, #20c997 100%); color: white; padding: 25px; border-radius: 10px; text-align: center; margin: 20px 0; }
.footer { text-align: center; color: #666; font-size: 0.9em; margin-top: 30px; }
</style>
</head>
<body>
<div class="header">
<h1>๐ฎ Welcome to SpellBloc!</h1>
<p>Where learning spelling is an adventure!</p>
</div>
<div class="content">
<h2>Hello ${parentName}! ๐</h2>
<p>Thank you for creating a SpellBloc account for <strong>${childName}</strong>! We're so excited to help your ${childAge}-year-old embark on their magical spelling journey.</p>
<div class="stats">
<h3>๐ฏ Perfect for Age ${childAge}</h3>
<p>Our AI has automatically selected the best learning level for ${childName}, with age-appropriate words and challenges.</p>
</div>
<div class="features">
<div class="feature">
<div class="emoji">๐ง </div>
<h3>AI-Powered Learning</h3>
<p>Adapts to ${childName}'s learning style</p>
</div>
<div class="feature">
<div class="emoji">๐</div>
<h3>Achievement Badges</h3>
<p>Earn rewards for every milestone</p>
</div>
<div class="feature">
<div class="emoji">๐</div>
<h3>Progress Tracking</h3>
<p>Watch ${childName}'s skills grow</p>
</div>
<div class="feature">
<div class="emoji">๐</div>
<h3>Multi-Language</h3>
<p>Learn spelling in 5 languages</p>
</div>
</div>
<h3>๐ What's Next?</h3>
<ul>
<li><strong>Start Playing:</strong> ${childName} can begin with age-appropriate words</li>
<li><strong>Earn Badges:</strong> Collect achievements for spelling success</li>
<li><strong>Track Progress:</strong> Receive weekly email reports</li>
<li><strong>Have Fun:</strong> Learning spelling has never been this exciting!</li>
</ul>
<div style="text-align: center;">
<a href="https://wordbloc.vercel.app" class="button">๐ฎ Start ${childName}'s Adventure!</a>
</div>
</div>
<div class="footer">
<p><strong>๐ Welcome to the SpellBloc family!</strong></p>
<p>We'll send you progress updates and achievement notifications to help you celebrate ${childName}'s learning milestones.</p>
<p><small>Questions? Reply to this email - we're here to help!</small></p>
</div>
</body>
</html>
`,
text: `
Welcome to SpellBloc, ${childName}!
Hello ${parentName}!
Thank you for creating a SpellBloc account for ${childName}! We're excited to help your ${childAge}-year-old learn spelling.
Perfect for Age ${childAge}:
Our AI has selected the best learning level for ${childName}, with age-appropriate words and challenges.
Features:
โข AI-Powered Learning - Adapts to ${childName}'s style
โข Achievement Badges - Earn rewards for milestones
โข Progress Tracking - Watch skills grow
โข Multi-Language - Learn in 5 languages
What's Next:
1. Start Playing - Begin with age-appropriate words
2. Earn Badges - Collect achievements for success
3. Track Progress - Receive weekly email reports
4. Have Fun - Learning spelling is exciting!
Start playing: https://wordbloc.vercel.app
Welcome to the SpellBloc family!
We'll send you progress updates and achievement notifications.
Questions? Reply to this email - we're here to help!
`
};
}
// Routes
// Serve login page
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, 'login.html'));
});
// Signup endpoint
app.post('/api/auth/signup', async (req, res) => {
try {
const { parentName, parentEmail, password, childName, childAge } = req.body;
// Validate input
if (!parentName || !parentEmail || !password || !childName || !childAge) {
return res.status(400).json({ message: 'All fields are required' });
}
if (password.length < 6) {
return res.status(400).json({ message: 'Password must be at least 6 characters' });
}
// Check if user already exists
const existingUser = users.find(user => user.email === parentEmail);
if (existingUser) {
return res.status(400).json({ message: 'An account with this email already exists' });
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 10);
// Create user
const user = {
id: userIdCounter++,
parentName,
email: parentEmail,
password: hashedPassword,
childName,
childAge,
createdAt: new Date().toISOString(),
emailPreferences: {
welcome: true,
achievements: true,
progress: true,
milestones: true,
weekly: true
}
};
users.push(user);
await saveUsers();
// Generate JWT token
const token = jwt.sign(
{ userId: user.id, email: user.email },
JWT_SECRET,
{ expiresIn: '7d' }
);
// Send welcome email
console.log(`๐ง Sending welcome email to ${parentEmail}...`);
try {
const welcomeEmailData = generateWelcomeEmail(parentName, childName, childAge);
welcomeEmailData.to = [parentEmail];
const emailResult = await sendEmail(welcomeEmailData);
if (emailResult.success) {
console.log(`โ
Welcome email sent successfully! Email ID: ${emailResult.id}`);
} else {
console.log(`โ Welcome email failed:`, emailResult.error);
}
} catch (emailError) {
console.log(`โ Welcome email error:`, emailError);
}
// Return user data (without password)
const { password: _, ...userWithoutPassword } = user;
res.status(201).json({
message: 'Account created successfully! Welcome email sent.',
user: userWithoutPassword,
token
});
console.log(`โ
New user created: ${parentName} (${parentEmail}) with child ${childName}, age ${childAge}`);
} catch (error) {
console.error('โ Signup error:', error);
res.status(500).json({ message: 'Internal server error' });
}
});
// Login endpoint
app.post('/api/auth/login', async (req, res) => {
try {
const { email, password } = req.body;
// Validate input
if (!email || !password) {
return res.status(400).json({ message: 'Email and password are required' });
}
// Find user
const user = users.find(u => u.email === email);
if (!user) {
return res.status(401).json({ message: 'Invalid email or password' });
}
// Check password
const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
return res.status(401).json({ message: 'Invalid email or password' });
}
// Generate JWT token
const token = jwt.sign(
{ userId: user.id, email: user.email },
JWT_SECRET,
{ expiresIn: '7d' }
);
// Return user data (without password)
const { password: _, ...userWithoutPassword } = user;
res.json({
message: 'Login successful',
user: userWithoutPassword,
token
});
console.log(`โ
User logged in: ${user.parentName} (${email})`);
} catch (error) {
console.error('โ Login error:', error);
res.status(500).json({ message: 'Internal server error' });
}
});
// Get user profile (protected route)
app.get('/api/auth/profile', authenticateToken, (req, res) => {
const user = users.find(u => u.id === req.user.userId);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
const { password: _, ...userWithoutPassword } = user;
res.json(userWithoutPassword);
});
// Middleware to authenticate JWT token
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Access token required' });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ message: 'Invalid or expired token' });
}
req.user = user;
next();
});
}
// Test email endpoint
app.post('/api/test-email', async (req, res) => {
try {
const { email } = req.body;
if (!email) {
return res.status(400).json({ message: 'Email is required' });
}
const testEmailData = {
from: 'SpellBloc <onboarding@resend.dev>',
to: [email],
subject: '๐งช SpellBloc Backend Test Email',
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 10px;">
<h1>โ
Backend Email Test Successful!</h1>
<p>Your SpellBloc backend server is working perfectly!</p>
</div>
<div style="background: #f8f9fa; padding: 25px; border-radius: 10px; margin-top: 20px;">
<h2>๐ฎ SpellBloc Backend Status</h2>
<ul>
<li>โ
Express server running</li>
<li>โ
Resend API connected</li>
<li>โ
Email templates working</li>
<li>โ
Authentication system ready</li>
</ul>
<p>Your SpellBloc authentication and email system is ready for users!</p>
</div>
</div>
`,
text: 'SpellBloc Backend Test - Email system working perfectly!'
};
const result = await sendEmail(testEmailData);
if (result.success) {
res.json({
message: 'Test email sent successfully!',
emailId: result.id
});
} else {
res.status(500).json({
message: 'Failed to send test email',
error: result.error
});
}
} catch (error) {
console.error('โ Test email error:', error);
res.status(500).json({ message: 'Internal server error' });
}
});
// Get all users (for debugging - remove in production)
app.get('/api/users', (req, res) => {
const usersWithoutPasswords = users.map(({ password, ...user }) => user);
res.json({
count: users.length,
users: usersWithoutPasswords
});
});
// Start server
async function startServer() {
await loadUsers();
app.listen(PORT, () => {
console.log('๐ SpellBloc Backend Server Started!');
console.log('=====================================');
console.log(`๐ก Server running on: http://localhost:${PORT}`);
console.log(`๐ Login page: http://localhost:${PORT}/login`);
console.log(`๐ฅ Users in database: ${users.length}`);
console.log(`๐ง Email system: Ready with Resend API`);
console.log('=====================================');
console.log('');
console.log('๐งช Test endpoints:');
console.log(` POST http://localhost:${PORT}/api/test-email`);
console.log(` GET http://localhost:${PORT}/api/users`);
console.log('');
console.log('๐ฎ Ready for SpellBloc users!');
});
}
startServer().catch(console.error);
module.exports = app;