scripts/api.py

81 lines
2.4 KiB
Python
Raw Normal View History

2022-05-24 04:01:33 +00:00
from subprocess import check_output
2022-05-24 03:10:31 +00:00
from urllib.parse import parse_qsl
from http.server import BaseHTTPRequestHandler
from adduser import adduser
from ldappass import code
2022-01-06 01:01:32 +00:00
2022-05-24 03:17:07 +00:00
class api(BaseHTTPRequestHandler):
"""User management HTTP server"""
2022-05-24 03:10:31 +00:00
def send(self, code, body):
"""Send HTTP response and body"""
2022-05-24 03:42:47 +00:00
2022-05-24 03:21:57 +00:00
print(code, body)
2022-05-24 03:10:31 +00:00
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"""
2022-05-24 03:42:47 +00:00
if data['code'] != code():
self.send(403, 'Nice try, but that secret code is totally wrong')
return
2022-05-24 03:42:47 +00:00
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
2022-05-24 03:42:47 +00:00
# Add the user
2022-05-24 03:42:47 +00:00
adduser(data['username'], data['firstname'],
data['lastname'], data['email'], data['password'])
self.send(200, 'Well I think it worked...')
2022-05-24 04:01:33 +00:00
def info(self):
"""Return info about the server"""
self.send(200, check_output('neofetch | sed \'s/\\x1B\\[[0-9;\\?]*[a-zA-Z]//g\'', shell=True).decode('utf-8'))
def packages(self):
"""Return the packages installed on the server"""
self.send(200, check_output(['pacman', '-Q']).decode('utf-8'))
2022-05-24 03:10:31 +00:00
def do_GET(self):
"""Handle GET requests"""
2022-05-24 03:42:47 +00:00
2022-05-24 04:01:33 +00:00
if self.path == '/api/server/info':
self.info()
return
elif self.path == '/api/server/packages':
self.packages()
return
self.send(501, 'We don\'t know how to do that yet')
2022-05-24 03:42:47 +00:00
2021-11-22 21:15:48 +00:00
def do_POST(self):
"""Handle API POST requests"""
2021-11-22 21:15:48 +00:00
content_length = int(self.headers['Content-Length'])
2022-05-24 03:21:57 +00:00
try:
2022-05-24 03:42:47 +00:00
data = dict(parse_qsl(self.rfile.read(
content_length).decode('utf-8')))
2022-05-24 03:21:57 +00:00
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)
2021-12-04 01:46:51 +00:00
if self.path == '/api/user/new':
self.usernew(data)
2022-05-24 03:21:57 +00:00
return
2022-05-24 03:42:47 +00:00
2022-05-24 03:21:57 +00:00
self.send(501, 'We don\'t know how to do that yet')