Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 0 additions & 100 deletions api/servers

This file was deleted.

44 changes: 0 additions & 44 deletions login

This file was deleted.

44 changes: 44 additions & 0 deletions user/lib/cgi-bin/api/servers
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#! /usr/bin/python3

import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from http.cookies import SimpleCookie
from get_servers import get_all_servers, get_server
from utils import *

def main():
# extract basic request info
request_method = os.environ["REQUEST_METHOD"]
extra_path = os.environ.get("PATH_INFO", "")

# Get user field from cookie
cookie_string = os.environ.get("HTTP_COOKIE", "")
parsed = SimpleCookie(cookie_string)
user = parsed.get("user").value if "user" in parsed else None

if not user: # Redirect to login
print_redirect_300(f"login.html")
return

if request_method == "GET":
if extra_path == "" or extra_path == "/":
# return all instances in database
resp = get_all_servers(user)
print_json_200(resp)

elif extra_path.startswith("/") and extra_path[1:].isnumeric(): # /api/servers/<id>
# return a single instance in db
primary_key = int(extra_path[1:])
resp = get_server(primary_key, user)
if resp == {}:
print_status_400("can't find server with this id in the database")
print_json_200(resp)

else:
print_status_400("Page not found: " + extra_path)

else:
print_status_405(extra_path, "GET")

if __name__ == "__main__":
main()
52 changes: 5 additions & 47 deletions create_server → user/lib/cgi-bin/create_server
Original file line number Diff line number Diff line change
Expand Up @@ -6,51 +6,16 @@ import MySQLdb
import config
from pydo import Client
from http.cookies import SimpleCookie
from utils import *

config_commands = """#cloud-config
runcmd:
- apt update
- apt install apache2 -y
- systemctl enable apache2
- mkdir -p /etc/systemd/system/apache2.service.d/
- bash -c 'echo -e "[Unit]\nAfter=network-online.target\nWants=network-online.target" > /etc/systemd/system/apache2.service.d/override.conf'
- systemctl daemon-reload
- systemctl restart apache2
- echo "hello, world" > /root/dummy.txt
- systemctl start apache2
"""

def print_status_400(body: str):
print("Status: 400 Bad Request")
print("Content-Type: text/plain\n")
print(f"Invalid Request: {body}")

def print_status_405(extra_path: str, allowed_method: str):
print("Status 405: Method Not Allowed")
print("Content-Type: text/plain\n")
print(f"Method '{allowed_method}' isn't allowed for path: '{extra_path}'\n \
Allowed method: POST")

def print_status_500(body: str):
print("Status: 500 Internal Server Error")
print("Content-Type: text/plain\n")
print(f"Database Connection Error: {body}")

def get_db_connection():
try:
db = MySQLdb.connect(
host=config.DB_HOST,
user=config.DB_USER,
passwd=config.DB_PASSWORD,
db=config.DB_NAME,
port=config.DB_PORT,
ssl={"ssl": {}}
)
return db

except MySQLdb.Error as e:
print_status_500(str(e))
exit(1)

def create_server(user: str, desc: str) -> int:
try:
if (user == "" and desc is None):
Expand Down Expand Up @@ -98,9 +63,7 @@ def add_server_to_db(user: str, desc: str, instance_id: int, ready: bool):
# run background script
os.system(f"./monitor_new_VM {instance_id} {new_server_id} 1>/dev/null 2>/dev/null &")

print("Status: 303 See Other")
print(f"Location: {config.ROOT_URL}/cgi-bin/api/servers/{new_server_id}")
print()
print_redirect_300("cgi-bin/home")

except Exception as e:
print_status_500(str(e))
Expand All @@ -109,17 +72,12 @@ def main():
# extract basic request info
request_method = os.environ["REQUEST_METHOD"]
extra_path = os.environ.get("PATH_INFO", "").lstrip("/")
path_component = extra_path.split("/")
if request_method == "POST" or request_method == "GET": # read query parameter case of GET/POST method
form = cgi.FieldStorage()
# Get user field from cookie
cookie_string = os.environ.get("HTTP_COOKIE", "")
parsed = SimpleCookie(cookie_string)
user = parsed.get("user").value if "user" in parsed else None
user = get_cookie()
if not user: # Redirect to login
print("Status: 303 See Other")
print(f"Location: {config.ROOT_URL}/login.html")
print()
print_redirect_300("login.html")
return
# Get desc field from query param
desc = form.getvalue("desc", None)
Expand Down
48 changes: 48 additions & 0 deletions user/lib/cgi-bin/get_servers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from utils import get_db_connection

def get_all_servers(user: str) -> list[dict]:
db = get_db_connection()
cursor = db.cursor()
# return all instances in database
cursor.execute("SELECT * FROM servers WHERE owner = %s;", (user,))
rows = cursor.fetchall()

cursor.close()
db.close()

resp = []
for row in rows:
resp.append(
{
"id": row[0],
"owner": row[1],
"description": row[2],
"instance_id": row[3],
"public_ip": row[4],
"ready": row[5]
}
)
return resp

def get_server(primary_key: int, user: str) -> dict:
db = get_db_connection()
cursor = db.cursor()
# return a single instance in db
cursor.execute("SELECT * FROM servers WHERE id = %s AND owner = %s;", (primary_key, user,))
row = cursor.fetchone()

cursor.close()
db.close()

if row is None:
return {}

resp = {
"id": row[0],
"owner": row[1],
"description": row[2],
"instance_id": row[3],
"public_ip": row[4],
"ready": row[5]
}
return resp
Loading