scripts/api.py

64 lines
1.9 KiB
Python

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"""
print(code, body)
self.send_response(code)
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 usernew(self, data):
"""Register a new user"""
if data['code'] != code():
self.send(403, 'Nice try, but that secret code is totally wrong')
return
if not all(c.isdigit() or c.islower() for c in data['username']) or data['username'][0].isdigit():
self.send(403, 'I don\'t like that username')
return
# Add the user
adduser(data['username'], data['firstname'],
data['lastname'], data['email'], data['password'])
self.send(200, 'Well I think it worked...')
def do_GET(self):
"""Handle GET requests"""
self.send(200, 'Hey there, you\'ve reached the top secret API')
def do_POST(self):
"""Handle API POST requests"""
content_length = int(self.headers['Content-Length'])
try:
data = dict(parse_qsl(self.rfile.read(
content_length).decode('utf-8')))
except:
self.send(400, 'Oops, that request doesn\'t look quite right')
# Print debug data
debug = data.copy()
debug.pop('password')
debug.pop('confirmpassword')
print(debug)
if self.path == '/api/user/new':
self.usernew(data)
return
self.send(501, 'We don\'t know how to do that yet')