from subprocess import run, check_output from urllib.parse import parse_qsl from http.server import BaseHTTPRequestHandler from adduser import adduser from ldappass import code class api(BaseHTTPRequestHandler): """User management HTTP server""" def send(self, code, body): """Send HTTP response and body""" self.send_response(code) self.send_response(200) self.send_header('Content-Type', 'text/plain') self.send_header('Content-Length', str(len(body))) self.end_headers() self.wfile.write(body.encode('utf-8')) def do_GET(self): """Handle GET requests""" self.send(200, 'Hello') def do_POST(self): """Handle API POST requests""" content_length = int(self.headers['Content-Length']) data = dict(parse_qsl(self.rfile.read(content_length).decode('utf-8'))) # Print debug data debug = data.copy() debug.pop('password') debug.pop('confirmpassword') print(debug) if self.path == '/api/join': # New user if data['code'] != code(): print('Incorrect code') self.send(403, 'Incorrect code') return if not all(c.isdigit() or c.islower() for c in data['username']) or data['username'][0].isdigit(): print('Bad username') self.send(403, 'Bad username') return # Add the user adduser(data['username'], data['firstname'].capitalize(), data['lastname'].capitalize(), data['email'], data['password']) else: print('Bad request') self.send(400, 'Bad request') return self.send(200, 'It worked!')