-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite-dev-server.js
More file actions
231 lines (200 loc) Β· 6.93 KB
/
vite-dev-server.js
File metadata and controls
231 lines (200 loc) Β· 6.93 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
require('dotenv/config');
const { createServer } = require('vite');
const { createServer: createHttpServer } = require('http');
const { parse } = require('url');
const { Pool } = require('pg');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const PORT = process.env.PORT || 5000;
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
// Database connection
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
// Helper functions
function parseBody(req) {
return new Promise((resolve) => {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
resolve(body ? JSON.parse(body) : {});
} catch {
resolve({});
}
});
});
}
function setHeaders(res, contentType = 'application/json') {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Content-Type', contentType);
}
async function authenticateToken(req, res, next) {
const authHeader = req.headers.authorization;
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
setHeaders(res);
res.writeHead(401);
res.end(JSON.stringify({ error: 'Access token required' }));
return;
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
setHeaders(res);
res.writeHead(403);
res.end(JSON.stringify({ error: 'Invalid token' }));
}
}
async function startServer() {
console.log('π Starting Vite development server...');
// Create Vite server
const vite = await createServer({
server: { middlewareMode: true },
appType: 'spa'
});
// Create HTTP server
const server = createHttpServer(async (req, res) => {
const url = parse(req.url || '/', true);
const pathname = url.pathname || '/';
setHeaders(res);
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// API routes
if (pathname.startsWith('/api/')) {
try {
// Parse request body for POST/PUT requests
if (req.method === 'POST' || req.method === 'PUT') {
req.body = await parseBody(req);
}
// Health check
if (pathname === '/api/health' && req.method === 'GET') {
res.writeHead(200);
res.end(JSON.stringify({
status: 'ok',
timestamp: new Date().toISOString(),
database: 'connected',
authentication: 'JWT enabled',
server: 'Vite + Node.js',
port: PORT
}));
return;
}
// Register endpoint
if (pathname === '/api/register' && req.method === 'POST') {
const { username, password } = req.body;
if (!username || !password) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Username and password required' }));
return;
}
try {
// Check if user exists
const existingUser = await pool.query('SELECT id FROM users WHERE username = $1', [username]);
if (existingUser.rows.length > 0) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Username already exists' }));
return;
}
// Hash password and create user
const hashedPassword = await bcrypt.hash(password, 10);
const result = await pool.query(
'INSERT INTO users (username, password_hash) VALUES ($1, $2) RETURNING id, username',
[username, hashedPassword]
);
const user = result.rows[0];
const token = jwt.sign({ userId: user.id, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
res.writeHead(201);
res.end(JSON.stringify({ token, user }));
} catch (error) {
console.error('Registration error:', error);
res.writeHead(500);
res.end(JSON.stringify({ error: 'Registration failed' }));
}
return;
}
// Login endpoint
if (pathname === '/api/login' && req.method === 'POST') {
const { username, password } = req.body;
if (!username || !password) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Username and password required' }));
return;
}
try {
const result = await pool.query('SELECT id, username, password_hash FROM users WHERE username = $1', [username]);
if (result.rows.length === 0) {
res.writeHead(401);
res.end(JSON.stringify({ error: 'Invalid credentials' }));
return;
}
const user = result.rows[0];
const validPassword = await bcrypt.compare(password, user.password_hash);
if (!validPassword) {
res.writeHead(401);
res.end(JSON.stringify({ error: 'Invalid credentials' }));
return;
}
const token = jwt.sign({ userId: user.id, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
res.writeHead(200);
res.end(JSON.stringify({ token, user: { id: user.id, username: user.username } }));
} catch (error) {
console.error('Login error:', error);
res.writeHead(500);
res.end(JSON.stringify({ error: 'Login failed' }));
}
return;
}
// User endpoint (protected)
if (pathname === '/api/user' && req.method === 'GET') {
return authenticateToken(req, res, () => {
res.writeHead(200);
res.end(JSON.stringify({
id: req.user.userId,
username: req.user.username
}));
});
}
// Default API response
res.writeHead(404);
res.end(JSON.stringify({ error: 'API endpoint not found' }));
return;
} catch (error) {
console.error('API Error:', error);
res.writeHead(500);
res.end(JSON.stringify({ error: 'Internal server error' }));
return;
}
}
// Use Vite's middleware for everything else
vite.middlewares(req, res, () => {
res.writeHead(404);
res.end('Not found');
});
});
server.listen(PORT, '0.0.0.0', () => {
console.log(`π Server running on http://0.0.0.0:${PORT}`);
console.log('π Database: PostgreSQL connected');
console.log('π JWT Authentication: Enabled');
console.log('β‘ Vite: Development server active');
console.log('β
Server ready for connections');
});
// Handle server shutdown
process.on('SIGTERM', () => {
console.log('Shutting down server...');
server.close(() => {
vite.close();
process.exit(0);
});
});
}
startServer().catch(console.error);