summaryrefslogtreecommitdiff
path: root/backend/main.py
diff options
context:
space:
mode:
Diffstat (limited to 'backend/main.py')
-rw-r--r--backend/main.py236
1 files changed, 195 insertions, 41 deletions
diff --git a/backend/main.py b/backend/main.py
index c69247f..e242389 100644
--- a/backend/main.py
+++ b/backend/main.py
@@ -11,12 +11,15 @@ from onesignal.api import default_api
import sqlite3
from typing import Annotated
import datetime
+from zoneinfo import ZoneInfo
from pydantic import BaseModel
import secrets
from enum import Enum, IntEnum
from dotenv import load_dotenv
from os import getenv
import yaml
+import notif # import notif.py
+import bcrypt
# ## API, db, and scheduler initialisation
app = fastapi.FastAPI(title="Victoria Hall LaundryWeb", description="LaundryWeb Backend API", version="0.1")
@@ -28,12 +31,14 @@ scheduler.start()
origins = [
"http://localhost",
+ "http://localhost:8081",
"http://localhost:998",
"http://localhost:5173",
"http://127.0.0.1",
"http://127.0.0.1:998",
"http://127.0.0.1:5173",
- "https://laundryweb.altafcreator.com"
+ "https://laundryweb.altafcreator.com",
+ "https://backend.laundryweb.altafcreator.com"
]
app.add_middleware(
@@ -56,6 +61,13 @@ CREATE TABLE IF NOT EXISTS timers (
subscription_id TEXT NOT NULL
);""") # block is either 1 or 2, machine (1-4), odd is dryer, even is machine.
+cursor.execute("""
+CREATE TABLE IF NOT EXISTS admin_cookies (
+ cookie VARCHAR(64) PRIMARY KEY
+);
+""")
+
+cursor.execute("DELETE FROM admin_cookies;")
class RowIndices(IntEnum):
TIMER_ID = 0,
@@ -106,7 +118,6 @@ ONESIGNAL_APP_ID = "83901cc7-d964-475a-90ec-9f854df4ba52"
class RequestData(BaseModel):
duration: int
machine_id: str
- onesignal_subscription_id: str
class InformationRequestData(BaseModel):
@@ -121,6 +132,12 @@ class FinishRequestData(BaseModel):
id: int
+class OverrideMachineData(BaseModel):
+ block: int
+ machine_id: int
+ disabled: bool
+
+
class Status(Enum):
EMPTY = 0,
FINISHED = 1,
@@ -128,6 +145,10 @@ class Status(Enum):
OUTOFSERVICE = 3,
+class PlaintextPasswordData(BaseModel):
+ password: str
+
+
URI_TO_MACHINES = {
"h1-status": [1, None],
"h1-dryer1": [1, 1],
@@ -141,6 +162,7 @@ URI_TO_MACHINES = {
"h2-washer2": [2, 4],
}
+TZ = "Asia/Jakarta"
# ## global vars for user-end
@@ -164,7 +186,7 @@ def restart_terminated_schedules():
for row in out:
print(row)
end_date = datetime.datetime.fromisoformat(row[RowIndices.END_TIME])
- now = datetime.datetime.now()
+ now = datetime.datetime.now(ZoneInfo(TZ))
timer_id = row[RowIndices.TIMER_ID]
if now > end_date:
@@ -187,57 +209,56 @@ def restart_terminated_schedules():
def reminder_timer_finished(timer_id):
print("timer almost finished", timer_id)
- cursor.execute(f"SELECT * FROM timers WHERE timer_id = '{timer_id}'")
+ cursor.execute("SELECT * FROM timers WHERE timer_id = ?", (timer_id,))
out = cursor.fetchall()
+ print(out)
scheduler.add_job(final_timer_finished, 'date', run_date=out[0][RowIndices.END_TIME], id=str(timer_id), args=[timer_id])
- notification = Notification(app_id=ONESIGNAL_APP_ID,
- include_subscription_ids=[out[0][RowIndices.SUBSCRIPTION_ID]],
- contents={'en': 'get ready to get your bloody laundry'},
- headings={'en': 'Laundry Reminder'},
- priority=10)
-
- try:
- api_response = api_instance.create_notification(notification)
- except Exception as e:
- print(e)
-
+ notif.send_notification(
+ out[0][RowIndices.SUBSCRIPTION_ID],
+ {
+ "title": "Laundry Reminder",
+ "body": "Your laundry is almost finished.",
+ }
+ )
def final_timer_finished(timer_id):
print("timer finished!1", timer_id)
- cursor.execute(f"SELECT * FROM timers WHERE timer_id = '{timer_id}'")
+ cursor.execute("SELECT * FROM timers WHERE timer_id = ?", (timer_id,))
out = cursor.fetchall()
- notification = Notification(app_id=ONESIGNAL_APP_ID,
- include_subscription_ids=[out[0][RowIndices.SUBSCRIPTION_ID]],
- contents={'en': 'get your bloody laundry'},
- headings={'en': 'Laundry Finished'},
- priority=10)
-
- try:
- api_response = api_instance.create_notification(notification)
- except Exception as e:
- print(e)
-
for row in out:
machine_status[row[RowIndices.BLOCK] - 1][row[RowIndices.MACHINE] - 1] = Status.FINISHED.name
+ notif.send_notification(
+ out[0][RowIndices.SUBSCRIPTION_ID],
+ {
+ "title": "Laundry Finished",
+ "body": "Your laundry is finished! Please collect your laundry.",
+ "requireInteraction": True,
+ "timerId": timer_id,
+ }
+ )
+
+# sec min hrs days
+COOKIE_MAX_AGE = 60 * 60 * 24 * 30 # 30 days
+
def create_session(response: fastapi.Response):
cookie = secrets.token_hex(32)
- response.set_cookie(key="session_key", value=cookie)
+ response.set_cookie(key="session_key", value=cookie, secure=True, max_age=COOKIE_MAX_AGE)
return cookie
def authenticate_block(response: fastapi.Response, machine_id: str = None, block: int = None):
if machine_id:
blk = URI_TO_MACHINES[qr_uri[machine_id]][0]
- response.set_cookie(key="auth_block", value=blk)
+ response.set_cookie(key="auth_block", value=blk, secure=True, max_age=COOKIE_MAX_AGE)
return blk
elif block:
blk = block
- response.set_cookie(key="auth_block", value=blk)
+ response.set_cookie(key="auth_block", value=blk, secure=True, max_age=COOKIE_MAX_AGE)
return block
else:
return "FAIL"
@@ -255,8 +276,8 @@ restart_terminated_schedules()
# eugh. too complex. TODO: refactor perhaps
# it's so complex even the linter is complaining
@app.post("/start", response_class=PlainTextResponse)
-def start_new_timer(data: RequestData, response: fastapi.Response, session_key: Annotated[str | None, fastapi.Cookie()] = None, auth_block: Annotated[str | None, fastapi.Cookie()] = None):
- now = datetime.datetime.now()
+def start_new_timer(data: RequestData, response: fastapi.Response, session_key: Annotated[str | None, fastapi.Cookie()] = None, auth_block: Annotated[str | None, fastapi.Cookie()] = None, subscription_endpoint: Annotated[str | None, fastapi.Cookie()] = None):
+ now = datetime.datetime.now(ZoneInfo(TZ))
try:
if not session_key:
print("no session key, creating.")
@@ -280,15 +301,19 @@ def start_new_timer(data: RequestData, response: fastapi.Response, session_key:
else:
authenticate_block(response, machine_id=data.machine_id)
+ if not subscription_endpoint:
+ print("user is not subscribed to notif")
+ response.status_code = fastapi.status = fastapi.status.HTTP_401_UNAUTHORIZED
+ return "a notification subscription is required to start a timer"
+
try:
print("session key valid", session_key)
end_date = now + datetime.timedelta(minutes=(data.duration * 30))
- cursor.execute(f"""
+ cursor.execute("""
INSERT INTO timers (user_id, start_time, end_time, block, machine, status, subscription_id)
- VALUES ('{session_key}', '{now.isoformat()}', '{end_date.isoformat()}', {block}, {machine}, 'RUNNING', '{data.onesignal_subscription_id}')
- """)
+ VALUES (?, ?, ?, ?, ?, ?, ?)""", (session_key, now.isoformat(), end_date.isoformat(), block, machine, 'RUNNING', subscription_endpoint,))
conn.commit()
- cursor.execute("SELECT * FROM timers;")
+ cursor.execute("SELECT * FROM timers WHERE end_time = ?;", (end_date.isoformat(),))
out = cursor.fetchall()
for row in out:
@@ -329,7 +354,7 @@ def check_status(response: fastapi.Response, session_key: Annotated[str | None,
print("no session key, creating.")
session_key = create_session(response)
- cursor.execute(f"SELECT * FROM timers WHERE user_id = '{session_key}'")
+ cursor.execute("SELECT * FROM timers WHERE user_id = ?", (session_key,))
out = cursor.fetchall()
for row in out:
@@ -358,7 +383,7 @@ def get_laundry_info(response: fastapi.Response, session_key: Annotated[str | No
if session_key:
result = []
- cursor.execute(f"SELECT * FROM timers WHERE user_id = '{session_key}'")
+ cursor.execute("SELECT * FROM timers WHERE user_id = ?", (session_key,))
out = cursor.fetchall()
for row in out:
@@ -387,10 +412,10 @@ def get_laundry_info(response: fastapi.Response, session_key: Annotated[str | No
@app.post("/finish", response_class=PlainTextResponse)
def finish_laundry(data: FinishRequestData, response: fastapi.Response, session_key: Annotated[str | None, fastapi.Cookie()] = None):
if session_key:
- cursor.execute(f"SELECT * FROM timers WHERE timer_id = '{data.id}'")
+ cursor.execute("SELECT * FROM timers WHERE timer_id = ?", (data.id,))
row = cursor.fetchall()[0]
- if datetime.datetime.now() < datetime.datetime.fromisoformat(row[RowIndices.END_TIME]):
+ if datetime.datetime.now(ZoneInfo(TZ)) < datetime.datetime.fromisoformat(row[RowIndices.END_TIME]):
response.status_code = fastapi.status.HTTP_400_BAD_REQUEST
return "timer has not finished yet"
@@ -398,7 +423,7 @@ def finish_laundry(data: FinishRequestData, response: fastapi.Response, session_
machine_times[row[RowIndices.BLOCK] - 1][row[RowIndices.MACHINE] - 1] = None
machine_endings[row[RowIndices.BLOCK] - 1][row[RowIndices.MACHINE] - 1] = None
- cursor.execute(f"DELETE FROM timers WHERE timer_id = {row[0]}")
+ cursor.execute("DELETE FROM timers WHERE timer_id = ?", (row[0],))
conn.commit()
print(f"timer of id {data.id} has been finished by {session_key}")
@@ -440,3 +465,132 @@ def uri_to_information(data: InformationRequestData, response: fastapi.Response,
return "NO INFORMATION PROVIDED. NO AUTH COOKIE."
return {"block": info[0], "machine": info[1]}
+
+
+# #### NOTIFICATION API END POINTS ####
+
+
+# --- subscribe
+@app.post("/notifsubscribe", response_class=PlainTextResponse)
+def notif_subscribe(data: notif.PushSubscriptionData, response: fastapi.Response):
+ try:
+ endpoint = notif.subscribe(data)
+ response.set_cookie(key="subscription_endpoint", value=endpoint, max_age=COOKIE_MAX_AGE, domain="laundryweb.altafcreator.com", samesite="none", secure=True, path="/")
+ response.status_code = fastapi.status.HTTP_200_OK
+ return "subscription saved."
+ except Exception as err:
+ response.status_code = fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR
+ return f"error, failed to save subscription {err}"
+
+
+# #### ADMIN PANEL API END POINTS ####
+
+# ## ADMIN PANEL SCHEDULER METHODS ##
+
+
+def delete_cookie_scheduler(cookie):
+ pass
+
+
+def authenticate_admin_check(cookie):
+ cursor.execute("SELECT * FROM admin_cookies WHERE cookie = ?", (cookie,))
+ rows = cursor.fetchall()
+
+ return len(rows) > 0
+
+
+# --- admin login
+@app.post("/admin_login", response_class=PlainTextResponse)
+def admin_login(data: PlaintextPasswordData, response: fastapi.Response):
+ print(data.password)
+
+ pwd = data.password.encode('utf-8')
+ stored_hash_pwd = getenv("ADMIN_PASSWORD_HASH").encode('utf-8')
+
+ if bcrypt.checkpw(pwd, stored_hash_pwd):
+ response.status_code = fastapi.status.HTTP_202_ACCEPTED
+
+ auth_cookie_str = secrets.token_hex(32)
+ AUTH_MAX_AGE = 60 * 10 # 10 minutes
+ response.set_cookie(key="admin_auth", value=auth_cookie_str, secure=True, max_age=AUTH_MAX_AGE, domain="backend.laundryweb.altafcreator.com", samesite="none")
+ cursor.execute("""INSERT INTO admin_cookies (cookie) VALUES (?);""", (auth_cookie_str,))
+ conn.commit()
+ cursor.execute("SELECT * FROM admin_cookies")
+ print(cursor.fetchall())
+
+ now = datetime.datetime.now(ZoneInfo(TZ))
+ end_date = now + datetime.timedelta(seconds=(AUTH_MAX_AGE))
+ scheduler.add_job(delete_cookie_scheduler, 'date', run_date=end_date, args=[auth_cookie_str])
+
+ return "hi admin you are Authenticated!!!11"
+
+ response.status_code = fastapi.status.HTTP_403_FORBIDDEN
+ return "Forbidden."
+
+
+# --- admin auth check
+@app.post("/admin_check", response_class=PlainTextResponse)
+def admin_check(response: fastapi.Response, admin_auth: Annotated[str | None, fastapi.Cookie()] = None):
+ print("admin check request, ", admin_auth)
+
+ if authenticate_admin_check(admin_auth):
+ response.status_code = fastapi.status.HTTP_202_ACCEPTED
+ return "Authorised."
+ else:
+ response.status_code = fastapi.status.HTTP_401_UNAUTHORIZED
+ return "Get out."
+
+
+# --- override each machine status
+@app.post("/override_status", response_class=PlainTextResponse)
+def override_status(data: OverrideMachineData, response: fastapi.Response, admin_auth: Annotated[str | None, fastapi.Cookie()] = None):
+ if not admin_auth:
+ response.status_code = fastapi.status.HTTP_401_UNAUTHORIZED
+ return "Unauthorised."
+
+ if authenticate_admin_check(admin_auth):
+ if (data.disabled):
+ machine_status[data.block - 1][data.machine_id - 1] = Status.OUTOFSERVICE.name
+ else:
+ cursor.execute("SELECT * FROM timers WHERE ((block = ?) AND (machine = ?))", (data.block, data.machine_id))
+ rows = cursor.fetchall()
+
+ if len(rows) > 0:
+ machine_status[data.block - 1][data.machine_id - 1] = Status.RUNNING.name
+ else:
+ machine_status[data.block - 1][data.machine_id - 1] = Status.EMPTY.name
+
+ response.status_code = fastapi.status.HTTP_200_OK
+ return "Set!"
+
+ print("set machine", data.machine_id, "of block", data.block, ".", machine_status)
+ else:
+ response.status_code = fastapi.status.HTTP_403_FORBIDDEN
+ return "Forbidden."
+
+
+# --- change admin password
+@app.post("/admin_change_password", response_class=PlainTextResponse)
+def admin_change_password(data: PlaintextPasswordData, response: fastapi.Response, admin_auth: Annotated[str | None, fastapi.Cookie()] = None):
+ if not admin_auth:
+ response.status_code = fastapi.status.HTTP_401_UNAUTHORIZED
+ return "Unauthorised."
+
+ if authenticate_admin_check(admin_auth):
+ pass
+ else:
+ pass
+
+
+# --- get all blocks machine status for admin
+@app.post("/admin_machine_status")
+def admin_machine_status(response: fastapi.Response, admin_auth: Annotated[str | None, fastapi.Cookie()] = None):
+ if not admin_auth:
+ response.status_code = fastapi.status.HTTP_401_UNAUTHORIZED
+ return """{"reply": "Unauthorised."}"""
+
+ if authenticate_admin_check(admin_auth):
+ return machine_status
+ else:
+ response.status_code = fastapi.status.HTTP_403_FORBIDDEN
+ return """{"reply": "Forbidden."}"""