( req: IncomingMessage, res: ServerResponse, serverDir: string, )
| 21 | } |
| 22 | |
| 23 | async function handleRequest( |
| 24 | req: IncomingMessage, |
| 25 | res: ServerResponse, |
| 26 | serverDir: string, |
| 27 | ): Promise<void> { |
| 28 | const url = req.url ?? '/'; |
| 29 | const method = req.method ?? 'GET'; |
| 30 | |
| 31 | if (url === '/login' && method === 'GET') { |
| 32 | const html = await readFile(join(serverDir, 'login.html'), 'utf-8'); |
| 33 | res.writeHead(200, { 'Content-Type': 'text/html' }); |
| 34 | res.end(html); |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | if (url === '/login' && method === 'POST') { |
| 39 | const body = await text(req); |
| 40 | const params = new URLSearchParams(body); |
| 41 | const username = params.get('username'); |
| 42 | const password = params.get('password'); |
| 43 | |
| 44 | if (username === 'testuser' && password === 'testpass') { |
| 45 | res.writeHead(302, { |
| 46 | Location: '/dashboard', |
| 47 | 'Set-Cookie': `${SESSION_COOKIE}; Path=/; HttpOnly`, |
| 48 | }); |
| 49 | res.end(); |
| 50 | } else { |
| 51 | res.writeHead(401, { 'Content-Type': 'text/plain' }); |
| 52 | res.end('Invalid credentials'); |
| 53 | } |
| 54 | return; |
| 55 | } |
| 56 | |
| 57 | if (url === '/dashboard') { |
| 58 | if (!isAuthenticated(req)) { |
| 59 | res.writeHead(302, { Location: '/login' }); |
| 60 | res.end(); |
| 61 | return; |
| 62 | } |
| 63 | const html = await readFile(join(serverDir, 'dashboard.html'), 'utf-8'); |
| 64 | res.writeHead(200, { 'Content-Type': 'text/html' }); |
| 65 | res.end(html); |
| 66 | return; |
| 67 | } |
| 68 | |
| 69 | res.writeHead(302, { Location: '/login' }); |
| 70 | res.end(); |
| 71 | } |
| 72 | |
| 73 | export function createAuthServer(serverDir: string): Server { |
| 74 | return createServer((req, res) => { |
no test coverage detected