Spaces:
Sleeping

apeHero / app.py
AByGCreation's picture
Add profile and about pages with corresponding routes and functionality
30dfa83
Raw History Blame Contribute Delete
17.9 kB
import os, sqlite3, csv, io, secrets, hmac, hashlib
from datetime import datetime
from functools import wraps
from pathlib import Path
from flask import Flask, render_template, request, jsonify, session, redirect, url_for, Response, abort
ROOT=Path(__file__).resolve().parent
DB_PATH=Path(os.environ.get('DATABASE_PATH', str(ROOT/'data'/'apero.sqlite3')))
DB_PATH.parent.mkdir(parents=True,exist_ok=True)
app=Flask(__name__,template_folder='templates',static_folder='static')
app.secret_key=os.environ.get('SECRET_KEY') or secrets.token_hex(32)
app.config.update(SESSION_COOKIE_HTTPONLY=True,SESSION_COOKIE_SAMESITE='Lax',SESSION_COOKIE_SECURE=os.environ.get('COOKIE_SECURE','1')=='1', MAX_CONTENT_LENGTH=1024*1024)
ADMIN_PASSWORD=os.environ.get('ADMIN_PASSWORD','')
if not ADMIN_PASSWORD: print('ATTENTION : ADMIN_PASSWORD non défini : interface admin inaccessible.',flush=True)
def db():
c=sqlite3.connect(DB_PATH,timeout=20)
c.row_factory=sqlite3.Row
c.execute('PRAGMA foreign_keys=ON')
c.execute('PRAGMA busy_timeout=20000')
return c
def init_db():
"""Create the schema and seed defaults only for an empty database."""
with db() as c:
existing_tables = c.execute(
"SELECT name FROM sqlite_master "
"WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
).fetchall()
database_has_data = False
for table in existing_tables:
table_name = table['name'].replace('"', '""')
query = f'SELECT 1 FROM "{table_name}" LIMIT 1'
if c.execute(query).fetchone() is not None:
database_has_data = True
break
c.executescript('''
CREATE TABLE IF NOT EXISTS guests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL CHECK(length(name)<=120),
service TEXT NOT NULL DEFAULT 'Autre',
status TEXT NOT NULL DEFAULT 'En attente',
extra INTEGER NOT NULL DEFAULT 0 CHECK(extra BETWEEN 0 AND 2),
contribution TEXT NOT NULL DEFAULT '',
notes TEXT NOT NULL DEFAULT '',
access_hash TEXT UNIQUE,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS dates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
day TEXT NOT NULL UNIQUE,
time TEXT NOT NULL DEFAULT '19:00',
active INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE IF NOT EXISTS votes (
guest_id INTEGER NOT NULL REFERENCES guests(id) ON DELETE CASCADE,
date_id INTEGER NOT NULL REFERENCES dates(id) ON DELETE CASCADE,
choice TEXT NOT NULL CHECK(choice IN ('Oui','Peut-être','Non')),
PRIMARY KEY(guest_id,date_id)
);
''')
if not any(x['name']=='party_size' for x in c.execute('PRAGMA table_info(guests)')):
c.execute('ALTER TABLE guests ADD COLUMN party_size INTEGER')
c.execute('UPDATE guests SET party_size=extra+1 WHERE party_size IS NULL')
if not any(x['name']=='dietary' for x in c.execute('PRAGMA table_info(guests)')):
c.execute("ALTER TABLE guests ADD COLUMN dietary TEXT NOT NULL DEFAULT ''")
c.execute('''CREATE TABLE IF NOT EXISTS shopping_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
label TEXT NOT NULL CHECK(length(label)<=160),
quantity TEXT NOT NULL DEFAULT '',
category TEXT NOT NULL DEFAULT 'Autre',
purchased INTEGER NOT NULL DEFAULT 0 CHECK(purchased IN (0,1)),
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)''')
if not database_has_data and c.execute(
'SELECT COUNT(*) FROM dates'
).fetchone()[0] == 0:
default_dates = (
'2026-11-28',
'2026-11-27',
'2026-12-04',
'2026-12-11',
'2026-12-12',
'2026-12-18',
'2026-12-19',
)
c.executemany(
'INSERT INTO dates(day,time) VALUES (?,?)',
[(day, '19:00') for day in default_dates],
)
init_db()
SERVICES=['ORGA','DT','EMRG','Autre']
STATUSES=['À inviter','En attente','Confirmé','Absent']
CHOICES=['Oui','Peut-être','Non']
def csrf_token():
if 'csrf' not in session: session['csrf']=secrets.token_urlsafe(24)
return session['csrf']
app.jinja_env.globals['csrf_token']=csrf_token
@app.before_request
def protect():
if request.method in ('POST','PUT','PATCH','DELETE'):
origin=request.headers.get('Origin')
if origin:
from urllib.parse import urlparse
if urlparse(origin).netloc != request.host: abort(403)
if not hmac.compare_digest(request.headers.get('X-CSRF-Token',''),csrf_token()): abort(403)
@app.after_request
def headers(r):
r.headers['X-Content-Type-Options']='nosniff'
r.headers['Referrer-Policy']='same-origin'
r.headers['X-Frame-Options']='SAMEORIGIN'
r.headers['Cache-Control']='no-store'
return r
@app.errorhandler(400)
@app.errorhandler(403)
@app.errorhandler(404)
def error(e):
if request.path.startswith('/api/'):
return jsonify(error=str(e.description) if hasattr(e,'description') else 'Erreur'),e.code
return f'Erreur {e.code}: {e.description}',e.code
def json_input():
data=request.get_json(silent=True)
if not isinstance(data,dict): abort(400,'JSON requis')
return data
def valid_text(v,limit,required=False):
if not isinstance(v,str): abort(400,'Texte invalide')
v=v.strip()
if len(v)>limit or (required and not v): abort(400,'Longueur invalide')
return v
def guest_fields(data,existing=None):
name=valid_text(data.get('name',existing['name'] if existing else ''),120,True)
service=valid_text(data.get('service',existing['service'] if existing else 'Autre'),60,True)
status=data.get('status',existing['status'] if existing else 'En attente')
if status not in STATUSES: abort(400,'Statut invalide')
try: party_size=int(data.get('party_size',data.get('extra',existing['party_size']-1 if existing else 0)+1))
except (ValueError,TypeError): abort(400,'Nombre de personnes invalide')
if not 1<=party_size<=20: abort(400,'Nombre de personnes entre 1 et 20')
extra=min(party_size-1,2)
contribution=valid_text(data.get('contribution',existing['contribution'] if existing else ''),250)
notes=valid_text(data.get('notes',existing['notes'] if existing else ''),500)
dietary=valid_text(data.get('dietary',existing['dietary'] if existing else ''),500)
return name,service,status,extra,contribution,notes,party_size,dietary
def admin_required(fn):
@wraps(fn)
def inner(*args,**kwargs):
if not session.get('admin'):
if request.path.startswith('/api/'): return jsonify(error='Connexion administrateur requise'),401
return redirect(url_for('login'))
return fn(*args,**kwargs)
return inner
@app.get('/healthz')
def healthz():
with db() as c: c.execute('SELECT 1').fetchone()
return jsonify(status='ok')
@app.get('/')
def home(): return render_template('index.html',page='public')
@app.get('/about')
@app.get('/about.html')
def about(): return render_template('about.html',page='about')
@app.get('/profil')
@app.get('/profil.html')
def profile(): return render_template('profil.html',page='profile')
@app.get('/admin/login')
def login(): return render_template('login.html',page='login')
@app.post('/api/login')
def do_login():
p=json_input().get('password','')
if not ADMIN_PASSWORD or not isinstance(p,str) or not hmac.compare_digest(p,ADMIN_PASSWORD): return jsonify(error='Mot de passe incorrect'),401
session.clear();session['admin']=True;csrf_token()
return jsonify(ok=True,csrf=session['csrf'])
@app.post('/api/logout')
def logout():session.clear();return jsonify(ok=True)
@app.get('/admin')
@admin_required
def admin(): return render_template('admin.html',page='admin')
@app.get('/api/dates')
def dates():
with db() as c: rows=c.execute('SELECT id,day,time FROM dates WHERE active=1 ORDER BY day,time').fetchall()
return jsonify(dates=[dict(x) for x in rows])
@app.get('/api/public-summary')
def summary():
with db() as c:
data=c.execute('''SELECT d.id,d.day,d.time,
SUM(CASE WHEN v.choice='Oui' THEN 1 ELSE 0 END) AS yes,
SUM(CASE WHEN v.choice='Peut-être' THEN 1 ELSE 0 END) AS maybe,
SUM(CASE WHEN v.choice='Non' THEN 1 ELSE 0 END) AS no
FROM dates d LEFT JOIN votes v ON v.date_id=d.id WHERE d.active=1 GROUP BY d.id ORDER BY d.day''').fetchall()
return jsonify(summary=[dict(x) for x in data])
@app.post('/api/vote')
def vote():
data=json_input(); token=data.get('token')
if token is not None and (not isinstance(token,str) or len(token)>160):abort(400,'Jeton invalide')
if not token: token=secrets.token_urlsafe(32)
token_hash=hashlib.sha256(token.encode()).hexdigest()
name=valid_text(data.get('name',''),120,True)
service=valid_text(data.get('service','Autre'),60,True)
try: participants=int(data.get('participants',1))
except (TypeError,ValueError):abort(400,'Nombre de personnes invalide')
if not 1<=participants<=20:abort(400,'Nombre de personnes entre 1 et 20')
contribution=valid_text(data.get('contribution',''),250)
dietary=valid_text(data.get('dietary',''),500)
votes=data.get('votes',{})
if not isinstance(votes,dict) or len(votes)>50:abort(400,'Votes invalides')
with db() as c:
active={str(x['id']) for x in c.execute('SELECT id FROM dates WHERE active=1')}
if not votes or any(str(k) not in active or v not in CHOICES for k,v in votes.items()):abort(400,'Choisissez vos disponibilités')
previous=c.execute('SELECT id FROM guests WHERE access_hash=?',(token_hash,)).fetchone()
if previous:
gid=previous['id'];c.execute('UPDATE guests SET name=?, service=?, extra=?, party_size=?, contribution=?, dietary=? WHERE id=?',(name,service,min(participants-1,2),participants,contribution,dietary,gid))
else:
gid=c.execute('INSERT INTO guests(name,service,status,extra,party_size,contribution,dietary,access_hash) VALUES (?,?,?,?,?,?,?,?)',(name,service,'En attente',min(participants-1,2),participants,contribution,dietary,token_hash)).lastrowid
c.execute('DELETE FROM votes WHERE guest_id=?',(gid,))
c.executemany('INSERT INTO votes(guest_id,date_id,choice) VALUES(?,?,?)',[(gid,int(k),v) for k,v in votes.items()])
return jsonify(ok=True,token=token)
@app.get('/api/me')
def me():
token=request.args.get('token','')
if not token or len(token)>160:return jsonify(guest=None)
h=hashlib.sha256(token.encode()).hexdigest()
with db() as c:
guest=c.execute('SELECT id,name,service,extra,party_size,contribution,dietary FROM guests WHERE access_hash=?',(h,)).fetchone()
if not guest:return jsonify(guest=None)
votes=c.execute('SELECT date_id,choice FROM votes WHERE guest_id=?',(guest['id'],)).fetchall()
return jsonify(guest=dict(guest),votes={str(x['date_id']):x['choice'] for x in votes})
@app.put('/api/me')
def update_me():
data=json_input()
token=valid_text(data.get('token',''),160,True)
token_hash=hashlib.sha256(token.encode()).hexdigest()
with db() as c:
guest=c.execute('SELECT * FROM guests WHERE access_hash=?',(token_hash,)).fetchone()
if guest is None: abort(404,'Réponse introuvable. Retrouve ton inscription depuis le sondage.')
name=valid_text(data.get('name',guest['name']),120,True)
try: participants=int(data.get('participants',guest['party_size']))
except (TypeError,ValueError): abort(400,'Nombre de personnes invalide')
if not 1<=participants<=20: abort(400,'Nombre de personnes entre 1 et 20')
contribution=valid_text(data.get('contribution',guest['contribution']),250)
dietary=valid_text(data.get('dietary',guest['dietary']),500)
c.execute('UPDATE guests SET name=?,extra=?,party_size=?,contribution=?,dietary=? WHERE id=?',
(name,min(participants-1,2),participants,contribution,dietary,guest['id']))
return jsonify(ok=True)
@app.get('/api/admin/state')
@admin_required
def state():
with db() as c:
guests=[dict(x) for x in c.execute('SELECT id,name,service,status,extra,party_size,contribution,dietary,notes,created_at FROM guests ORDER BY id DESC')]
days=[dict(x) for x in c.execute('SELECT id,day,time,active FROM dates ORDER BY day,time')]
votes=[dict(x) for x in c.execute('SELECT guest_id,date_id,choice FROM votes')]
return jsonify(guests=guests,dates=days,votes=votes)
@app.post('/api/admin/guests')
@admin_required
def create_guest():
vals=guest_fields(json_input())
with db() as c:gid=c.execute('INSERT INTO guests(name,service,status,extra,contribution,notes,party_size,dietary) VALUES(?,?,?,?,?,?,?,?)',vals).lastrowid
return jsonify(ok=True,id=gid),201
@app.put('/api/admin/guests/<int:gid>')
@admin_required
def edit_guest(gid):
with db() as c:
old=c.execute('SELECT * FROM guests WHERE id=?',(gid,)).fetchone()
if old is None:abort(404)
vals=guest_fields(json_input(),old)
c.execute('UPDATE guests SET name=?,service=?,status=?,extra=?,contribution=?,notes=?,party_size=?,dietary=? WHERE id=?',(*vals,gid))
return jsonify(ok=True)
@app.delete('/api/admin/guests/<int:gid>')
@admin_required
def delete_guest(gid):
with db() as c:c.execute('DELETE FROM guests WHERE id=?',(gid,))
return jsonify(ok=True)
@app.post('/api/admin/dates')
@admin_required
def create_date():
d=json_input(); day=d.get('day','');time=d.get('time','19:00')
try:datetime.strptime(day,'%Y-%m-%d');datetime.strptime(time,'%H:%M')
except (ValueError,TypeError):abort(400,'Date ou heure invalide')
with db() as c:
try:c.execute('INSERT INTO dates(day,time) VALUES(?,?)',(day,time))
except sqlite3.IntegrityError:abort(400,'Date déjà ajoutée')
return jsonify(ok=True),201
@app.delete('/api/admin/dates/<int:did>')
@admin_required
def delete_date(did):
with db() as c:c.execute('DELETE FROM dates WHERE id=?',(did,))
return jsonify(ok=True)
@app.get('/api/admin/export.csv')
@admin_required
def export():
out=io.StringIO();w=csv.writer(out,delimiter=';')
with db() as c:
days=c.execute('SELECT id,day FROM dates ORDER BY day').fetchall()
w.writerow(['Nom','Service','Statut','Nombre total de personnes','Accompagnants','Contribution','Allergies et intolérances','Notes']+[x['day'] for x in days])
for g in c.execute('SELECT * FROM guests ORDER BY name'):
votes={v['date_id']:v['choice'] for v in c.execute('SELECT date_id,choice FROM votes WHERE guest_id=?',(g['id'],))}
w.writerow([g['name'],g['service'],g['status'],g['party_size'],g['party_size']-1,g['contribution'],g['dietary'],g['notes']]+[votes.get(d['id'],'') for d in days])
return Response('\ufeff'+out.getvalue(),mimetype='text/csv; charset=utf-8',headers={'Content-Disposition':'attachment; filename="apero-invites.csv"'})
# Shopping list: only authenticated administrators may view or modify purchases.
def shopping_fields(data, existing=None):
label=valid_text(data.get('label',existing['label'] if existing else ''),160,True)
quantity=valid_text(data.get('quantity',existing['quantity'] if existing else ''),80)
category=valid_text(data.get('category',existing['category'] if existing else 'Autre'),60,True)
if category not in ('Apéritif salé','Dessert','Boissons','Frais','Épicerie','Matériel','Autre'):
abort(400,'Catégorie invalide')
purchased=data.get('purchased',bool(existing['purchased']) if existing else False)
if not isinstance(purchased,bool): abort(400,'Statut achat invalide')
return label,quantity,category,int(purchased)
@app.get('/api/admin/shopping')
@admin_required
def shopping_list():
with db() as c:
items=[dict(x) for x in c.execute('SELECT id,label,quantity,category,purchased FROM shopping_items ORDER BY purchased,category,label,id')]
return jsonify(items=items)
@app.post('/api/admin/shopping')
@admin_required
def shopping_add():
vals=shopping_fields(json_input())
with db() as c:
item_id=c.execute('INSERT INTO shopping_items(label,quantity,category,purchased) VALUES (?,?,?,?)',vals).lastrowid
return jsonify(ok=True,id=item_id),201
@app.put('/api/admin/shopping/<int:item_id>')
@admin_required
def shopping_update(item_id):
with db() as c:
item=c.execute('SELECT * FROM shopping_items WHERE id=?',(item_id,)).fetchone()
if item is None: abort(404)
vals=shopping_fields(json_input(),item)
c.execute('UPDATE shopping_items SET label=?,quantity=?,category=?,purchased=? WHERE id=?',(*vals,item_id))
return jsonify(ok=True)
@app.delete('/api/admin/shopping/<int:item_id>')
@admin_required
def shopping_delete(item_id):
with db() as c:
c.execute('DELETE FROM shopping_items WHERE id=?',(item_id,))
return jsonify(ok=True)
@app.get('/api/admin/shopping.csv')
@admin_required
def shopping_csv():
out=io.StringIO();writer=csv.writer(out,delimiter=';')
writer.writerow(['Article','Quantité','Catégorie','État'])
with db() as c:
for x in c.execute('SELECT label,quantity,category,purchased FROM shopping_items ORDER BY category,label'):
writer.writerow([x['label'],x['quantity'],x['category'],'Acheté' if x['purchased'] else 'À acheter'])
return Response('\ufeff'+out.getvalue(),mimetype='text/csv; charset=utf-8',headers={'Content-Disposition':'attachment; filename="apero-courses.csv"'})
@app.get('/health')
def health():return jsonify(status='ok')
if __name__=='__main__':app.run(host='0.0.0.0',port=int(os.environ.get('PORT',7860)))