From 558cae4bf51b3c2657f46bd7c52176fb8fed2e91 Mon Sep 17 00:00:00 2001 From: Thorgathis Date: Wed, 23 Sep 2026 20:43:55 +0300 Subject: [PATCH] init --- README.md | 9 ++ __init__.py | 230 ++++++++++++++++++++++++++++++ config.json | 4 + hooks.py | 155 ++++++++++++++++++++ models.py | 58 ++++++++ templates/affiliations/base.html | 45 ++++++ templates/affiliations/codes.html | 79 ++++++++++ templates/affiliations/users.html | 85 +++++++++++ 8 files changed, 665 insertions(+) create mode 100644 README.md create mode 100644 __init__.py create mode 100644 config.json create mode 100644 hooks.py create mode 100644 models.py create mode 100644 templates/affiliations/base.html create mode 100644 templates/affiliations/codes.html create mode 100644 templates/affiliations/users.html diff --git a/README.md b/README.md new file mode 100644 index 0000000..3a73bf9 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# CTFd-affiliations + +CTFd plugin that adds registration codes that set the user's **Affiliation**. Users who register with one of these codes cannot change their affiliation afterwards. + +- The built-in CTFd Registration Code still works. Users who register with it, or with no code, get an empty affiliation they can edit. +- Admin pages are under **Admin → Plugins → CTFd Affiliations**: + - **Codes**: create, edit, disable and delete codes, with optional usage limits. + - **Users**: list the members of an affiliation, add a user by ID, or remove a user. +- If an admin changes a user's affiliation, that user is removed from the code's members. \ No newline at end of file diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..509a268 --- /dev/null +++ b/__init__.py @@ -0,0 +1,230 @@ +import secrets + +from flask import ( + Blueprint, + flash, + get_flashed_messages, + redirect, + render_template, + request, + url_for, +) + +from CTFd.cache import clear_standings, clear_user_session +from CTFd.models import Users, db +from CTFd.utils.decorators import admins_only + +from .hooks import ( + patch_registration_form, + patch_settings_form, + register_affiliation_guard, + system_code, + wrap_register_view, +) +from .models import AffiliationCodes, AffiliationCodeUsers + +PLUGIN_NAME = "ctfd-affiliations" +ERRORS = f"{PLUGIN_NAME}.errors" +INFOS = f"{PLUGIN_NAME}.infos" + + +def _read_code_form(code_id=None): + """Return (code, affiliation, max_uses, errors) from the submitted form.""" + code = request.form.get("code", "").strip() + affiliation = request.form.get("affiliation", "").strip() + max_uses = request.form.get("max_uses", "").strip() + errors = [] + + if code_id is None and not code: + code = secrets.token_hex(4) + if not code or len(code) > 128: + errors.append("Code must be 1-128 characters long") + elif code.lower() == system_code().lower(): + errors.append("Code must differ from the system registration code") + else: + existing = AffiliationCodes.find(code) + if existing is not None and existing.id != code_id: + errors.append("This code already exists") + + if not affiliation or len(affiliation) > 127: + errors.append("Affiliation must be 1-127 characters long") + + if not max_uses or max_uses == "0": + max_uses = None + elif max_uses.isdigit(): + max_uses = int(max_uses) + else: + errors.append("Max uses must be a non-negative integer") + + return code, affiliation, max_uses, errors + + +def _refresh_users(user_ids): + for user_id in user_ids: + clear_user_session(user_id=user_id) + if user_ids: + clear_standings() + + +def _render(template, **kwargs): + return render_template( + template, + errors=get_flashed_messages(category_filter=ERRORS), + infos=get_flashed_messages(category_filter=INFOS), + **kwargs, + ) + + +def load(app): + app.db.create_all() + + patch_registration_form() + patch_settings_form() + wrap_register_view(app) + register_affiliation_guard(app) + + blueprint = Blueprint( + PLUGIN_NAME, + __name__, + template_folder="templates", + url_prefix=f"/plugins/{PLUGIN_NAME}", + ) + + def codes_page(): + return redirect(url_for(f"{PLUGIN_NAME}.admin_codes")) + + def users_page(affiliation): + return redirect(url_for(f"{PLUGIN_NAME}.admin_users", affiliation=affiliation)) + + @blueprint.route("/admin/codes", methods=["GET"]) + @admins_only + def admin_codes(): + codes = AffiliationCodes.query.order_by(AffiliationCodes.id.desc()).all() + return _render("affiliations/codes.html", codes=codes) + + @blueprint.route("/admin/codes", methods=["POST"]) + @admins_only + def admin_create_code(): + code, affiliation, max_uses, errors = _read_code_form() + for error in errors: + flash(error, ERRORS) + if not errors: + db.session.add( + AffiliationCodes(code=code, affiliation=affiliation, max_uses=max_uses) + ) + db.session.commit() + flash(f"Code {code} created", INFOS) + return codes_page() + + @blueprint.route("/admin/codes/", methods=["POST"]) + @admins_only + def admin_update_code(code_id): + code = AffiliationCodes.query.filter_by(id=code_id).first_or_404() + value, affiliation, max_uses, errors = _read_code_form(code_id=code.id) + for error in errors: + flash(error, ERRORS) + if errors: + return codes_page() + + renamed = [] + if affiliation != code.affiliation: + renamed = [ + m.user_id for m in AffiliationCodeUsers.query.filter_by(code_id=code.id) + ] + if renamed: + Users.query.filter(Users.id.in_(renamed)).update( + {"affiliation": affiliation}, synchronize_session=False + ) + code.code = value + code.affiliation = affiliation + code.max_uses = max_uses + code.enabled = request.form.get("enabled") == "y" + db.session.commit() + _refresh_users(renamed) + + flash(f"Code {value} updated", INFOS) + return codes_page() + + @blueprint.route("/admin/codes//delete", methods=["POST"]) + @admins_only + def admin_delete_code(code_id): + code = AffiliationCodes.query.filter_by(id=code_id).first_or_404() + # Members keep their affiliation but may change it again + AffiliationCodeUsers.query.filter_by(code_id=code.id).delete() + db.session.delete(code) + db.session.commit() + flash(f"Code {code.code} deleted", INFOS) + return codes_page() + + @blueprint.route("/admin/users", methods=["GET"]) + @admins_only + def admin_users(): + affiliations = {} + for code in AffiliationCodes.query.order_by(AffiliationCodes.affiliation): + affiliations[code.affiliation] = affiliations.get(code.affiliation, 0) + code.uses + + selected = request.args.get("affiliation") + codes, members = [], [] + if selected in affiliations: + codes = ( + AffiliationCodes.query.filter_by(affiliation=selected) + .order_by(AffiliationCodes.id) + .all() + ) + members = ( + AffiliationCodeUsers.query.join(Users) + .filter(AffiliationCodeUsers.code_id.in_([c.id for c in codes])) + .order_by(AffiliationCodeUsers.created.desc()) + .all() + ) + else: + selected = None + + return _render( + "affiliations/users.html", + affiliations=affiliations, + selected=selected, + codes=codes, + members=members, + ) + + @blueprint.route("/admin/users", methods=["POST"]) + @admins_only + def admin_add_user(): + code = AffiliationCodes.query.filter_by( + id=request.form.get("code_id", type=int) + ).first_or_404() + user = Users.query.filter_by(id=request.form.get("user_id", type=int)).first() + if user is None: + flash("User not found", ERRORS) + return users_page(code.affiliation) + + member = AffiliationCodeUsers.query.filter_by(user_id=user.id).first() + if member is not None and member.code_id == code.id: + flash(f"{user.name} is already a member", ERRORS) + return users_page(code.affiliation) + if member is not None: + db.session.delete(member) + + user.affiliation = code.affiliation + db.session.add(AffiliationCodeUsers(user_id=user.id, code_id=code.id)) + db.session.commit() + _refresh_users([user.id]) + + flash(f"{user.name} added to {code.affiliation}", INFOS) + return users_page(code.affiliation) + + @blueprint.route("/admin/users//delete", methods=["POST"]) + @admins_only + def admin_remove_user(user_id): + member = AffiliationCodeUsers.query.filter_by(user_id=user_id).first_or_404() + affiliation = member.code.affiliation + member.user.affiliation = None + db.session.delete(member) + db.session.commit() + _refresh_users([user_id]) + + flash("User removed from the affiliation", INFOS) + return users_page(affiliation) + + app.register_blueprint(blueprint) diff --git a/config.json b/config.json new file mode 100644 index 0000000..e490109 --- /dev/null +++ b/config.json @@ -0,0 +1,4 @@ +{ + "name": "CTFd Affiliations", + "route": "/plugins/ctfd-affiliations/admin/codes" +} diff --git a/hooks.py b/hooks.py new file mode 100644 index 0000000..8826acf --- /dev/null +++ b/hooks.py @@ -0,0 +1,155 @@ +import functools + +from flask import g, jsonify, render_template, request +from flask_babel import lazy_gettext as _l +from werkzeug.datastructures import ImmutableMultiDict +from wtforms import StringField +from wtforms.validators import Optional + +import CTFd.forms.auth as auth_forms +import CTFd.forms.self as self_forms +from CTFd.models import Users, db +from CTFd.utils import get_config +from CTFd.utils.user import authed, get_current_user, is_admin + +from .models import AffiliationCodes, AffiliationCodeUsers + +LOCKED_MESSAGE = "Your affiliation was set by a registration code and cannot be changed" + + +def system_code(): + return str(get_config("registration_code", default="") or "") + + +def patch_registration_form(): + original_attach = auth_forms.attach_registration_code_field + + def attach_registration_code_field(form_cls): + if system_code(): + return original_attach(form_cls) + if AffiliationCodes.any_enabled(): + form_cls.registration_code = StringField( + "Registration Code", + description="Organization code, if you have one. It sets your affiliation", + validators=[Optional()], + ) + + def build_registration_code_field(form): + field = getattr(form, "registration_code", None) + if field is None: + return [] + field.field_type = "text" + return [field] + + auth_forms.attach_registration_code_field = attach_registration_code_field + auth_forms.build_registration_code_field = build_registration_code_field + + +def _register_error(error): + return render_template( + "register.html", + errors=[error], + name=request.form.get("name", ""), + email=request.form.get("email", ""), + password=request.form.get("password", ""), + ) + + +def wrap_register_view(app): + original = app.view_functions["auth.register"] + + @functools.wraps(original) + def register(*args, **kwargs): + if request.method != "POST" or authed(): + return original(*args, **kwargs) + + entered = request.form.get("registration_code", "").strip() + sys_code = system_code() + if not entered or entered.lower() == sys_code.lower(): + return original(*args, **kwargs) + + code = AffiliationCodes.find(entered) + if code is None or not code.enabled: + if sys_code: + return original(*args, **kwargs) + return _register_error(_l("The registration code you entered was incorrect")) + if code.exhausted: + return _register_error(_l("This registration code has reached its usage limit")) + + code_id, affiliation = code.id, code.affiliation + form = request.form.copy() + form["affiliation"] = affiliation + if sys_code: + form["registration_code"] = sys_code + request.form = ImmutableMultiDict(form) + + response = original(*args, **kwargs) + + user = get_current_user() if authed() else None + if user is not None and user.affiliation == affiliation: + AffiliationCodeUsers.query.filter_by(user_id=user.id).delete() + db.session.add(AffiliationCodeUsers(user_id=user.id, code_id=code_id)) + db.session.commit() + return response + + app.view_functions["auth.register"] = register + + +def patch_settings_form(): + original = self_forms.SettingsForm + + def SettingsForm(*args, **kwargs): + form = original(*args, **kwargs) + user = get_current_user() + if user is not None and AffiliationCodeUsers.is_locked(user.id): + form.affiliation.render_kw = {"readonly": True, "title": LOCKED_MESSAGE} + return form + + self_forms.SettingsForm = SettingsForm + + +def _affiliation_change_target(): + """The user whose affiliation this API request changes, if any.""" + if request.method != "PATCH": + return None + if request.endpoint == "api.users_user_private": + user = get_current_user() + elif request.endpoint == "api.users_user_public" and is_admin(): + user = Users.query.filter_by(id=request.view_args["user_id"]).first() + else: + return None + + data = request.get_json(silent=True) + if user is None or not isinstance(data, dict) or "affiliation" not in data: + return None + if (data["affiliation"] or "") == (user.affiliation or ""): + return None + return user + + +def register_affiliation_guard(app): + @app.before_request + def guard_locked_affiliation(): + if not authed(): + return + user = _affiliation_change_target() + if user is None or not AffiliationCodeUsers.is_locked(user.id): + return + if is_admin(): + # The admin overrides the code: unlock once the change is saved + g.affiliation_unlock_user_id = user.id + return + return jsonify({"success": False, "errors": {"affiliation": [LOCKED_MESSAGE]}}), 400 + + @app.before_request + def track_user_deletion(): + if request.method == "DELETE" and request.endpoint == "api.users_user_public": + g.affiliation_unlock_user_id = request.view_args["user_id"] + + @app.after_request + def drop_membership(response): + user_id = g.pop("affiliation_unlock_user_id", None) + if user_id is not None and response.status_code == 200: + AffiliationCodeUsers.query.filter_by(user_id=user_id).delete() + db.session.commit() + return response diff --git a/models.py b/models.py new file mode 100644 index 0000000..e909288 --- /dev/null +++ b/models.py @@ -0,0 +1,58 @@ +import datetime + +from sqlalchemy import func + +from CTFd.models import Users, db + + +class AffiliationCodes(db.Model): + __tablename__ = "affiliation_codes" + + id = db.Column(db.Integer, primary_key=True) + code = db.Column(db.String(128), unique=True, nullable=False) + affiliation = db.Column(db.String(127), nullable=False) + max_uses = db.Column(db.Integer, nullable=True) # None means unlimited + enabled = db.Column(db.Boolean, nullable=False, default=True) + + @property + def uses(self): + return ( + AffiliationCodeUsers.query.join(Users) + .filter(AffiliationCodeUsers.code_id == self.id) + .count() + ) + + @property + def exhausted(self): + return self.max_uses is not None and self.uses >= self.max_uses + + @classmethod + def find(cls, code): + return cls.query.filter(func.lower(cls.code) == code.lower()).first() + + @classmethod + def any_enabled(cls): + return cls.query.filter_by(enabled=True).first() is not None + + +class AffiliationCodeUsers(db.Model): + """Users whose affiliation is set and locked by a code.""" + + __tablename__ = "affiliation_code_users" + + user_id = db.Column( + db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"), primary_key=True + ) + code_id = db.Column( + db.Integer, + db.ForeignKey("affiliation_codes.id", ondelete="CASCADE"), + nullable=False, + ) + created = db.Column(db.DateTime, default=datetime.datetime.utcnow) + + user = db.relationship("Users", lazy="joined") + code = db.relationship("AffiliationCodes", lazy="joined") + + @classmethod + def is_locked(cls, user_id): + return cls.query.filter_by(user_id=user_id).first() is not None diff --git a/templates/affiliations/base.html b/templates/affiliations/base.html new file mode 100644 index 0000000..294f40b --- /dev/null +++ b/templates/affiliations/base.html @@ -0,0 +1,45 @@ +{% extends "admin/base.html" %} + +{% block content %} +
+
+

