From 12d831a321709c6ef1e5dea744619278332c8a97 Mon Sep 17 00:00:00 2001 From: Kevin Chung Date: Wed, 29 Apr 2020 03:15:20 -0400 Subject: [PATCH] Make CTFd.utils.user.is_admin wrap a cached function so we avoid a DB hit on page loads --- CTFd/cache/__init__.py | 5 +++++ CTFd/utils/user/__init__.py | 11 +++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/CTFd/cache/__init__.py b/CTFd/cache/__init__.py index 78a63b5..200e207 100644 --- a/CTFd/cache/__init__.py +++ b/CTFd/cache/__init__.py @@ -44,3 +44,8 @@ def clear_pages(): cache.delete_memoized(get_pages) cache.delete_memoized(get_page) + + +def clear_user_session(user_id): + from CTFd.utils.user import get_user_type + cache.delete_memoized(get_user_type, user_id=user_id) diff --git a/CTFd/utils/user/__init__.py b/CTFd/utils/user/__init__.py index 81762ba..a5f0c22 100644 --- a/CTFd/utils/user/__init__.py +++ b/CTFd/utils/user/__init__.py @@ -4,6 +4,7 @@ import re from flask import current_app as app from flask import request, session +from CTFd.cache import cache from CTFd.models import Fails, Users, db from CTFd.utils import get_config @@ -32,14 +33,20 @@ def get_current_user_type(fallback=None): return fallback +@cache.memoize() +def get_user_type(user_id): + user = Users.query.filter_by(id=user_id).first() + return user.type + + def authed(): return bool(session.get("id", False)) def is_admin(): if authed(): - user = get_current_user() - return user.type == "admin" + user_type = get_user_type(user_id=session["id"]) + return user_type == "admin" else: return False