File size: 1,933 Bytes
2ee2c2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
from pathlib import Path

# Function to check credentials
def check_credentials(username, password):
    # Replace with your authentication logic
    return username == 'admin' and password == 'password'

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed_path = urlparse(self.path)
        path = parsed_path.path
        if path == '/':
            self._send_html_response('templates/index.html')
        elif path == '/login':
            self._send_html_response('templates/login.html')
        else:
            self.send_error(404, "File not found")

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length).decode('utf-8')
        params = parse_qs(post_data)
        username = params['username'][0]
        password = params['password'][0]

        if check_credentials(username, password):
            self.send_response(302)
            self.send_header('Location', '/index.html')
            self.end_headers()
        else:
            self._send_html_response('templates/login.html')

    def _send_html_response(self, page):
        path = Path(page)
        if path.exists() and path.is_file():
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            with open(page, 'rb') as file:
                self.wfile.write(file.read())
        else:
            self.send_error(404, "File not found")

def run(server_class=HTTPServer, handler_class=RequestHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Starting httpd on port {port}...')
    httpd.serve_forever()

if __name__ == '__main__':
    run()