-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathserver.ts
More file actions
100 lines (88 loc) · 2.67 KB
/
server.ts
File metadata and controls
100 lines (88 loc) · 2.67 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
import { readFile } from 'node:fs/promises';
import {
type IncomingMessage,
type Server,
type ServerResponse,
createServer,
} from 'node:http';
import { join } from 'node:path';
import { text } from 'node:stream/consumers';
const SESSION_COOKIE = 'session=authenticated';
function getCookie(req: IncomingMessage, name: string): string | undefined {
const cookies = req.headers.cookie?.split(';').map(c => c.trim()) ?? [];
const cookie = cookies.find(c => c.startsWith(`${name}=`));
return cookie?.split('=')[1];
}
function isAuthenticated(req: IncomingMessage): boolean {
return getCookie(req, 'session') === 'authenticated';
}
async function handleRequest(
req: IncomingMessage,
res: ServerResponse,
serverDir: string,
): Promise<void> {
const url = req.url ?? '/';
const method = req.method ?? 'GET';
if (url === '/login' && method === 'GET') {
const html = await readFile(join(serverDir, 'login.html'), 'utf-8');
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
return;
}
if (url === '/login' && method === 'POST') {
const body = await text(req);
const params = new URLSearchParams(body);
const username = params.get('username');
const password = params.get('password');
if (username === 'testuser' && password === 'testpass') {
res.writeHead(302, {
Location: '/dashboard',
'Set-Cookie': `${SESSION_COOKIE}; Path=/; HttpOnly`,
});
res.end();
} else {
res.writeHead(401, { 'Content-Type': 'text/plain' });
res.end('Invalid credentials');
}
return;
}
if (url === '/dashboard') {
if (!isAuthenticated(req)) {
res.writeHead(302, { Location: '/login' });
res.end();
return;
}
const html = await readFile(join(serverDir, 'dashboard.html'), 'utf-8');
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
return;
}
res.writeHead(302, { Location: '/login' });
res.end();
}
export function createAuthServer(serverDir: string): Server {
return createServer((req, res) => {
handleRequest(req, res, serverDir).catch(error => {
console.error('Server error:', error);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
});
});
}
export function startServer(server: Server, port: number): Promise<void> {
return new Promise((resolve, reject) => {
server.on('error', reject);
server.listen(port, () => resolve());
});
}
export function stopServer(server: Server): Promise<void> {
return new Promise((resolve, reject) => {
server.close(err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}