UI updates and caching fixes on submission

This commit is contained in:
2026-01-05 22:52:20 +00:00
parent db14e03f0e
commit 96714c2b60
2 changed files with 89 additions and 40 deletions

View File

@@ -7,6 +7,7 @@ from CTFd.utils.decorators.visibility import check_challenge_visibility
from CTFd.plugins.flags import get_flag_class from CTFd.plugins.flags import get_flag_class
from CTFd.plugins.challenges import get_chal_class from CTFd.plugins.challenges import get_chal_class
from CTFd.utils import get_config, set_config from CTFd.utils import get_config, set_config
from CTFd.cache import clear_challenges, clear_standings
def load(app): def load(app):
plugin_bp = Blueprint('category_submission', __name__, plugin_bp = Blueprint('category_submission', __name__,
@@ -51,12 +52,12 @@ def load(app):
if category not in enabled_cats: if category not in enabled_cats:
return jsonify({'success': False, 'message': 'Invalid category'}) return jsonify({'success': False, 'message': 'Invalid category'})
# Rate Limiting # 1. Rate Limiting
last_sub = Submissions.query.filter_by(user_id=user.id).order_by(Submissions.date.desc()).first() last_sub = Submissions.query.filter_by(user_id=user.id).order_by(Submissions.date.desc()).first()
if last_sub and (time.time() - last_sub.date.timestamp() < cooldown): if last_sub and (time.time() - last_sub.date.timestamp() < cooldown):
return jsonify({'success': False, 'message': f'Wait {cooldown}s'}) return jsonify({'success': False, 'message': f'Wait {cooldown}s'})
# Search unsolved challenges in this category # 2. Search unsolved challenges in this category
solve_filter = (Solves.team_id == team.id) if team else (Solves.user_id == user.id) solve_filter = (Solves.team_id == team.id) if team else (Solves.user_id == user.id)
challenges = Challenges.query.filter( challenges = Challenges.query.filter(
Challenges.category == category, Challenges.category == category,
@@ -65,25 +66,35 @@ def load(app):
).all() ).all()
for chall in challenges: for chall in challenges:
# 1. Manual check (no DB write)
flags = Flags.query.filter_by(challenge_id=chall.id).all() flags = Flags.query.filter_by(challenge_id=chall.id).all()
for flag in flags: for flag in flags:
try: try:
# Perform comparison in-memory to avoid cluttering logs with incorrects
if get_flag_class(flag.type).compare(flag, provided): if get_flag_class(flag.type).compare(flag, provided):
# 2. Match found! Now use built-in CTFd methods. # 3. Match Found: Log the correct submission
sub = Submissions(
user_id=user.id, team_id=team.id if team else None,
challenge_id=chall.id, ip=request.remote_addr, provided=provided, type='correct'
)
db.session.add(sub)
# 4. Native Solve Logic (Handles points and Solves table)
chal_class = get_chal_class(chall.type) chal_class = get_chal_class(chall.type)
# attempt() creates the 'correct' Submission record
chal_class.attempt(chall, request)
# solve() creates the Solve record and awards points
chal_class.solve(user=user, team=team, challenge=chall, request=request) chal_class.solve(user=user, team=team, challenge=chall, request=request)
# 5. Clear Caches so UI reflects changes immediately
clear_challenges()
clear_standings()
db.session.commit() db.session.commit()
return jsonify({'success': True, 'message': f'Correct! Solved: {chall.name}'}) return jsonify({
'success': True,
'message': f'Correct: {chall.name}',
'challenge_id': chall.id
})
except Exception: continue except Exception: continue
# 3. No match: Log ONE incorrect attempt globally # 6. No Match: Log exactly one incorrect attempt globally
db.session.add(Submissions( db.session.add(Submissions(
user_id=user.id, team_id=team.id if team else None, user_id=user.id, team_id=team.id if team else None,
challenge_id=None, ip=request.remote_addr, provided=provided, type='incorrect' challenge_id=None, ip=request.remote_addr, provided=provided, type='incorrect'

View File

@@ -1,44 +1,74 @@
(function() { (function() {
if (window.location.pathname !== '/challenges') return; if (window.location.pathname !== '/challenges') return;
// LocalStorage to bypass server-side cache delays
const getLocalSolves = () => JSON.parse(localStorage.getItem('temp_solves') || "[]");
const addLocalSolve = (id) => {
const solves = getLocalSolves();
if (!solves.includes(id)) {
solves.push(id);
localStorage.setItem('temp_solves', JSON.stringify(solves));
}
};
function injectBoxes(config) { function injectBoxes(config) {
// Highlight locally solved challenges
getLocalSolves().forEach(id => {
const el = document.querySelector(`[data-id="${id}"]`);
if (el && !el.classList.contains('solved')) el.classList.add('solved');
});
const enabledCategories = config.categories || []; const enabledCategories = config.categories || [];
// We look for category headers
document.querySelectorAll('.category-header').forEach(header => { document.querySelectorAll('.category-header').forEach(header => {
const catName = header.textContent.trim(); const catName = header.textContent.trim();
// Check if already injected to prevent duplicates // Prevent duplicate injections
if (enabledCategories.includes(catName) && !header.nextElementSibling?.classList.contains('cat-sub-row')) { if (enabledCategories.includes(catName) && !header.parentElement.querySelector('.cat-sub-container')) {
const row = document.createElement('div');
row.className = "cat-sub-row row mb-4 justify-content-center"; const container = document.createElement('div');
row.innerHTML = ` container.className = "cat-sub-container mb-4";
<div class="col-md-10"> // Style to match the alignment of the text exactly
<div class="input-group input-group-lg"> container.style.maxWidth = "700px";
container.style.marginTop = "10px";
container.innerHTML = `
<div class="input-group" style="display: flex; width: 100%;">
<input type="text" <input type="text"
class="form-control bg-dark text-light border-secondary" class="form-control bg-dark text-light"
placeholder="Submit ${catName} flag..." placeholder="Submit ${catName} flag..."
id="in-${catName.replace(/\s+/g, '-')}" id="in-${catName.replace(/\s+/g, '-')}"
autocomplete="off"> autocomplete="off"
<div class="input-group-append"> style="border-color: #495057; border-top-right-radius: 0; border-bottom-right-radius: 0; height: 45px;">
<button class="btn btn-success px-4" type="button">Submit</button> <div class="input-group-append" style="margin-left: -1px;">
<button class="btn btn-success btn-sub"
type="button"
style="border-top-left-radius: 0; border-bottom-left-radius: 0; height: 45px; font-weight: 600; padding: 0 25px;">
Submit
</button>
</div> </div>
</div> </div>
<div class="status-msg mt-2" style="min-height: 24px; font-weight: bold;"></div> <div class="status-msg mt-2" style="min-height: 24px; font-size: 0.9rem; font-weight: 500;"></div>
</div>
`; `;
header.after(row);
const input = row.querySelector('input'); header.after(container);
const btn = row.querySelector('button');
const msg = row.querySelector('.status-msg'); const input = container.querySelector('input');
const btn = container.querySelector('button');
const msg = container.querySelector('.status-msg');
const submitFlag = () => { const submitFlag = () => {
const val = input.value.trim(); const val = input.value.trim();
if (!val || btn.disabled) return; if (!val || btn.disabled) return;
btn.disabled = true; btn.disabled = true;
msg.innerHTML = '<span class="text-info">Checking...</span>'; msg.innerHTML = '<span class="text-info">Checking flag...</span>';
const params = new URLSearchParams({ submission: val, category: catName, nonce: init.csrfNonce }); const params = new URLSearchParams({
submission: val,
category: catName,
nonce: init.csrfNonce
});
fetch('/category_submit', { fetch('/category_submit', {
method: 'POST', method: 'POST',
@@ -48,9 +78,15 @@
.then(r => r.json()) .then(r => r.json())
.then(data => { .then(data => {
if (data.success) { if (data.success) {
addLocalSolve(data.challenge_id);
msg.innerHTML = `<span class="text-success">✔ ${data.message}</span>`; msg.innerHTML = `<span class="text-success">✔ ${data.message}</span>`;
input.value = ''; input.value = '';
setTimeout(() => { window.location.reload(); }, 1000);
// Visual feedback on the challenge card
const card = document.querySelector(`[data-id="${data.challenge_id}"]`);
if (card) card.classList.add('solved');
setTimeout(() => { window.location.reload(); }, 1200);
} else { } else {
msg.innerHTML = `<span class="text-danger">✘ ${data.message}</span>`; msg.innerHTML = `<span class="text-danger">✘ ${data.message}</span>`;
btn.disabled = false; btn.disabled = false;
@@ -68,7 +104,9 @@
}); });
} }
fetch('/category_submit/config').then(r => r.json()).then(config => { fetch('/category_submit/config')
.then(r => r.json())
.then(config => {
injectBoxes(config); injectBoxes(config);
const observer = new MutationObserver(() => { const observer = new MutationObserver(() => {
observer.disconnect(); observer.disconnect();