Switch to get_user_attrs strategy

is_admin_func_cache_hit
Kevin Chung 2020-04-29 20:19:05 -04:00
parent ff4ad5185f
commit f86b7ae18f
6 changed files with 56 additions and 14 deletions

3
.gitignore vendored
View File

@ -73,3 +73,6 @@ CTFd/uploads
# JS
node_modules/
# Flask Profiler files
flask_profiler.sql

View File

@ -47,6 +47,6 @@ def clear_pages():
def clear_user_session(user_id):
from CTFd.utils.user import get_user_type
from CTFd.utils.user import get_user_attrs
cache.delete_memoized(get_user_type, user_id=user_id)
cache.delete_memoized(get_user_attrs, user_id=user_id)

22
CTFd/constants/users.py Normal file
View File

@ -0,0 +1,22 @@
from collections import namedtuple
UserAttrs = namedtuple(
"UserAttrs",
[
"id",
"oauth_id",
"name",
"email",
"type",
"secret",
"website",
"affiliation",
"country",
"bracket",
"hidden",
"banned",
"verified",
"team_id",
"created",
],
)

View File

@ -5,7 +5,8 @@ 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.constants.users import UserAttrs
from CTFd.models import Fails, Users, db, Teams
from CTFd.utils import get_config
@ -17,6 +18,24 @@ def get_current_user():
return None
def get_current_user_attrs():
if authed():
return get_user_attrs(user_id=session["id"])
else:
return None
@cache.memoize()
def get_user_attrs(user_id):
user = Users.query.filter_by(id=user_id).first()
if user:
d = {}
for field in UserAttrs._fields:
d[field] = getattr(user, field)
return UserAttrs(**d)
return user
def get_current_team():
if authed():
user = get_current_user()
@ -27,33 +46,27 @@ def get_current_team():
def get_current_user_type(fallback=None):
if authed():
user = Users.query.filter_by(id=session["id"]).first()
user = get_current_user_attrs()
return user.type
else:
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_type = get_user_type(user_id=session["id"])
return user_type == "admin"
user = get_current_user_attrs()
return user.type == "admin"
else:
return False
def is_verified():
if get_config("verify_emails"):
user = get_current_user()
user = get_current_user_attrs()
if user:
return user.verified
else:

View File

@ -10,7 +10,7 @@ psycopg2-binary==2.7.5
codecov==2.0.15
moto==1.3.7
bandit==1.5.1
flask_profiler==1.7
flask_profiler==1.8.1
pytest-xdist==1.28.0
pytest-cov==2.8.1
sphinx_rtd_theme==0.4.3

View File

@ -18,6 +18,10 @@ if args.profile:
"enabled": app.config["DEBUG"],
"storage": {"engine": "sqlite"},
"basicAuth": {"enabled": False},
"ignore": [
"^/themes/.*",
"^/events",
]
}
flask_profiler.init_app(app)
app.config["DEBUG_TB_PROFILER_ENABLED"] = True