This commit is contained in:
2026-09-23 20:43:55 +03:00
commit 558cae4bf5
8 changed files with 665 additions and 0 deletions
+9
View File
@@ -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.
+230
View File
@@ -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/<int:code_id>", 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/<int:code_id>/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/<int:user_id>/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)
+4
View File
@@ -0,0 +1,4 @@
{
"name": "CTFd Affiliations",
"route": "/plugins/ctfd-affiliations/admin/codes"
}
+155
View File
@@ -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
+58
View File
@@ -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
+45
View File
@@ -0,0 +1,45 @@
{% extends "admin/base.html" %}
{% block content %}
<div class="jumbotron">
<div class="container">
<h1>CTFd Affiliations</h1>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-3">
<ul class="nav nav-pills flex-column">
<li class="nav-item">
<a class="nav-link rounded-0 {% if active_page == 'codes' %}active{% endif %}"
href="{{ url_for('ctfd-affiliations.admin_codes') }}">Codes</a>
</li>
<li class="nav-item">
<a class="nav-link rounded-0 {% if active_page == 'users' %}active{% endif %}"
href="{{ url_for('ctfd-affiliations.admin_users') }}">Users</a>
</li>
</ul>
</div>
<div class="col-md-9">
{% for error in errors %}
<div class="alert alert-danger alert-dismissable" role="alert">
{{ error }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% for info in infos %}
<div class="alert alert-success alert-dismissable" role="alert">
{{ info }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% block page %}{% endblock %}
</div>
</div>
</div>
{% endblock %}
+79
View File
@@ -0,0 +1,79 @@
{% extends "affiliations/base.html" %}
{% set active_page = "codes" %}
{% block page %}
<h4>New code</h4>
<form method="POST" action="{{ url_for('ctfd-affiliations.admin_create_code') }}" class="form-row align-items-end">
<input type="hidden" name="nonce" value="{{ Session.nonce }}">
<div class="form-group col-md-4">
<label for="new-affiliation"><b>Affiliation</b></label>
<input id="new-affiliation" name="affiliation" class="form-control" maxlength="127" required>
</div>
<div class="form-group col-md-3">
<label for="new-code"><b>Code</b></label>
<input id="new-code" name="code" class="form-control" maxlength="128" placeholder="Random if empty">
</div>
<div class="form-group col-md-3">
<label for="new-max-uses"><b>Max uses</b></label>
<input id="new-max-uses" name="max_uses" type="number" min="0" class="form-control" placeholder="Unlimited">
</div>
<div class="form-group col-md-2">
<button type="submit" class="btn btn-primary w-100">Create</button>
</div>
</form>
<h4 class="mt-4">Codes</h4>
{% if codes %}
<table class="table table-striped border">
<thead>
<tr>
<th>Affiliation</th>
<th>Code</th>
<th class="text-center">Uses</th>
<th>Max uses</th>
<th class="text-center">Enabled</th>
<th></th>
</tr>
</thead>
<tbody>
{% for code in codes %}
<tr>
<td>
<form id="edit-{{ code.id }}" method="POST" action="{{ url_for('ctfd-affiliations.admin_update_code', code_id=code.id) }}">
<input type="hidden" name="nonce" value="{{ Session.nonce }}">
</form>
<input form="edit-{{ code.id }}" name="affiliation" class="form-control form-control-sm" value="{{ code.affiliation }}" maxlength="127" required>
</td>
<td>
<input form="edit-{{ code.id }}" name="code" class="form-control form-control-sm text-monospace" value="{{ code.code }}" maxlength="128" required>
</td>
<td class="text-center align-middle">
<a href="{{ url_for('ctfd-affiliations.admin_users', affiliation=code.affiliation) }}" title="Show users">{{ code.uses }}</a>
</td>
<td>
<input form="edit-{{ code.id }}" name="max_uses" type="number" min="0" class="form-control form-control-sm" value="{{ code.max_uses or '' }}" placeholder="∞">
</td>
<td class="text-center align-middle">
<input form="edit-{{ code.id }}" name="enabled" type="checkbox" value="y" {% if code.enabled %}checked{% endif %}>
{% if code.exhausted %}<br><small class="text-danger">limit reached</small>{% endif %}
</td>
<td class="text-right text-nowrap">
<button form="edit-{{ code.id }}" type="submit" class="btn btn-sm btn-outline-primary" title="Save">
<i class="fas fa-save"></i>
</button>
<form method="POST" action="{{ url_for('ctfd-affiliations.admin_delete_code', code_id=code.id) }}" class="d-inline"
onsubmit="return confirm('Delete code {{ code.code }}? Its users keep the affiliation but will be able to change it.');">
<input type="hidden" name="nonce" value="{{ Session.nonce }}">
<button type="submit" class="btn btn-sm btn-outline-danger" title="Delete">
<i class="fas fa-times"></i>
</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="text-muted">No codes yet.</p>
{% endif %}
{% endblock %}
+85
View File
@@ -0,0 +1,85 @@
{% extends "affiliations/base.html" %}
{% set active_page = "users" %}
{% block page %}
{% if affiliations %}
<form method="GET" action="{{ url_for('ctfd-affiliations.admin_users') }}" class="mb-4">
<label for="affiliation-select"><b>Affiliation</b></label>
<select id="affiliation-select" name="affiliation" class="form-control custom-select" onchange="this.form.submit()">
<option value="" disabled {% if selected is none %}selected{% endif %}>Select affiliation</option>
{% for affiliation, count in affiliations.items() %}
<option value="{{ affiliation }}" {% if affiliation == selected %}selected{% endif %}>
{{ affiliation }} ({{ count }})
</option>
{% endfor %}
</select>
</form>
{% else %}
<p class="text-muted">
No affiliations yet. Create a code on the
<a href="{{ url_for('ctfd-affiliations.admin_codes') }}">Codes</a> page.
</p>
{% endif %}
{% if selected is not none %}
<form method="POST" action="{{ url_for('ctfd-affiliations.admin_add_user') }}" class="form-row align-items-end mb-3">
<input type="hidden" name="nonce" value="{{ Session.nonce }}">
<div class="form-group col-md-4">
<label for="add-user-id"><b>User ID</b></label>
<input id="add-user-id" name="user_id" type="number" min="1" class="form-control" required>
</div>
{% if codes | length > 1 %}
<div class="form-group col-md-4">
<label for="add-code"><b>Code</b></label>
<select id="add-code" name="code_id" class="form-control custom-select">
{% for code in codes %}
<option value="{{ code.id }}">{{ code.code }}</option>
{% endfor %}
</select>
</div>
{% else %}
<input type="hidden" name="code_id" value="{{ codes[0].id }}">
{% endif %}
<div class="form-group col-md-2">
<button type="submit" class="btn btn-primary w-100">Add</button>
</div>
</form>
{% if members %}
<table class="table table-striped border">
<thead>
<tr>
<th class="text-center">ID</th>
<th>User</th>
<th>Email</th>
<th>Code</th>
<th>Added</th>
<th></th>
</tr>
</thead>
<tbody>
{% for member in members %}
<tr>
<td class="text-center">{{ member.user.id }}</td>
<td><a href="{{ url_for('admin.users_detail', user_id=member.user.id) }}">{{ member.user.name }}</a></td>
<td>{{ member.user.email }}</td>
<td class="text-monospace">{{ member.code.code }}</td>
<td>{{ member.created.strftime('%Y-%m-%d %H:%M') if member.created else '' }} UTC</td>
<td class="text-right">
<form method="POST" action="{{ url_for('ctfd-affiliations.admin_remove_user', user_id=member.user_id) }}" class="d-inline"
onsubmit="return confirm('Remove {{ member.user.name }} from {{ selected }}? Their affiliation will be cleared.');">
<input type="hidden" name="nonce" value="{{ Session.nonce }}">
<button type="submit" class="btn btn-sm btn-outline-danger" title="Remove">
<i class="fas fa-times"></i>
</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="text-muted">No users in this affiliation yet.</p>
{% endif %}
{% endif %}
{% endblock %}