-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
305 lines (251 loc) · 8.23 KB
/
server.js
File metadata and controls
305 lines (251 loc) · 8.23 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
import express from 'express';
import cors from 'cors';
import pg from 'pg';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
const { Pool } = pg;
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
// Database
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false
});
// Initialize database
async function initDB() {
await pool.query(`
CREATE TABLE IF NOT EXISTS users (
email VARCHAR(255) PRIMARY KEY,
password_hash VARCHAR(255) NOT NULL,
credits INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS tasks (
id SERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
status VARCHAR(50) DEFAULT 'pending',
credits_spent INTEGER DEFAULT 10,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS redeemed_codes (
email VARCHAR(255) NOT NULL,
code VARCHAR(50) NOT NULL,
redeemed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (email, code)
)
`);
}
initDB().catch(console.error);
// Credit codes
const CODES = {
'BETA10K': 10000,
'BETA5K': 5000,
'WELCOME': 1000
};
// Helper functions
function generateToken(email) {
return jwt.sign({ email }, 'impacteragi-secret-key', { expiresIn: '7d' });
}
function getUserFromToken(token) {
try {
const decoded = jwt.verify(token, 'impacteragi-secret-key');
return decoded.email;
} catch {
return null;
}
}
// Routes
app.post('/api/auth/signup', async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Email and password required' });
}
if (password.length < 8) {
return res.status(400).json({ error: 'Password must be at least 8 characters' });
}
// Check if exists
const existing = await pool.query('SELECT email FROM users WHERE email = $1', [email]);
if (existing.rows.length > 0) {
return res.status(409).json({ error: 'User already exists' });
}
// Create user
const passwordHash = await bcrypt.hash(password, 10);
await pool.query(
'INSERT INTO users (email, password_hash, credits) VALUES ($1, $2, 0)',
[email, passwordHash]
);
const token = generateToken(email);
res.json({ success: true, token, email, credits: 0 });
} catch (error) {
console.error('Signup error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.post('/api/auth/login', async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Email and password required' });
}
const result = await pool.query(
'SELECT email, password_hash, credits FROM users WHERE email = $1',
[email]
);
if (result.rows.length === 0) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const user = result.rows[0];
const isValid = await bcrypt.compare(password, user.password_hash);
if (!isValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = generateToken(email);
res.json({ success: true, token, email, credits: user.credits });
} catch (error) {
console.error('Login error:', error);
res.status(401).json({ error: 'Invalid credentials' });
}
});
app.get('/api/user', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
const token = authHeader.substring(7);
const email = getUserFromToken(token);
if (!email) {
return res.status(401).json({ error: 'Invalid token' });
}
const result = await pool.query(
'SELECT email, credits, created_at FROM users WHERE email = $1',
[email]
);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ success: true, ...result.rows[0] });
} catch (error) {
console.error('User API error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.post('/api/redeem', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
const token = authHeader.substring(7);
const email = getUserFromToken(token);
if (!email) {
return res.status(401).json({ error: 'Invalid token' });
}
const { code } = req.body;
if (!code) {
return res.status(400).json({ error: 'Code required' });
}
const codeUpper = code.toUpperCase();
const credits = CODES[codeUpper];
if (!credits) {
return res.status(400).json({ error: 'Invalid code' });
}
// Check if already redeemed
const redeemed = await pool.query(
'SELECT 1 FROM redeemed_codes WHERE email = $1 AND code = $2',
[email, codeUpper]
);
if (redeemed.rows.length > 0) {
return res.status(400).json({ error: 'Code already redeemed' });
}
// Add credits
const result = await pool.query(
'UPDATE users SET credits = credits + $1 WHERE email = $2 RETURNING credits',
[credits, email]
);
// Mark as redeemed
await pool.query(
'INSERT INTO redeemed_codes (email, code) VALUES ($1, $2)',
[email, codeUpper]
);
const newTotal = result.rows[0].credits;
res.json({ success: true, credits: newTotal, message: `Successfully redeemed ${credits} credits!` });
} catch (error) {
console.error('Redeem error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/api/tasks', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
const token = authHeader.substring(7);
const email = getUserFromToken(token);
if (!email) {
return res.status(401).json({ error: 'Invalid token' });
}
const result = await pool.query(
'SELECT * FROM tasks WHERE email = $1 ORDER BY created_at DESC',
[email]
);
res.json({ success: true, tasks: result.rows });
} catch (error) {
console.error('Tasks error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.post('/api/tasks', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
const token = authHeader.substring(7);
const email = getUserFromToken(token);
if (!email) {
return res.status(401).json({ error: 'Invalid token' });
}
const { description } = req.body;
if (!description) {
return res.status(400).json({ error: 'Description required' });
}
// Check credits
const userResult = await pool.query('SELECT credits FROM users WHERE email = $1', [email]);
const userCredits = userResult.rows[0].credits;
if (userCredits < 10) {
return res.status(400).json({ error: 'Insufficient credits', required: 10, available: userCredits });
}
// Create task
await pool.query(
'INSERT INTO tasks (email, description, status, credits_spent) VALUES ($1, $2, $3, $4)',
[email, description, 'pending', 10]
);
// Deduct credits
const result = await pool.query(
'UPDATE users SET credits = credits - 10 WHERE email = $1 RETURNING credits',
[email]
);
const newCredits = result.rows[0].credits;
res.json({ success: true, credits: newCredits, message: 'Task submitted successfully' });
} catch (error) {
console.error('Task creation error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
app.listen(PORT, () => {
console.log(`ImpacterAGI API running on port ${PORT}`);
});