CTFd Affiliations

+
+
+
+
+
+ +
+
+ {% for error in errors %} + + {% endfor %} + {% for info in infos %} + + {% endfor %} + + {% block page %}{% endblock %} +
+
+
+{% endblock %} diff --git a/templates/affiliations/codes.html b/templates/affiliations/codes.html new file mode 100644 index 0000000..3699b9b --- /dev/null +++ b/templates/affiliations/codes.html @@ -0,0 +1,79 @@ +{% extends "affiliations/base.html" %} +{% set active_page = "codes" %} + +{% block page %} +

New code

+
+ +
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ +

Codes

+{% if codes %} + + + + + + + + + + + + + {% for code in codes %} + + + + + + + + + {% endfor %} + +
AffiliationCodeUsesMax usesEnabled
+
+ +
+ +
+ + + {{ code.uses }} + + + + + {% if code.exhausted %}
limit reached{% endif %} +
+ +
+ + +
+
+{% else %} +

No codes yet.

+{% endif %} +{% endblock %} diff --git a/templates/affiliations/users.html b/templates/affiliations/users.html new file mode 100644 index 0000000..a237bea --- /dev/null +++ b/templates/affiliations/users.html @@ -0,0 +1,85 @@ +{% extends "affiliations/base.html" %} +{% set active_page = "users" %} + +{% block page %} +{% if affiliations %} +
+ + +
+{% else %} +

+ No affiliations yet. Create a code on the + Codes page. +

+{% endif %} + +{% if selected is not none %} +
+ +
+ + +
+ {% if codes | length > 1 %} +
+ + +
+ {% else %} + + {% endif %} +
+ +
+
+ +{% if members %} + + + + + + + + + + + + + {% for member in members %} + + + + + + + + + {% endfor %} + +
IDUserEmailCodeAdded
{{ member.user.id }}{{ member.user.name }}{{ member.user.email }}{{ member.code.code }}{{ member.created.strftime('%Y-%m-%d %H:%M') if member.created else '' }} UTC +
+ + +
+
+{% else %} +

No users in this affiliation yet.

+{% endif %} +{% endif %} +{% endblock %}