105 lines
2.4 KiB
Python
105 lines
2.4 KiB
Python
from flask import Flask, render_template, request, redirect, session, jsonify
|
|
import sqlite3
|
|
|
|
app = Flask(__name__)
|
|
app.secret_key = "supersecretkey"
|
|
|
|
DB = "database.db"
|
|
|
|
# ---------------- DATABASE ----------------
|
|
def get_db():
|
|
conn = sqlite3.connect(DB)
|
|
conn.row_factory = sqlite3.Row
|
|
return conn
|
|
|
|
def init_db():
|
|
conn = get_db()
|
|
conn.execute('''
|
|
CREATE TABLE IF NOT EXISTS toner (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
name TEXT NOT NULL,
|
|
quantity INTEGER NOT NULL
|
|
)
|
|
''')
|
|
conn.execute('''
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
username TEXT,
|
|
password TEXT
|
|
)
|
|
''')
|
|
conn.commit()
|
|
|
|
# ---------------- ROUTES ----------------
|
|
|
|
@app.route("/")
|
|
def index():
|
|
return render_template("index.html")
|
|
|
|
@app.route("/api/toner")
|
|
def get_toner():
|
|
conn = get_db()
|
|
toner = conn.execute("SELECT * FROM toner").fetchall()
|
|
return jsonify([dict(row) for row in toner])
|
|
|
|
@app.route("/login", methods=["GET", "POST"])
|
|
def login():
|
|
if request.method == "POST":
|
|
user = request.form["username"]
|
|
pw = request.form["password"]
|
|
|
|
conn = get_db()
|
|
result = conn.execute(
|
|
"SELECT * FROM users WHERE username=? AND password=?",
|
|
(user, pw)
|
|
).fetchone()
|
|
|
|
if result:
|
|
session["user"] = user
|
|
return redirect("/admin")
|
|
|
|
return render_template("login.html")
|
|
|
|
@app.route("/admin")
|
|
def admin():
|
|
if "user" not in session:
|
|
return redirect("/login")
|
|
return render_template("admin.html")
|
|
|
|
@app.route("/api/add", methods=["POST"])
|
|
def add_item():
|
|
if "user" not in session:
|
|
return "Unauthorized", 401
|
|
|
|
data = request.json
|
|
conn = get_db()
|
|
conn.execute(
|
|
"INSERT INTO toner (name, quantity) VALUES (?, ?)",
|
|
(data["name"], data["quantity"])
|
|
)
|
|
conn.commit()
|
|
return "OK"
|
|
|
|
@app.route("/api/update", methods=["POST"])
|
|
def update_item():
|
|
if "user" not in session:
|
|
return "Unauthorized", 401
|
|
|
|
data = request.json
|
|
conn = get_db()
|
|
conn.execute(
|
|
"UPDATE toner SET quantity=? WHERE id=?",
|
|
(data["quantity"], data["id"])
|
|
)
|
|
conn.commit()
|
|
return "OK"
|
|
|
|
@app.route("/logout")
|
|
def logout():
|
|
session.clear()
|
|
return redirect("/")
|
|
|
|
# ---------------- RUN ----------------
|
|
if __name__ == "__main__":
|
|
init_db()
|
|
app.run(debug=True) |