1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
|
import json
from hashlib import scrypt
from os import urandom
from hmac import compare_digest
import sqlite3
from colorsys import rgb_to_hsv
from flask import (
Flask,
render_template,
request,
redirect,
url_for,
session,
g,
flash,
)
from werkzeug.exceptions import HTTPException, NotImplemented, BadRequest
import requests
from captcha import Captcha
from presets import GUEST_CAPTCHA, GUIDE_CAPTCHAS
SCRYPT_PARAMS = {"n": 16384, "r": 8, "p": 1}
HEX_CHARS = set("0123456789ABCDEF")
def get_db():
if "db" not in g:
g.db = sqlite3.connect("akasha.db", detect_types=sqlite3.PARSE_DECLTYPES)
g.db.row_factory = sqlite3.Row
return g.db
def teardown(e=None):
if (db := g.pop("db", None)) is not None:
db.close()
def has_captcha(captcha_id):
return captcha_id in session.get("captcha", [])
def add_captcha(captcha_id):
if "captcha" not in session:
session["captcha"] = []
if captcha_id not in session["captcha"]:
session["captcha"].append(captcha_id)
session.modified = True
def make_app():
global LIGHT_URL
app = Flask(__name__)
with sqlite3.connect("akasha.db", detect_types=sqlite3.PARSE_DECLTYPES) as temp_db:
cur = temp_db.cursor()
cur.execute("SELECT value FROM config WHERE key='fsk'")
app.config["SECRET_KEY"] = cur.fetchone()[0]
cur.execute("SELECT value FROM config WHERE key='light'")
LIGHT_URL = f"http://192.168.1.10/api/{cur.fetchone()[0]}"
app.teardown_appcontext(teardown)
return app
app = make_app()
@app.context_processor
def context_processor():
return dict(has_captcha=has_captcha)
@app.before_request
def before_request():
if not request.endpoint or request.endpoint == "static":
return
db = get_db()
cur = db.cursor()
cur.execute("SELECT public FROM permit WHERE endpoint=?", (request.endpoint,))
public = cur.fetchone()
if public is None:
raise NotImplemented
match public[0]:
case 2:
return
case 1:
if "username" in session:
return
flash("You must be logged in to access this content.")
return redirect(url_for("guest_login"))
case 0:
if "username" in session:
cur = db.cursor()
cur.execute(
"SELECT 1 FROM permit_override WHERE username=? AND endpoint=?",
(session["username"], request.endpoint),
)
if cur.fetchone():
return
flash("This content requires additional permissions to view.")
else:
flash("You must be logged in to access this content.")
return redirect(url_for("login"))
case _:
raise NotImplemented
@app.errorhandler(HTTPException)
def handle_bad_request(error):
if error.code == 501:
if "username" in session:
flash("This content requires additional permissions to view.")
else:
flash("You must be logged in to access this content.")
return redirect(url_for("login"))
return render_template("error.html", error=error), error.code
@app.route("/")
def index():
db = get_db()
cur = db.cursor()
cur.execute("SELECT * FROM news ORDER BY id DESC LIMIT 1")
results = cur.fetchone()
return render_template("index.html", news=results)
@app.route("/captcha")
def captcha():
size = request.args.get("size", "")
label = request.args.get("label", "")
lock = request.args.get("lock", "")
answer = request.args.get("answer", "")
captcha = Captcha.safe_validate(size, label, lock, answer)
if captcha:
add_captcha(captcha.id)
return {"valid": True}, 200
return {"valid": False}, 400
@app.route("/login", methods=["GET", "POST"])
def login():
db = get_db()
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
if not username or not password:
flash("Error: Empty username or password.")
return redirect(url_for("login"))
if request.form.get("register") == "1":
cur = db.cursor()
cur.execute("SELECT 1 FROM users WHERE username=?", (username,))
if cur.fetchone():
flash("Error: User already exists.")
return redirect(url_for("login"))
salt = urandom(32)
hash = scrypt(password.encode("utf-8"), salt=salt, **SCRYPT_PARAMS)
cur.execute(
"INSERT INTO users (username, hash, salt) VALUES (?, ?, ?)",
(username, hash, salt),
)
flash("Success: User registered.")
db.commit()
else:
cur = db.cursor()
cur.execute("SELECT hash, salt FROM users WHERE username=?", (username,))
results = cur.fetchone()
if not results:
flash("Error: Invalid username or password.")
return redirect(url_for("login"))
expected_hash, salt = results
actual_hash = scrypt(password.encode("utf-8"), salt=salt, **SCRYPT_PARAMS)
if not compare_digest(expected_hash, actual_hash):
flash("Error: Invalid username or password.")
return redirect(url_for("login"))
session["username"] = username
flash(f"Success: Logged in as {username}.")
return redirect(url_for("index"))
return render_template("login.html")
@app.route("/guest")
def guest_login():
if has_captcha(GUEST_CAPTCHA.id) and "username" not in session:
session["username"] = "guest"
flash(f"Success: Logged in as guest.")
return redirect(url_for("index"))
return render_template("guest.html", captcha=GUEST_CAPTCHA)
@app.route("/eguide")
def eguide():
return render_template("eguide.html", captchas=GUIDE_CAPTCHAS)
@app.route("/logout")
def logout():
if "username" in session:
del session["username"]
if "captcha" in session:
del session["captcha"]
flash("Success: You have been logged out.")
return redirect(url_for("index"))
@app.route("/hyde")
def hydematch():
db = get_db()
cur = db.cursor()
cur.execute("SELECT * FROM matches ORDER BY id DESC")
results = cur.fetchall()
return render_template("hyde.html", matches=results)
@app.route("/news")
def news():
db = get_db()
cur = db.cursor()
cur.execute("SELECT * FROM news ORDER BY id DESC")
results = cur.fetchall()
return render_template("news.html", news=results)
@app.route("/mgmt", methods=["GET", "POST"])
def management():
if request.method == "POST":
try:
lid_key = request.form.get("lid", "custom")
if lid_key == "custom":
lid = int(request.form.get("custom", "5"))
else:
lid = int(lid_key)
except ValueError:
raise BadRequest
set_key = request.form.get("set")
match set_key:
case "off":
tool_disable_light(lid)
case "on":
tool_enable_light(lid)
case "color":
tool_color_light(lid, request.form.get("color", "#FF00AA"))
case _:
raise BadRequest
return render_template("mgmt.html")
def tool_disable_light(light: int):
requests.put(
f"{LIGHT_URL}/lights/{light}/state",
json={"on": False},
timeout=5,
)
def tool_enable_light(light: int):
requests.put(
f"{LIGHT_URL}/lights/{light}/state",
json={"on": True, "ct": 366},
timeout=5,
)
def tool_color_light(light: int, color: str):
if color[0] == "#":
color = color[1:]
color = color.upper()
if len(color) != 6 or not all(c in HEX_CHARS for c in color):
color = "FF00AA"
rgb = [int(color[i : i + 2], 16) / 255 for i in range(0, 6, 2)]
hsv = rgb_to_hsv(*rgb)
requests.put(
f"{LIGHT_URL}/lights/{light}/state",
json={
"on": True,
"hue": int(hsv[0] * 65535),
"sat": int(hsv[1] * 254),
"bri": int(hsv[2] * 254),
},
timeout=5,
)
@app.route("/permits")
def permits():
raise NotImplemented
@app.route("/radio")
def radio():
raise NotImplemented
@app.route("/absidy")
def absidy():
raise NotImplemented
|