Files
PC-Seq-Exam-WebApp/src/app.py
2025-12-15 23:07:46 +10:00

142 lines
4.5 KiB
Python

import sqlite3
from fastapi import FastAPI
from fastapi import Request, Form
from fastapi.responses import HTMLResponse, RedirectResponse
DB_PATH = "./data/database.db"
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, login TEXT NOT NULL UNIQUE, password TEXT NOT NULL)")
app = FastAPI(
docs_url=None, # Disable Swagger UI
redoc_url=None, # Disable ReDoc
openapi_url=None # Disable OpenAPI JSON schema
)
STYLES = """
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
}
</style>
"""
@app.get("/register", response_class=HTMLResponse)
async def register_form():
return f"""
<html>
<head><title>Регистрация</title>{STYLES}</head>
<body>
<h2>Регистрация</h2>
<form action="/register" method="post">
<input name="login" placeholder="Login" required><br>
<input name="password" type="password" placeholder="Password" required><br>
<button type="submit">Register</button>
</form>
<p>Уже есть аккаунт? <a href="/login">Войти</a></p>
</body>
</html>
"""
@app.post("/register")
async def register(login: str = Form(...), password: str = Form(...)):
try:
cursor.execute("INSERT INTO users (login, password) VALUES (?, ?)", (login, password))
conn.commit()
response = RedirectResponse(url="/welcome", status_code=302)
response.set_cookie("login", login)
response.set_cookie("password", password)
return response
except sqlite3.IntegrityError:
return HTMLResponse(f"""
<html>
<head><title>Ошибка регистрации</title>{STYLES}</head>
<body>
<h3>Login уже существует</h3>
<a href='/register'>Попробовать снова</a>
</body>
</html>
""", status_code=400)
@app.get("/login", response_class=HTMLResponse)
async def login_form():
return f"""
<html>
<head><title>Вход</title>{STYLES}</head>
<body>
<h2>Вход</h2>
<form action="/login" method="post">
<input name="login" placeholder="Login" required><br>
<input name="password" type="password" placeholder="Password" required><br>
<button type="submit">Login</button>
</form>
<p>Нет аккаунта? <a href="/register">Зарегистрироваться</a></p>
</body>
</html>
"""
@app.post("/login")
async def login(login: str = Form(...), password: str = Form(...)):
cursor.execute("SELECT * FROM users WHERE login=? AND password=?", (login, password))
user = cursor.fetchone()
if user:
response = RedirectResponse(url="/welcome", status_code=302)
response.set_cookie("login", login)
response.set_cookie("password", password)
return response
else:
return HTMLResponse(f"""
<html>
<head><title>Ошибка входа</title>{STYLES}</head>
<body>
<h3>Неверные учетные данные</h3>
<a href='/login'>Попробовать снова</a>
</body>
</html>
""", status_code=401)
@app.get("/welcome", response_class=HTMLResponse)
async def welcome(request: Request):
login = request.cookies.get("login")
password = request.cookies.get("password")
if not login or not password:
return RedirectResponse(url="/login")
cursor.execute("SELECT * FROM users WHERE login=? AND password=?", (login, password))
user = cursor.fetchone()
if user:
return f"""
<html>
<head><title>Добро пожаловать</title>{STYLES}</head>
<body>
<h1>Привет, {login}</h1>
<form action="/logout" method="post" onsubmit="return logoutAlert();">
<button type="submit">Выйти</button>
</form>
<script>
function logoutAlert() {{
alert('Вы вышли из аккаунта');
return true;
}}
</script>
</body>
</html>
"""
else:
return RedirectResponse(url="/login")
@app.post("/logout")
async def logout():
response = RedirectResponse(url="/login", status_code=302)
response.delete_cookie("login")
response.delete_cookie("password")
return response
@app.get("/", include_in_schema=False)
async def root():
return RedirectResponse(url="/login")