Upload 23 files
Browse filesFiles changed (11)
- app.py+330-108
- instance/ghostboard.db
- models.py+27-10
- requirements.txt+1
- templates/base.html+103
- templates/board.html+5-5
- templates/index.html+34
- templates/thread.html+2-2
- templates/user_profile.htmlAdded+91
- test_features.pyAdded+51
- tests.pyAdded+64
12345673 unmodified lines11121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041 unmodified line1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641656 unmodified lines1721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622631 unmodified line2652662672682692702712722732742752761 unmodified line2782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143151 unmodified line317318319320321322323324325326327from flask import Flask, render_template, request, redirect, url_for, abort, flash, session, send_from_directoryfrom werkzeug.utils import secure_filenamefrom werkzeug.security import check_password_hash, generate_password_hashfrom models import db, Board, Post, BannedIP, PostFilefrom forms import PostFormfrom datetime import datetimeimport os3 unmodified linesfrom functools import wrapsapp = Flask(__name__)app.config['SECRET_KEY'] = 'dev-secret-key' # Change in productionos.makedirs(app.instance_path, exist_ok=True)app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.instance_path, 'ghostboard.db')app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = Falseapp.config['UPLOAD_FOLDER'] = os.path.join(app.root_path, 'static/uploads')os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)app.config['MAX_CONTENT_LENGTH'] = 20 * 1024 * 1024 # 20 MB limitapp.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'mp4', 'webm'}app.config['ADMIN_PASSWORD_HASH'] = generate_password_hash('admin') # Default password: admindb.init_app(app)def init_db():db.create_all()# Seed default boardsboards = [{'slug': 'g', 'name': 'Général', 'description': 'Discussion générale'},{'slug': 'tech', 'name': 'Technologie', 'description': 'Ordinateurs, programmation, gadgets'},{'slug': 'art', 'name': 'Création', 'description': 'Art, design, musique'},{'slug': 'news', 'name': 'Actualités', 'description': 'Événements actuels'}]for b_data in boards:if not Board.query.filter_by(slug=b_data['slug']).first():board = Board(slug=b_data['slug'], name=b_data['name'], description=b_data['description'])db.session.add(board)db.session.commit()# Auto-initialize database if it doesn't existwith app.app_context():if not os.path.exists(os.path.join(app.instance_path, 'ghostboard.db')):init_db()def allowed_file(filename):return '.' in filename and \filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']def save_file(file):if file and allowed_file(file.filename):original_filename = secure_filename(file.filename)extension = original_filename.rsplit('.', 1)[1].lower()new_filename = f"{uuid.uuid4().hex}.{extension}"file.save(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))return new_filename, original_filenamereturn None, Nonedef delete_post_files(post):for file in post.files:path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)if os.path.exists(path):os.remove(path)db.session.delete(file)def delete_thread_content(thread):# Delete all repliesreplies = Post.query.filter_by(thread_id=thread.id).all()for reply in replies:delete_post_files(reply)db.session.delete(reply)delete_post_files(thread)db.session.delete(thread)def prune_board(board_id):# Limit to 100 threadsthreads_query = Post.query.filter_by(board_id=board_id, thread_id=None).order_by(Post.updated_at.desc())if threads_query.count() > 100:threads_to_delete = threads_query.offset(100).all()for thread in threads_to_delete:delete_thread_content(thread)db.session.commit()def admin_required(f):@wraps(f)def decorated_function(*args, **kwargs):if not session.get('is_admin'):return redirect(url_for('admin_login', next=request.url))return f(*args, **kwargs)return decorated_functiondef check_ban():ip = request.remote_addrban = BannedIP.query.filter_by(ip_address=ip).first()if ban:abort(403, description=f"Vous êtes banni. Raison : {ban.reason}")@app.cli.command("init-db")def init_db_command():"""Create database tables and seed initial data."""1 unmodified lineinit_db()print("Base de données initialisée.")@app.context_processordef inject_boards():return dict(global_boards=Board.query.all())@app.template_filter('format_post')def format_post(content):if not content:return ""# Escape HTML first (safety)content = str(Markup.escape(content))# Link to quotes >>12345def replace_quote(match):post_id = match.group(1)return f'<a href="#post-{post_id}" class="text-blue-400 hover:underline" onclick="highlightPost({post_id})">>>{post_id}</a>'content = re.sub(r'>>(\d+)', replace_quote, content)# Greentext (lines starting with >)content = re.sub(r'^(>.*)$', r'<span class="text-green-400">\1</span>', content, flags=re.MULTILINE)# Convert newlines to <br>content = content.replace('\n', '<br>')return Markup(content)@app.route('/manifest.json')def manifest():return send_from_directory('static', 'manifest.json')@app.route('/sw.js')def service_worker():return send_from_directory('static', 'sw.js')@app.route('/')def index():boards = Board.query.all()return render_template('index.html', boards=boards)@app.route('/<slug>/', methods=['GET', 'POST'])def board(slug):board = Board.query.filter_by(slug=slug).first_or_404()form = PostForm()if form.validate_on_submit():check_ban()# Create new threadpost = Post(board_id=board.id,content=form.content.data,nickname=form.nickname.data or 'Anonyme',ip_address=request.remote_addr)db.session.add(post)db.session.commit()6 unmodified linespost_file = PostFile(post_id=post.id,filename=filename,original_filename=original_filename)db.session.add(post_file)db.session.commit()# Prune boardprune_board(board.id)return redirect(url_for('board', slug=slug))# Get threads (posts with no thread_id), sorted by updated_at (bumping)threads = Post.query.filter_by(board_id=board.id, thread_id=None)\.order_by(Post.updated_at.desc()).limit(50).all()return render_template('board.html', board=board, threads=threads, form=form)@app.route('/thread/<int:thread_id>/', methods=['GET', 'POST'])def thread(thread_id):thread_post = Post.query.get_or_404(thread_id)if thread_post.thread_id is not None:# If it's a reply, redirect to the main threadreturn redirect(url_for('thread', thread_id=thread_post.thread_id))form = PostForm()if form.validate_on_submit():check_ban()# Create replyreply = Post(board_id=thread_post.board_id,thread_id=thread_post.id,content=form.content.data,nickname=form.nickname.data or 'Anonyme',ip_address=request.remote_addr)db.session.add(reply)# Handle multiple filesif form.files.data:for f in form.files.data:2 unmodified linespost_file = PostFile(post_id=reply.id,filename=filename,original_filename=original_filename)db.session.add(post_file)# Bump the threadthread_post.updated_at = datetime.utcnow()db.session.commit()return redirect(url_for('thread', thread_id=thread_post.id))replies = Post.query.filter_by(thread_id=thread_post.id).order_by(Post.created_at.asc()).all()return render_template('thread.html', thread=thread_post, replies=replies, board=thread_post.board, form=form)# Admin Routes@app.route('/admin/login', methods=['GET', 'POST'])def admin_login():if request.method == 'POST':password = request.form.get('password')if check_password_hash(app.config['ADMIN_PASSWORD_HASH'], password):session['is_admin'] = Truereturn redirect(url_for('admin_dashboard'))else:flash('Mot de passe invalide')return render_template('admin_login.html')@app.route('/admin/logout')def admin_logout():session.pop('is_admin', None)return redirect(url_for('index'))@app.route('/admin')@admin_requireddef admin_dashboard():# Show recent posts (both threads and replies) for moderationrecent_posts = Post.query.order_by(Post.created_at.desc()).limit(100).all()return render_template('admin.html', posts=recent_posts)@app.route('/admin/delete/<int:post_id>', methods=['POST'])@admin_requireddef delete_post(post_id):post = Post.query.get_or_404(post_id)if post.thread_id is None:# It's a thread starter, delete whole threaddelete_thread_content(post)1 unmodified line# It's a replydelete_post_file(post)db.session.delete(post)db.session.commit()flash('Post supprimé')return redirect(request.referrer or url_for('admin_dashboard'))@app.route('/admin/ban/<int:post_id>', methods=['POST'])@admin_requireddef ban_ip(post_id):post = Post.query.get_or_404(post_id)1 unmodified lineban = BannedIP(ip_address=post.ip_address, reason="Banni par l'administrateur")db.session.add(ban)db.session.commit()flash(f'IP {post.ip_address} bannie')else:flash(f'L\'IP {post.ip_address} est déjà bannie')return redirect(request.referrer or url_for('admin_dashboard'))@app.route('/admin/boards')@admin_requireddef admin_boards():boards = Board.query.all()return render_template('admin_boards.html', boards=boards)@app.route('/admin/boards/add', methods=['POST'])@admin_requireddef admin_add_board():slug = request.form.get('slug')name = request.form.get('name')description = request.form.get('description')if slug and name:if not Board.query.filter_by(slug=slug).first():board = Board(slug=slug, name=name, description=description)db.session.add(board)db.session.commit()flash('Planche ajoutée')else:flash('Ce slug existe déjà')else:flash('Données manquantes')return redirect(url_for('admin_boards'))@app.route('/admin/boards/delete/<int:board_id>', methods=['POST'])@admin_requireddef admin_delete_board(board_id):board = Board.query.get_or_404(board_id)1 unmodified lineposts = Post.query.filter_by(board_id=board.id, thread_id=None).all()for post in posts:delete_thread_content(post)db.session.delete(board)db.session.commit()flash('Planche supprimée')return redirect(url_for('admin_boards'))if __name__ == '__main__':app.run(debug=True)12345678910111213141516173 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411 unmodified line1431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123136 unmodified lines3203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044052 unmodified lines4084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794801 unmodified line4824834844854864874884894904914924934941 unmodified line4964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355361 unmodified line538539540541542543544545546547548549from flask import (Flask,render_template,request,redirect,url_for,abort,flash,session,send_from_directory,)from werkzeug.utils import secure_filenamefrom werkzeug.security import check_password_hash, generate_password_hashfrom models import db, Board, Post, BannedIP, PostFile, Userfrom forms import PostFormfrom datetime import datetimeimport os3 unmodified linesfrom functools import wrapsapp = Flask(__name__)app.config["SECRET_KEY"] = "dev-secret-key" # Change in productionos.makedirs(app.instance_path, exist_ok=True)app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(app.instance_path, "ghostboard.db")app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = Falseapp.config["UPLOAD_FOLDER"] = os.path.join(app.root_path, "static/uploads")os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)app.config["MAX_CONTENT_LENGTH"] = 20 * 1024 * 1024 # 20 MB limitapp.config["ALLOWED_EXTENSIONS"] = {"png", "jpg", "jpeg", "gif", "webp", "mp4", "webm"}app.config["ADMIN_PASSWORD_HASH"] = generate_password_hash("admin") # Default password: admindb.init_app(app)def init_db():db.create_all()# Seed default boardsboards = [{"slug": "g", "name": "Général", "description": "Discussion générale"},{"slug": "tech","name": "Technologie","description": "Ordinateurs, programmation, gadgets",},{"slug": "art", "name": "Création", "description": "Art, design, musique"},{"slug": "news", "name": "Actualités", "description": "Événements actuels"},]for b_data in boards:if not Board.query.filter_by(slug=b_data["slug"]).first():board = Board(slug=b_data["slug"],name=b_data["name"],description=b_data["description"],)db.session.add(board)db.session.commit()# Auto-initialize database if it doesn't existwith app.app_context():if not os.path.exists(os.path.join(app.instance_path, "ghostboard.db")):init_db()def allowed_file(filename):return ("." in filenameand filename.rsplit(".", 1)[1].lower() in app.config["ALLOWED_EXTENSIONS"])def save_file(file):if file and allowed_file(file.filename):original_filename = secure_filename(file.filename)extension = original_filename.rsplit(".", 1)[1].lower()new_filename = f"{uuid.uuid4().hex}.{extension}"file.save(os.path.join(app.config["UPLOAD_FOLDER"], new_filename))return new_filename, original_filenamereturn None, Nonedef delete_post_files(post):for file in post.files:path = os.path.join(app.config["UPLOAD_FOLDER"], file.filename)if os.path.exists(path):os.remove(path)db.session.delete(file)def delete_thread_content(thread):# Delete all repliesreplies = Post.query.filter_by(thread_id=thread.id).all()for reply in replies:delete_post_files(reply)db.session.delete(reply)delete_post_files(thread)db.session.delete(thread)def prune_board(board_id):# Limit to 100 threadsthreads_query = Post.query.filter_by(board_id=board_id, thread_id=None).order_by(Post.updated_at.desc())if threads_query.count() > 100:threads_to_delete = threads_query.offset(100).all()for thread in threads_to_delete:delete_thread_content(thread)db.session.commit()def admin_required(f):@wraps(f)def decorated_function(*args, **kwargs):if not session.get("is_admin"):return redirect(url_for("admin_login", next=request.url))return f(*args, **kwargs)return decorated_functiondef check_ban():ip = request.remote_addrban = BannedIP.query.filter_by(ip_address=ip).first()if ban:abort(403, description=f"Vous êtes banni. Raison : {ban.reason}")@app.cli.command("init-db")def init_db_command():"""Create database tables and seed initial data."""1 unmodified lineinit_db()print("Base de données initialisée.")@app.context_processordef inject_boards():return dict(global_boards=Board.query.all())@app.template_filter("format_post")def format_post(content, post_context=None):"""Format post content with quotes and greentext.post_context: dict mapping post_id -> nickname for resolving >>12345 references"""if not content:return ""# Escape HTML first (safety)content = str(Markup.escape(content))# Link to quotes >>12345def replace_quote(match):post_id = match.group(1)if post_context and post_id in post_context:nickname = post_context[post_id]return f'<a href="#post-{post_id}" class="text-blue-400 hover:underline" onclick="highlightPost({post_id})">@<span class="font-semibold">{nickname}</span></a>'else:# Fallback: try to get from database (slower)post = Post.query.get(int(post_id))if post and post.user:return f'<a href="#post-{post_id}" class="text-blue-400 hover:underline" onclick="highlightPost({post_id})">@<span class="font-semibold">{post.user.nickname}</span></a>'elif post:return f'<a href="#post-{post_id}" class="text-blue-400 hover:underline" onclick="highlightPost({post_id})">@<span class="font-semibold">{post.nickname}</span></a>'else:return f'<a href="#post-{post_id}" class="text-blue-400 hover:underline" onclick="highlightPost({post_id})">>>{post_id}</a>'content = re.sub(r">>(\d+)", replace_quote, content)# Greentext (lines starting with >)content = re.sub(r"^(>.*)$",r'<span class="text-green-400">\1</span>',content,flags=re.MULTILINE,)# Convert newlines to <br>content = content.replace("\n", "<br>")return Markup(content)# API Routes for user management@app.route("/api/set-nickname", methods=["POST"])def set_nickname():"""Set or update user nickname"""data = request.get_json()nickname = data.get("nickname", "").strip()if not nickname:return {"error": "Pseudo requis"}, 400if len(nickname) > 50:return {"error": "Pseudo trop long (max 50 caractères)"}, 400# Check if nickname already existsexisting_user = User.query.filter_by(nickname=nickname).first()if existing_user:# If it's the same user, allow itif session.get("user_id") == existing_user.id:return {"success": True, "user_id": existing_user.id, "nickname": nickname}else:return {"error": "Ce pseudo est déjà pris"}, 400# Get or create useruser_id = session.get("user_id")if user_id:user = User.query.get(user_id)if user:user.nickname = nicknameuser.last_seen_at = datetime.utcnow()else:# Session invalid, create new useruser = User(nickname=nickname)db.session.add(user)else:user = User(nickname=nickname)db.session.add(user)db.session.commit()session["user_id"] = user.idsession["nickname"] = user.nicknamereturn {"success": True, "user_id": user.id, "nickname": nickname}@app.route("/api/me")def get_current_user():"""Get current user info"""user_id = session.get("user_id")if user_id:user = User.query.get(user_id)if user:user.last_seen_at = datetime.utcnow()db.session.commit()return {"user_id": user.id, "nickname": user.nickname}return {"user_id": None, "nickname": None}@app.route("/user/<int:user_id>")def user_profile(user_id):"""Show user profile and posts"""user = User.query.get_or_404(user_id)posts = (Post.query.filter_by(user_id=user_id).order_by(Post.created_at.desc()).limit(50).all())return render_template("user_profile.html", user=user, posts=posts)@app.route("/manifest.json")def manifest():return send_from_directory("static", "manifest.json")@app.route("/sw.js")def service_worker():return send_from_directory("static", "sw.js")@app.route("/")def index():boards = Board.query.all()return render_template("index.html", boards=boards)@app.route("/<slug>/", methods=["GET", "POST"])def board(slug):board = Board.query.filter_by(slug=slug).first_or_404()form = PostForm()if form.validate_on_submit():check_ban()# Get user_id from session or use anonymoususer_id = session.get("user_id")nickname = "Anonyme"if user_id:user = User.query.get(user_id)if user:nickname = user.nicknameelse:user_id = None # Invalid user_idelse:# Anonymous postnickname = form.nickname.data or "Anonyme"# Create new threadpost = Post(board_id=board.id,user_id=user_id,content=form.content.data,nickname=nickname,ip_address=request.remote_addr,)db.session.add(post)db.session.commit()6 unmodified linespost_file = PostFile(post_id=post.id,filename=filename,original_filename=original_filename,)db.session.add(post_file)db.session.commit()# Prune boardprune_board(board.id)return redirect(url_for("board", slug=slug))# Get threads (posts with no thread_id), sorted by updated_at (bumping)threads = (Post.query.filter_by(board_id=board.id, thread_id=None).order_by(Post.updated_at.desc()).limit(50).all())# Create post context for format_post filter# Include all threads and their recent repliespost_context = {}for thread in threads:if thread.user:post_context[str(thread.id)] = thread.user.nicknameelse:post_context[str(thread.id)] = thread.nickname# Also include recent replies for this threadrecent_replies = (Post.query.filter_by(thread_id=thread.id).order_by(Post.created_at.desc()).limit(3).all())for reply in recent_replies:if reply.user:post_context[str(reply.id)] = reply.user.nicknameelse:post_context[str(reply.id)] = reply.nicknamereturn render_template("board.html", board=board, threads=threads, form=form, post_context=post_context)@app.route("/thread/<int:thread_id>/", methods=["GET", "POST"])def thread(thread_id):thread_post = Post.query.get_or_404(thread_id)if thread_post.thread_id is not None:# If it's a reply, redirect to the main threadreturn redirect(url_for("thread", thread_id=thread_post.thread_id))form = PostForm()if form.validate_on_submit():check_ban()# Get user_id from session or use anonymoususer_id = session.get("user_id")nickname = "Anonyme"if user_id:user = User.query.get(user_id)if user:nickname = user.nicknameelse:user_id = None # Invalid user_idelse:# Anonymous postnickname = form.nickname.data or "Anonyme"# Create replyreply = Post(board_id=thread_post.board_id,thread_id=thread_post.id,user_id=user_id,content=form.content.data,nickname=nickname,ip_address=request.remote_addr,)db.session.add(reply)# Handle multiple filesif form.files.data:for f in form.files.data:2 unmodified linespost_file = PostFile(post_id=reply.id,filename=filename,original_filename=original_filename,)db.session.add(post_file)# Bump the threadthread_post.updated_at = datetime.utcnow()db.session.commit()return redirect(url_for("thread", thread_id=thread_post.id))replies = (Post.query.filter_by(thread_id=thread_post.id).order_by(Post.created_at.asc()).all())# Create post context for format_post filter (maps post_id -> nickname)post_context = {}all_posts = [thread_post] + repliesfor post in all_posts:if post.user:post_context[str(post.id)] = post.user.nicknameelse:post_context[str(post.id)] = post.nicknamereturn render_template("thread.html",thread=thread_post,replies=replies,board=thread_post.board,form=form,post_context=post_context,)# Admin Routes@app.route("/admin/login", methods=["GET", "POST"])def admin_login():if request.method == "POST":password = request.form.get("password")if check_password_hash(app.config["ADMIN_PASSWORD_HASH"], password):session["is_admin"] = Truereturn redirect(url_for("admin_dashboard"))else:flash("Mot de passe invalide")return render_template("admin_login.html")@app.route("/admin/logout")def admin_logout():session.pop("is_admin", None)return redirect(url_for("index"))@app.route("/admin")@admin_requireddef admin_dashboard():# Show recent posts (both threads and replies) for moderationrecent_posts = Post.query.order_by(Post.created_at.desc()).limit(100).all()return render_template("admin.html", posts=recent_posts)@app.route("/admin/delete/<int:post_id>", methods=["POST"])@admin_requireddef delete_post(post_id):post = Post.query.get_or_404(post_id)if post.thread_id is None:# It's a thread starter, delete whole threaddelete_thread_content(post)1 unmodified line# It's a replydelete_post_file(post)db.session.delete(post)db.session.commit()flash("Post supprimé")return redirect(request.referrer or url_for("admin_dashboard"))@app.route("/admin/ban/<int:post_id>", methods=["POST"])@admin_requireddef ban_ip(post_id):post = Post.query.get_or_404(post_id)1 unmodified lineban = BannedIP(ip_address=post.ip_address, reason="Banni par l'administrateur")db.session.add(ban)db.session.commit()flash(f"IP {post.ip_address} bannie")else:flash(f"L'IP {post.ip_address} est déjà bannie")return redirect(request.referrer or url_for("admin_dashboard"))@app.route("/admin/boards")@admin_requireddef admin_boards():boards = Board.query.all()return render_template("admin_boards.html", boards=boards)@app.route("/admin/boards/add", methods=["POST"])@admin_requireddef admin_add_board():slug = request.form.get("slug")name = request.form.get("name")description = request.form.get("description")if slug and name:if not Board.query.filter_by(slug=slug).first():board = Board(slug=slug, name=name, description=description)db.session.add(board)db.session.commit()flash("Planche ajoutée")else:flash("Ce slug existe déjà")else:flash("Données manquantes")return redirect(url_for("admin_boards"))@app.route("/admin/boards/delete/<int:board_id>", methods=["POST"])@admin_requireddef admin_delete_board(board_id):board = Board.query.get_or_404(board_id)1 unmodified lineposts = Post.query.filter_by(board_id=board.id, thread_id=None).all()for post in posts:delete_thread_content(post)db.session.delete(board)db.session.commit()flash("Planche supprimée")return redirect(url_for("admin_boards"))if __name__ == "__main__":app.run(debug=True)
2 unmodified lines3456789101112131415161718192021222324252627282930313233343536372 unmodified linesdb = SQLAlchemy()class Board(db.Model):id = db.Column(db.Integer, primary_key=True)slug = db.Column(db.String(10), unique=True, nullable=False)name = db.Column(db.String(50), nullable=False)description = db.Column(db.String(200))posts = db.relationship('Post', backref='board', lazy=True)class PostFile(db.Model):id = db.Column(db.Integer, primary_key=True)post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)filename = db.Column(db.String(100), nullable=False)original_filename = db.Column(db.String(100), nullable=False)class Post(db.Model):id = db.Column(db.Integer, primary_key=True)thread_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=True) # If null, it's a thread starterboard_id = db.Column(db.Integer, db.ForeignKey('board.id'), nullable=False)content = db.Column(db.Text, nullable=True)nickname = db.Column(db.String(50), default='Anonyme')created_at = db.Column(db.DateTime, default=datetime.utcnow)updated_at = db.Column(db.DateTime, default=datetime.utcnow) # For bumpingip_address = db.Column(db.String(50), nullable=True)files = db.relationship('PostFile', backref='post', lazy=True)# Relationship to access replies easilyreplies = db.relationship('Post',backref=db.backref('parent', remote_side=[id]),lazy=True)class BannedIP(db.Model):id = db.Column(db.Integer, primary_key=True)2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253542 unmodified linesdb = SQLAlchemy()class Board(db.Model):id = db.Column(db.Integer, primary_key=True)slug = db.Column(db.String(10), unique=True, nullable=False)name = db.Column(db.String(50), nullable=False)description = db.Column(db.String(200))posts = db.relationship("Post", backref="board", lazy=True)class User(db.Model):id = db.Column(db.Integer, primary_key=True)nickname = db.Column(db.String(50), unique=True, nullable=False)created_at = db.Column(db.DateTime, default=datetime.utcnow)last_seen_at = db.Column(db.DateTime, default=datetime.utcnow)posts = db.relationship("Post", backref="user", lazy=True)class PostFile(db.Model):id = db.Column(db.Integer, primary_key=True)post_id = db.Column(db.Integer, db.ForeignKey("post.id"), nullable=False)filename = db.Column(db.String(100), nullable=False)original_filename = db.Column(db.String(100), nullable=False)class Post(db.Model):id = db.Column(db.Integer, primary_key=True)thread_id = db.Column(db.Integer, db.ForeignKey("post.id"), nullable=True) # If null, it's a thread starterboard_id = db.Column(db.Integer, db.ForeignKey("board.id"), nullable=False)user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=True) # Nullable for backward compatibilitycontent = db.Column(db.Text, nullable=True)nickname = db.Column(db.String(50), default="Anonyme") # Keep for historical postscreated_at = db.Column(db.DateTime, default=datetime.utcnow)updated_at = db.Column(db.DateTime, default=datetime.utcnow) # For bumpingip_address = db.Column(db.String(50), nullable=True)files = db.relationship("PostFile", backref="post", lazy=True)# Relationship to access replies easilyreplies = db.relationship("Post", backref=db.backref("parent", remote_side=[id]), lazy=True)class BannedIP(db.Model):id = db.Column(db.Integer, primary_key=True)
12345FlaskFlask-SQLAlchemyFlask-WTFemail_validatorWerkzeug123456FlaskFlask-SQLAlchemyFlask-WTFFlask-Migrateemail_validatorWerkzeug
315 unmodified lines316317318319320321315 unmodified lines});}}</script></body></html>315 unmodified lines316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424315 unmodified lines});}}// User nickname managementfunction setNickname(event) {event.preventDefault();const nickname = document.getElementById('nickname-input').value.trim();if (!nickname) {alert('Veuillez entrer un pseudo');return;}fetch('/api/set-nickname', {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify({ nickname: nickname })}).then(response => response.json()).then(data => {if (data.success) {localStorage.setItem('ghostboard_nickname', data.nickname);closeNicknameModal();location.reload(); // Refresh to update UI} else {alert(data.error || 'Erreur lors de la sauvegarde');}}).catch(error => {console.error('Error:', error);alert('Erreur de connexion');});}function getNickname() {return localStorage.getItem('ghostboard_nickname');}function checkNicknameAndShowModal() {// Check if user has a nicknameconst nickname = getNickname();if (!nickname) {// Check with server if user existsfetch('/api/me').then(response => response.json()).then(data => {if (data.nickname) {localStorage.setItem('ghostboard_nickname', data.nickname);} else {// No nickname, show modaldocument.getElementById('nickname-modal').classList.remove('hidden');document.getElementById('nickname-input').focus();}}).catch(error => {console.error('Error checking user:', error);// On error, show modal anywaydocument.getElementById('nickname-modal').classList.remove('hidden');document.getElementById('nickname-input').focus();});}}function closeNicknameModal() {document.getElementById('nickname-modal').classList.add('hidden');}// Auto-fill nickname fieldsfunction autoFillNickname() {const nickname = getNickname();if (nickname) {// Fill nickname inputsconst inputs = document.querySelectorAll('input[name="nickname"]');inputs.forEach(input => {if (!input.value) {input.value = nickname;}});// Hide nickname fields since user has a nicknameconst nicknameFields = document.querySelectorAll('#nickname-field, #nickname-input');nicknameFields.forEach(field => {if (field) field.style.display = 'none';});} else {// Show nickname fields for anonymous usersconst nicknameFields = document.querySelectorAll('#nickname-field, #nickname-input');nicknameFields.forEach(field => {if (field) field.style.display = 'block';});}}// Initialize on page loaddocument.addEventListener('DOMContentLoaded', function() {// Check nickname on index pageif (window.location.pathname === '/') {checkNicknameAndShowModal();}// Auto-fill nickname fieldsautoFillNickname();});</script></body></html>
44 unmodified lines4546474849505160 unmodified lines11211311411511611711811912012144 unmodified lines</div><div class="text-gray-800 text-base leading-relaxed break-words line-clamp-4 mb-3">{{ thread.content|default('', true)|truncate(300)|format_post }}</div><div class="flex items-center justify-between">60 unmodified lines<div class="hidden">{{ form.honeypot() }}</div><div><label class="block text-gray-700 text-sm font-semibold mb-2" for="nickname">Pseudo</label>{{ form.nickname(class="w-full bg-gray-50 text-gray-900 border border-gray-200 rounded-lg py-3 px-4 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent", placeholder="Pseudo (Optionnel)") }}</div><div><label class="block text-gray-700 text-sm font-semibold mb-2" for="content">Message</label>{{ form.content(class="w-full bg-gray-50 text-gray-900 border border-gray-200 rounded-lg py-3 px-4 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent h-40 resize-none text-base", placeholder="Écrivez quelque chose...") }}44 unmodified lines4546474849505160 unmodified lines11211311411511611711811912012144 unmodified lines</div><div class="text-gray-800 text-base leading-relaxed break-words line-clamp-4 mb-3">{{ thread.content|default('', true)|truncate(300)|format_post(post_context) }}</div><div class="flex items-center justify-between">60 unmodified lines<div class="hidden">{{ form.honeypot() }}</div><div id="nickname-field"><label class="block text-gray-700 text-sm font-semibold mb-2" for="nickname">Pseudo</label>{{ form.nickname(class="w-full bg-gray-50 text-gray-900 border border-gray-200 rounded-lg py-3 px-4 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent", placeholder="Pseudo (Optionnel)") }}</div><div><label class="block text-gray-700 text-sm font-semibold mb-2" for="content">Message</label>{{ form.content(class="w-full bg-gray-50 text-gray-900 border border-gray-200 rounded-lg py-3 px-4 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent h-40 resize-none text-base", placeholder="Écrivez quelque chose...") }}
14 unmodified lines1516171814 unmodified lines</a>{% endfor %}</div>{% endblock %}14 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950515214 unmodified lines</a>{% endfor %}</div><!-- Nickname Modal --><div id="nickname-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-gray-900 bg-opacity-40 backdrop-blur-sm p-4"><div class="absolute inset-0" onclick="closeNicknameModal()"></div><div class="bg-white w-full max-w-sm rounded-2xl shadow-2xl transform transition-all relative z-10 overflow-hidden"><div class="p-6 text-center"><h3 class="text-xl font-bold text-gray-900 mb-4">Comment voulez-vous être appelé ?</h3><p class="text-sm text-gray-600 mb-6">Choisissez un pseudo pour vos posts. Il sera enregistré et réutilisé automatiquement.</p><form onsubmit="setNickname(event)" class="space-y-4"><div><inputtype="text"id="nickname-input"placeholder="Votre pseudo..."maxlength="50"class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-center text-lg"required></div><buttontype="submit"class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg transition-colors">Commencer</button></form><p class="text-xs text-gray-500 mt-4">Vous pourrez changer votre pseudo plus tard.</p></div></div></div>{% endblock %}
54 unmodified lines5556575859606176 unmodified lines13813914014114214314454 unmodified lines<div class="space-y-6"><!-- Text --><div class="prose prose-slate max-w-none text-slate-800 text-lg leading-relaxed break-words">{{ thread.content|format_post }}</div><!-- Media Grid -->76 unmodified lines{% endif %}<div class="prose prose-sm max-w-none text-[15px] leading-snug text-slate-800">{{ reply.content|format_post }}</div></div></div>54 unmodified lines5556575859606176 unmodified lines13813914014114214314454 unmodified lines<div class="space-y-6"><!-- Text --><div class="prose prose-slate max-w-none text-slate-800 text-lg leading-relaxed break-words">{{ thread.content|format_post(post_context) }}</div><!-- Media Grid -->76 unmodified lines{% endif %}<div class="prose prose-sm max-w-none text-[15px] leading-snug text-slate-800">{{ reply.content|format_post(post_context) }}</div></div></div>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091{% extends 'base.html' %}
{% block title %}Profil de {{ user.nickname }}{% endblock %}
{% block content %}<div class="max-w-4xl mx-auto px-3 sm:px-6"> <div class="mb-6 pt-6"> <a href="{{ url_for('index') }}" class="inline-flex items-center text-slate-500 hover:text-blue-600 transition-colors font-medium text-sm"> <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" /> </svg> Retour à l'accueil </a> </div>
<!-- User Header --> <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-6 mb-6"> <div class="flex items-center gap-4"> <div class="w-16 h-16 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white font-bold text-2xl shadow-md"> {{ user.nickname[0]|upper }} </div> <div class="flex-1"> <h1 class="text-2xl font-bold text-slate-900">{{ user.nickname }}</h1> <p class="text-slate-600">Membre depuis {{ user.created_at.strftime('%d %B %Y') }}</p> <p class="text-sm text-slate-500">{{ posts|length }} posts publiés</p> </div> </div> </div>
<!-- Posts List --> <div class="space-y-4"> <h2 class="text-xl font-semibold text-slate-900 mb-4">Posts récents</h2>
{% for post in posts %} <div class="bg-white p-6 rounded-xl border border-slate-100 shadow-sm"> <div class="flex items-start gap-4"> <!-- Avatar --> <div class="w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white font-bold text-sm shadow-sm flex-shrink-0"> {{ user.nickname[0]|upper }} </div>
<!-- Content --> <div class="flex-1 min-w-0"> <div class="flex items-center gap-2 mb-2"> <span class="font-semibold text-slate-900">{{ user.nickname }}</span> <span class="text-slate-500">•</span> <span class="text-sm text-slate-500">{{ post.created_at.strftime('%d/%m/%Y %H:%M') }}</span> <span class="text-slate-500">•</span> <a href="{{ url_for('board', slug=post.board.slug) }}" class="text-blue-600 hover:underline">/{{ post.board.slug }}/</a> </div>
<div class="text-slate-800 mb-3 break-words"> {{ post.content|format_post }} </div>
<!-- Media --> {% if post.files %} <div class="flex flex-wrap gap-2 mb-3"> {% for file in post.files %} <div class="rounded-lg overflow-hidden border border-slate-200"> {% if file.filename.endswith(('.mp4', '.webm')) %} <video controls class="max-w-full max-h-48"> <source src="{{ url_for('static', filename='uploads/' + file.filename) }}" type="video/{{ file.filename.split('.')[-1] }}"> </video> {% else %} <img src="{{ url_for('static', filename='uploads/' + file.filename) }}" alt="Image" class="max-w-full max-h-48 object-cover"> {% endif %} </div> {% endfor %} </div> {% endif %}
<!-- Thread link if it's a reply --> {% if post.thread_id %} <a href="{{ url_for('thread', thread_id=post.thread_id) }}" class="text-sm text-blue-600 hover:underline"> Voir le fil complet </a> {% endif %} </div> </div> </div> {% endfor %}
{% if posts|length == 0 %} <div class="text-center text-slate-400 py-12 bg-white rounded-xl border border-slate-100 border-dashed"> <p>Aucun post trouvé.</p> </div> {% endfor %} </div></div>{% endblock %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#!/usr/bin/env python3"""Test script for the new nickname and @pseudo features"""
import requestsimport time
BASE_URL = "http://127.0.0.1:5000"
def test_nickname_api(): """Test the nickname API""" print("Testing nickname API...")
# Test set nickname response = requests.post( f"{BASE_URL}/api/set-nickname", json={"nickname": "TestUser123"} ) print(f"Set nickname response: {response.status_code}") data = response.json() print(f"Response: {data}")
# Test get current user response = requests.get(f"{BASE_URL}/api/me") print(f"Get user response: {response.status_code}") data = response.json() print(f"Current user: {data}")
def test_board_page(): """Test accessing a board page""" print("\nTesting board page...") response = requests.get(f"{BASE_URL}/g/") print(f"Board page response: {response.status_code}") if "nickname-modal" in response.text: print("✅ Nickname modal found on board page") else: print("❌ Nickname modal not found")
if __name__ == "__main__": # Wait for server to start time.sleep(2)
try: test_nickname_api() test_board_page() print("\n✅ All tests completed!") except Exception as e: print(f"❌ Test failed: {e}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import unittestfrom app import app, db, Board, Post, BannedIP, prune_board
class GhostBoardTestCase(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' app.config['WTF_CSRF_ENABLED'] = False self.app = app.test_client() with app.app_context(): db.create_all() b = Board(slug='tst', name='Test Board', description='Testing') db.session.add(b) db.session.commit()
def tearDown(self): with app.app_context(): db.session.remove() db.drop_all()
def test_board_exists(self): response = self.app.get('/tst/') self.assertEqual(response.status_code, 200) self.assertIn(b'Test Board', response.data)
def test_create_thread(self): with app.app_context(): # Mock form data response = self.app.post('/tst/', data=dict( content='Test Thread Content' ), follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertIn(b'Test Thread Content', response.data) post = Post.query.first() self.assertIsNotNone(post) self.assertIsNone(post.thread_id)
def test_pruning(self): with app.app_context(): board = Board.query.filter_by(slug='tst').first() # Create 101 threads for i in range(101): p = Post(board_id=board.id, content=f'Thread {i}') db.session.add(p) db.session.commit() self.assertEqual(Post.query.count(), 101) prune_board(board.id) self.assertEqual(Post.query.count(), 100)
def test_ban_check(self): with app.app_context(): banned = BannedIP(ip_address='127.0.0.1', reason='Test Ban') db.session.add(banned) db.session.commit() response = self.app.post('/tst/', data=dict( content='Should fail' )) self.assertEqual(response.status_code, 403)
if __name__ == '__main__': unittest.main()app.py+330-108
instance/ghostboard.db
models.py+27-10
requirements.txt+1
templates/base.html+103
templates/board.html+5-5
templates/index.html+34
templates/thread.html+2-2
templates/user_profile.htmlAdded+91
test_features.pyAdded+51
tests.pyAdded+64