We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
log rotation does not works
In the file https://github.com/CTFd/CTFd/blob/master/CTFd/utils/initialization/__init__.py#L107
the log handlers `logging.handlers.RotatingFileHandler` are not created with the right parameters (see [RotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.RotatingFileHandler)) because _if either of maxBytes or backupCount is zero, rollover never occurs_ (`backupCount` parameter is missing)

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `CTFd/utils/initialization/__init__.py`
Content:
```
1 import datetime
2 import logging
3 import os
4 import sys
5 
6 from flask import abort, redirect, render_template, request, session, url_for
7 from sqlalchemy.exc import IntegrityError, InvalidRequestError
8 from werkzeug.wsgi import DispatcherMiddleware
9 
10 from CTFd.exceptions import UserNotFoundException, UserTokenExpiredException
11 from CTFd.models import Tracking, db
12 from CTFd.utils import config, get_config, markdown
13 from CTFd.utils.config import (
14     can_send_mail,
15     ctf_logo,
16     ctf_name,
17     ctf_theme,
18     integrations,
19     is_setup,
20 )
21 from CTFd.utils.config.pages import get_pages
22 from CTFd.utils.config.visibility import (
23     accounts_visible,
24     challenges_visible,
25     registration_visible,
26     scores_visible,
27 )
28 from CTFd.utils.countries import get_countries, lookup_country_code
29 from CTFd.utils.dates import isoformat, unix_time, unix_time_millis
30 from CTFd.utils.events import EventManager, RedisEventManager
31 from CTFd.utils.modes import generate_account_url, get_mode_as_word
32 from CTFd.utils.plugins import (
33     get_configurable_plugins,
34     get_registered_admin_scripts,
35     get_registered_admin_stylesheets,
36     get_registered_scripts,
37     get_registered_stylesheets,
38 )
39 from CTFd.utils.security.auth import login_user, logout_user, lookup_user_token
40 from CTFd.utils.security.csrf import generate_nonce
41 from CTFd.utils.user import authed, get_current_team, get_current_user, get_ip
42 
43 
44 def init_template_filters(app):
45     app.jinja_env.filters["markdown"] = markdown
46     app.jinja_env.filters["unix_time"] = unix_time
47     app.jinja_env.filters["unix_time_millis"] = unix_time_millis
48     app.jinja_env.filters["isoformat"] = isoformat
49 
50 
51 def init_template_globals(app):
52     app.jinja_env.globals.update(config=config)
53     app.jinja_env.globals.update(get_pages=get_pages)
54     app.jinja_env.globals.update(can_send_mail=can_send_mail)
55     app.jinja_env.globals.update(get_ctf_name=ctf_name)
56     app.jinja_env.globals.update(get_ctf_logo=ctf_logo)
57     app.jinja_env.globals.update(get_ctf_theme=ctf_theme)
58     app.jinja_env.globals.update(get_configurable_plugins=get_configurable_plugins)
59     app.jinja_env.globals.update(get_registered_scripts=get_registered_scripts)
60     app.jinja_env.globals.update(get_registered_stylesheets=get_registered_stylesheets)
61     app.jinja_env.globals.update(
62         get_registered_admin_scripts=get_registered_admin_scripts
63     )
64     app.jinja_env.globals.update(
65         get_registered_admin_stylesheets=get_registered_admin_stylesheets
66     )
67     app.jinja_env.globals.update(get_config=get_config)
68     app.jinja_env.globals.update(generate_account_url=generate_account_url)
69     app.jinja_env.globals.update(get_countries=get_countries)
70     app.jinja_env.globals.update(lookup_country_code=lookup_country_code)
71     app.jinja_env.globals.update(accounts_visible=accounts_visible)
72     app.jinja_env.globals.update(challenges_visible=challenges_visible)
73     app.jinja_env.globals.update(registration_visible=registration_visible)
74     app.jinja_env.globals.update(scores_visible=scores_visible)
75     app.jinja_env.globals.update(get_mode_as_word=get_mode_as_word)
76     app.jinja_env.globals.update(integrations=integrations)
77     app.jinja_env.globals.update(authed=authed)
78 
79 
80 def init_logs(app):
81     logger_submissions = logging.getLogger("submissions")
82     logger_logins = logging.getLogger("logins")
83     logger_registrations = logging.getLogger("registrations")
84 
85     logger_submissions.setLevel(logging.INFO)
86     logger_logins.setLevel(logging.INFO)
87     logger_registrations.setLevel(logging.INFO)
88 
89     log_dir = app.config["LOG_FOLDER"]
90     if not os.path.exists(log_dir):
91         os.makedirs(log_dir)
92 
93     logs = {
94         "submissions": os.path.join(log_dir, "submissions.log"),
95         "logins": os.path.join(log_dir, "logins.log"),
96         "registrations": os.path.join(log_dir, "registrations.log"),
97     }
98 
99     try:
100         for log in logs.values():
101             if not os.path.exists(log):
102                 open(log, "a").close()
103 
104         submission_log = logging.handlers.RotatingFileHandler(
105             logs["submissions"], maxBytes=10000
106         )
107         login_log = logging.handlers.RotatingFileHandler(logs["logins"], maxBytes=10000)
108         registration_log = logging.handlers.RotatingFileHandler(
109             logs["registrations"], maxBytes=10000
110         )
111 
112         logger_submissions.addHandler(submission_log)
113         logger_logins.addHandler(login_log)
114         logger_registrations.addHandler(registration_log)
115     except IOError:
116         pass
117 
118     stdout = logging.StreamHandler(stream=sys.stdout)
119 
120     logger_submissions.addHandler(stdout)
121     logger_logins.addHandler(stdout)
122     logger_registrations.addHandler(stdout)
123 
124     logger_submissions.propagate = 0
125     logger_logins.propagate = 0
126     logger_registrations.propagate = 0
127 
128 
129 def init_events(app):
130     if app.config.get("CACHE_TYPE") == "redis":
131         app.events_manager = RedisEventManager()
132     elif app.config.get("CACHE_TYPE") == "filesystem":
133         app.events_manager = EventManager()
134     else:
135         app.events_manager = EventManager()
136 
137 
138 def init_request_processors(app):
139     @app.context_processor
140     def inject_user():
141         if session:
142             return dict(session)
143         return dict()
144 
145     @app.url_defaults
146     def inject_theme(endpoint, values):
147         if "theme" not in values and app.url_map.is_endpoint_expecting(
148             endpoint, "theme"
149         ):
150             values["theme"] = ctf_theme()
151 
152     @app.before_request
153     def needs_setup():
154         if is_setup() is False:
155             if request.endpoint in (
156                 "views.setup",
157                 "views.integrations",
158                 "views.themes",
159             ):
160                 return
161             else:
162                 return redirect(url_for("views.setup"))
163 
164     @app.before_request
165     def tracker():
166         if request.endpoint == "views.themes":
167             return
168 
169         if authed():
170             track = Tracking.query.filter_by(ip=get_ip(), user_id=session["id"]).first()
171             if not track:
172                 visit = Tracking(ip=get_ip(), user_id=session["id"])
173                 db.session.add(visit)
174             else:
175                 track.date = datetime.datetime.utcnow()
176 
177             try:
178                 db.session.commit()
179             except (InvalidRequestError, IntegrityError):
180                 db.session.rollback()
181                 logout_user()
182 
183             if authed():
184                 user = get_current_user()
185                 team = get_current_team()
186 
187                 if request.path.startswith("/themes") is False:
188                     if user and user.banned:
189                         return (
190                             render_template(
191                                 "errors/403.html",
192                                 error="You have been banned from this CTF",
193                             ),
194                             403,
195                         )
196 
197                     if team and team.banned:
198                         return (
199                             render_template(
200                                 "errors/403.html",
201                                 error="Your team has been banned from this CTF",
202                             ),
203                             403,
204                         )
205 
206             db.session.close()
207 
208     @app.before_request
209     def tokens():
210         token = request.headers.get("Authorization")
211         if token and request.content_type == "application/json":
212             try:
213                 token_type, token = token.split(" ", 1)
214                 user = lookup_user_token(token)
215             except UserNotFoundException:
216                 abort(401)
217             except UserTokenExpiredException:
218                 abort(401)
219             except Exception:
220                 abort(401)
221             else:
222                 login_user(user)
223 
224     @app.before_request
225     def csrf():
226         try:
227             func = app.view_functions[request.endpoint]
228         except KeyError:
229             abort(404)
230         if hasattr(func, "_bypass_csrf"):
231             return
232         if request.headers.get("Authorization"):
233             return
234         if not session.get("nonce"):
235             session["nonce"] = generate_nonce()
236         if request.method not in ("GET", "HEAD", "OPTIONS", "TRACE"):
237             if request.content_type == "application/json":
238                 if session["nonce"] != request.headers.get("CSRF-Token"):
239                     abort(403)
240             if request.content_type != "application/json":
241                 if session["nonce"] != request.form.get("nonce"):
242                     abort(403)
243 
244     application_root = app.config.get("APPLICATION_ROOT")
245     if application_root != "/":
246 
247         @app.before_request
248         def force_subdirectory_redirect():
249             if request.path.startswith(application_root) is False:
250                 return redirect(
251                     application_root + request.script_root + request.full_path
252                 )
253 
254         app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {application_root: app})
255
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/CTFd/utils/initialization/__init__.py b/CTFd/utils/initialization/__init__.py
--- a/CTFd/utils/initialization/__init__.py
+++ b/CTFd/utils/initialization/__init__.py
@@ -102,11 +102,13 @@
                 open(log, "a").close()
 
         submission_log = logging.handlers.RotatingFileHandler(
-            logs["submissions"], maxBytes=10000
+            logs["submissions"], maxBytes=10485760, backupCount=5
+        )
+        login_log = logging.handlers.RotatingFileHandler(
+            logs["logins"], maxBytes=10485760, backupCount=5
         )
-        login_log = logging.handlers.RotatingFileHandler(logs["logins"], maxBytes=10000)
         registration_log = logging.handlers.RotatingFileHandler(
-            logs["registrations"], maxBytes=10000
+            logs["registrations"], maxBytes=10485760, backupCount=5
         )
 
         logger_submissions.addHandler(submission_log)

{"golden_diff": "diff --git a/CTFd/utils/initialization/__init__.py b/CTFd/utils/initialization/__init__.py\n--- a/CTFd/utils/initialization/__init__.py\n+++ b/CTFd/utils/initialization/__init__.py\n@@ -102,11 +102,13 @@\n                 open(log, \"a\").close()\n \n         submission_log = logging.handlers.RotatingFileHandler(\n-            logs[\"submissions\"], maxBytes=10000\n+            logs[\"submissions\"], maxBytes=10485760, backupCount=5\n+        )\n+        login_log = logging.handlers.RotatingFileHandler(\n+            logs[\"logins\"], maxBytes=10485760, backupCount=5\n         )\n-        login_log = logging.handlers.RotatingFileHandler(logs[\"logins\"], maxBytes=10000)\n         registration_log = logging.handlers.RotatingFileHandler(\n-            logs[\"registrations\"], maxBytes=10000\n+            logs[\"registrations\"], maxBytes=10485760, backupCount=5\n         )\n \n         logger_submissions.addHandler(submission_log)\n", "issue": "log rotation does not works\nIn the file https://github.com/CTFd/CTFd/blob/master/CTFd/utils/initialization/__init__.py#L107\r\nthe log handlers `logging.handlers.RotatingFileHandler` are not created with the right parameters (see [RotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.RotatingFileHandler)) because _if either of maxBytes or backupCount is zero, rollover never occurs_ (`backupCount` parameter is missing)\n", "before_files": [{"content": "import datetime\nimport logging\nimport os\nimport sys\n\nfrom flask import abort, redirect, render_template, request, session, url_for\nfrom sqlalchemy.exc import IntegrityError, InvalidRequestError\nfrom werkzeug.wsgi import DispatcherMiddleware\n\nfrom CTFd.exceptions import UserNotFoundException, UserTokenExpiredException\nfrom CTFd.models import Tracking, db\nfrom CTFd.utils import config, get_config, markdown\nfrom CTFd.utils.config import (\n    can_send_mail,\n    ctf_logo,\n    ctf_name,\n    ctf_theme,\n    integrations,\n    is_setup,\n)\nfrom CTFd.utils.config.pages import get_pages\nfrom CTFd.utils.config.visibility import (\n    accounts_visible,\n    challenges_visible,\n    registration_visible,\n    scores_visible,\n)\nfrom CTFd.utils.countries import get_countries, lookup_country_code\nfrom CTFd.utils.dates import isoformat, unix_time, unix_time_millis\nfrom CTFd.utils.events import EventManager, RedisEventManager\nfrom CTFd.utils.modes import generate_account_url, get_mode_as_word\nfrom CTFd.utils.plugins import (\n    get_configurable_plugins,\n    get_registered_admin_scripts,\n    get_registered_admin_stylesheets,\n    get_registered_scripts,\n    get_registered_stylesheets,\n)\nfrom CTFd.utils.security.auth import login_user, logout_user, lookup_user_token\nfrom CTFd.utils.security.csrf import generate_nonce\nfrom CTFd.utils.user import authed, get_current_team, get_current_user, get_ip\n\n\ndef init_template_filters(app):\n    app.jinja_env.filters[\"markdown\"] = markdown\n    app.jinja_env.filters[\"unix_time\"] = unix_time\n    app.jinja_env.filters[\"unix_time_millis\"] = unix_time_millis\n    app.jinja_env.filters[\"isoformat\"] = isoformat\n\n\ndef init_template_globals(app):\n    app.jinja_env.globals.update(config=config)\n    app.jinja_env.globals.update(get_pages=get_pages)\n    app.jinja_env.globals.update(can_send_mail=can_send_mail)\n    app.jinja_env.globals.update(get_ctf_name=ctf_name)\n    app.jinja_env.globals.update(get_ctf_logo=ctf_logo)\n    app.jinja_env.globals.update(get_ctf_theme=ctf_theme)\n    app.jinja_env.globals.update(get_configurable_plugins=get_configurable_plugins)\n    app.jinja_env.globals.update(get_registered_scripts=get_registered_scripts)\n    app.jinja_env.globals.update(get_registered_stylesheets=get_registered_stylesheets)\n    app.jinja_env.globals.update(\n        get_registered_admin_scripts=get_registered_admin_scripts\n    )\n    app.jinja_env.globals.update(\n        get_registered_admin_stylesheets=get_registered_admin_stylesheets\n    )\n    app.jinja_env.globals.update(get_config=get_config)\n    app.jinja_env.globals.update(generate_account_url=generate_account_url)\n    app.jinja_env.globals.update(get_countries=get_countries)\n    app.jinja_env.globals.update(lookup_country_code=lookup_country_code)\n    app.jinja_env.globals.update(accounts_visible=accounts_visible)\n    app.jinja_env.globals.update(challenges_visible=challenges_visible)\n    app.jinja_env.globals.update(registration_visible=registration_visible)\n    app.jinja_env.globals.update(scores_visible=scores_visible)\n    app.jinja_env.globals.update(get_mode_as_word=get_mode_as_word)\n    app.jinja_env.globals.update(integrations=integrations)\n    app.jinja_env.globals.update(authed=authed)\n\n\ndef init_logs(app):\n    logger_submissions = logging.getLogger(\"submissions\")\n    logger_logins = logging.getLogger(\"logins\")\n    logger_registrations = logging.getLogger(\"registrations\")\n\n    logger_submissions.setLevel(logging.INFO)\n    logger_logins.setLevel(logging.INFO)\n    logger_registrations.setLevel(logging.INFO)\n\n    log_dir = app.config[\"LOG_FOLDER\"]\n    if not os.path.exists(log_dir):\n        os.makedirs(log_dir)\n\n    logs = {\n        \"submissions\": os.path.join(log_dir, \"submissions.log\"),\n        \"logins\": os.path.join(log_dir, \"logins.log\"),\n        \"registrations\": os.path.join(log_dir, \"registrations.log\"),\n    }\n\n    try:\n        for log in logs.values():\n            if not os.path.exists(log):\n                open(log, \"a\").close()\n\n        submission_log = logging.handlers.RotatingFileHandler(\n            logs[\"submissions\"], maxBytes=10000\n        )\n        login_log = logging.handlers.RotatingFileHandler(logs[\"logins\"], maxBytes=10000)\n        registration_log = logging.handlers.RotatingFileHandler(\n            logs[\"registrations\"], maxBytes=10000\n        )\n\n        logger_submissions.addHandler(submission_log)\n        logger_logins.addHandler(login_log)\n        logger_registrations.addHandler(registration_log)\n    except IOError:\n        pass\n\n    stdout = logging.StreamHandler(stream=sys.stdout)\n\n    logger_submissions.addHandler(stdout)\n    logger_logins.addHandler(stdout)\n    logger_registrations.addHandler(stdout)\n\n    logger_submissions.propagate = 0\n    logger_logins.propagate = 0\n    logger_registrations.propagate = 0\n\n\ndef init_events(app):\n    if app.config.get(\"CACHE_TYPE\") == \"redis\":\n        app.events_manager = RedisEventManager()\n    elif app.config.get(\"CACHE_TYPE\") == \"filesystem\":\n        app.events_manager = EventManager()\n    else:\n        app.events_manager = EventManager()\n\n\ndef init_request_processors(app):\n    @app.context_processor\n    def inject_user():\n        if session:\n            return dict(session)\n        return dict()\n\n    @app.url_defaults\n    def inject_theme(endpoint, values):\n        if \"theme\" not in values and app.url_map.is_endpoint_expecting(\n            endpoint, \"theme\"\n        ):\n            values[\"theme\"] = ctf_theme()\n\n    @app.before_request\n    def needs_setup():\n        if is_setup() is False:\n            if request.endpoint in (\n                \"views.setup\",\n                \"views.integrations\",\n                \"views.themes\",\n            ):\n                return\n            else:\n                return redirect(url_for(\"views.setup\"))\n\n    @app.before_request\n    def tracker():\n        if request.endpoint == \"views.themes\":\n            return\n\n        if authed():\n            track = Tracking.query.filter_by(ip=get_ip(), user_id=session[\"id\"]).first()\n            if not track:\n                visit = Tracking(ip=get_ip(), user_id=session[\"id\"])\n                db.session.add(visit)\n            else:\n                track.date = datetime.datetime.utcnow()\n\n            try:\n                db.session.commit()\n            except (InvalidRequestError, IntegrityError):\n                db.session.rollback()\n                logout_user()\n\n            if authed():\n                user = get_current_user()\n                team = get_current_team()\n\n                if request.path.startswith(\"/themes\") is False:\n                    if user and user.banned:\n                        return (\n                            render_template(\n                                \"errors/403.html\",\n                                error=\"You have been banned from this CTF\",\n                            ),\n                            403,\n                        )\n\n                    if team and team.banned:\n                        return (\n                            render_template(\n                                \"errors/403.html\",\n                                error=\"Your team has been banned from this CTF\",\n                            ),\n                            403,\n                        )\n\n            db.session.close()\n\n    @app.before_request\n    def tokens():\n        token = request.headers.get(\"Authorization\")\n        if token and request.content_type == \"application/json\":\n            try:\n                token_type, token = token.split(\" \", 1)\n                user = lookup_user_token(token)\n            except UserNotFoundException:\n                abort(401)\n            except UserTokenExpiredException:\n                abort(401)\n            except Exception:\n                abort(401)\n            else:\n                login_user(user)\n\n    @app.before_request\n    def csrf():\n        try:\n            func = app.view_functions[request.endpoint]\n        except KeyError:\n            abort(404)\n        if hasattr(func, \"_bypass_csrf\"):\n            return\n        if request.headers.get(\"Authorization\"):\n            return\n        if not session.get(\"nonce\"):\n            session[\"nonce\"] = generate_nonce()\n        if request.method not in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            if request.content_type == \"application/json\":\n                if session[\"nonce\"] != request.headers.get(\"CSRF-Token\"):\n                    abort(403)\n            if request.content_type != \"application/json\":\n                if session[\"nonce\"] != request.form.get(\"nonce\"):\n                    abort(403)\n\n    application_root = app.config.get(\"APPLICATION_ROOT\")\n    if application_root != \"/\":\n\n        @app.before_request\n        def force_subdirectory_redirect():\n            if request.path.startswith(application_root) is False:\n                return redirect(\n                    application_root + request.script_root + request.full_path\n                )\n\n        app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {application_root: app})\n", "path": "CTFd/utils/initialization/__init__.py"}], "after_files": [{"content": "import datetime\nimport logging\nimport os\nimport sys\n\nfrom flask import abort, redirect, render_template, request, session, url_for\nfrom sqlalchemy.exc import IntegrityError, InvalidRequestError\nfrom werkzeug.wsgi import DispatcherMiddleware\n\nfrom CTFd.exceptions import UserNotFoundException, UserTokenExpiredException\nfrom CTFd.models import Tracking, db\nfrom CTFd.utils import config, get_config, markdown\nfrom CTFd.utils.config import (\n    can_send_mail,\n    ctf_logo,\n    ctf_name,\n    ctf_theme,\n    integrations,\n    is_setup,\n)\nfrom CTFd.utils.config.pages import get_pages\nfrom CTFd.utils.config.visibility import (\n    accounts_visible,\n    challenges_visible,\n    registration_visible,\n    scores_visible,\n)\nfrom CTFd.utils.countries import get_countries, lookup_country_code\nfrom CTFd.utils.dates import isoformat, unix_time, unix_time_millis\nfrom CTFd.utils.events import EventManager, RedisEventManager\nfrom CTFd.utils.modes import generate_account_url, get_mode_as_word\nfrom CTFd.utils.plugins import (\n    get_configurable_plugins,\n    get_registered_admin_scripts,\n    get_registered_admin_stylesheets,\n    get_registered_scripts,\n    get_registered_stylesheets,\n)\nfrom CTFd.utils.security.auth import login_user, logout_user, lookup_user_token\nfrom CTFd.utils.security.csrf import generate_nonce\nfrom CTFd.utils.user import authed, get_current_team, get_current_user, get_ip\n\n\ndef init_template_filters(app):\n    app.jinja_env.filters[\"markdown\"] = markdown\n    app.jinja_env.filters[\"unix_time\"] = unix_time\n    app.jinja_env.filters[\"unix_time_millis\"] = unix_time_millis\n    app.jinja_env.filters[\"isoformat\"] = isoformat\n\n\ndef init_template_globals(app):\n    app.jinja_env.globals.update(config=config)\n    app.jinja_env.globals.update(get_pages=get_pages)\n    app.jinja_env.globals.update(can_send_mail=can_send_mail)\n    app.jinja_env.globals.update(get_ctf_name=ctf_name)\n    app.jinja_env.globals.update(get_ctf_logo=ctf_logo)\n    app.jinja_env.globals.update(get_ctf_theme=ctf_theme)\n    app.jinja_env.globals.update(get_configurable_plugins=get_configurable_plugins)\n    app.jinja_env.globals.update(get_registered_scripts=get_registered_scripts)\n    app.jinja_env.globals.update(get_registered_stylesheets=get_registered_stylesheets)\n    app.jinja_env.globals.update(\n        get_registered_admin_scripts=get_registered_admin_scripts\n    )\n    app.jinja_env.globals.update(\n        get_registered_admin_stylesheets=get_registered_admin_stylesheets\n    )\n    app.jinja_env.globals.update(get_config=get_config)\n    app.jinja_env.globals.update(generate_account_url=generate_account_url)\n    app.jinja_env.globals.update(get_countries=get_countries)\n    app.jinja_env.globals.update(lookup_country_code=lookup_country_code)\n    app.jinja_env.globals.update(accounts_visible=accounts_visible)\n    app.jinja_env.globals.update(challenges_visible=challenges_visible)\n    app.jinja_env.globals.update(registration_visible=registration_visible)\n    app.jinja_env.globals.update(scores_visible=scores_visible)\n    app.jinja_env.globals.update(get_mode_as_word=get_mode_as_word)\n    app.jinja_env.globals.update(integrations=integrations)\n    app.jinja_env.globals.update(authed=authed)\n\n\ndef init_logs(app):\n    logger_submissions = logging.getLogger(\"submissions\")\n    logger_logins = logging.getLogger(\"logins\")\n    logger_registrations = logging.getLogger(\"registrations\")\n\n    logger_submissions.setLevel(logging.INFO)\n    logger_logins.setLevel(logging.INFO)\n    logger_registrations.setLevel(logging.INFO)\n\n    log_dir = app.config[\"LOG_FOLDER\"]\n    if not os.path.exists(log_dir):\n        os.makedirs(log_dir)\n\n    logs = {\n        \"submissions\": os.path.join(log_dir, \"submissions.log\"),\n        \"logins\": os.path.join(log_dir, \"logins.log\"),\n        \"registrations\": os.path.join(log_dir, \"registrations.log\"),\n    }\n\n    try:\n        for log in logs.values():\n            if not os.path.exists(log):\n                open(log, \"a\").close()\n\n        submission_log = logging.handlers.RotatingFileHandler(\n            logs[\"submissions\"], maxBytes=10485760, backupCount=5\n        )\n        login_log = logging.handlers.RotatingFileHandler(\n            logs[\"logins\"], maxBytes=10485760, backupCount=5\n        )\n        registration_log = logging.handlers.RotatingFileHandler(\n            logs[\"registrations\"], maxBytes=10485760, backupCount=5\n        )\n\n        logger_submissions.addHandler(submission_log)\n        logger_logins.addHandler(login_log)\n        logger_registrations.addHandler(registration_log)\n    except IOError:\n        pass\n\n    stdout = logging.StreamHandler(stream=sys.stdout)\n\n    logger_submissions.addHandler(stdout)\n    logger_logins.addHandler(stdout)\n    logger_registrations.addHandler(stdout)\n\n    logger_submissions.propagate = 0\n    logger_logins.propagate = 0\n    logger_registrations.propagate = 0\n\n\ndef init_events(app):\n    if app.config.get(\"CACHE_TYPE\") == \"redis\":\n        app.events_manager = RedisEventManager()\n    elif app.config.get(\"CACHE_TYPE\") == \"filesystem\":\n        app.events_manager = EventManager()\n    else:\n        app.events_manager = EventManager()\n\n\ndef init_request_processors(app):\n    @app.context_processor\n    def inject_user():\n        if session:\n            return dict(session)\n        return dict()\n\n    @app.url_defaults\n    def inject_theme(endpoint, values):\n        if \"theme\" not in values and app.url_map.is_endpoint_expecting(\n            endpoint, \"theme\"\n        ):\n            values[\"theme\"] = ctf_theme()\n\n    @app.before_request\n    def needs_setup():\n        if is_setup() is False:\n            if request.endpoint in (\n                \"views.setup\",\n                \"views.integrations\",\n                \"views.themes\",\n            ):\n                return\n            else:\n                return redirect(url_for(\"views.setup\"))\n\n    @app.before_request\n    def tracker():\n        if request.endpoint == \"views.themes\":\n            return\n\n        if authed():\n            track = Tracking.query.filter_by(ip=get_ip(), user_id=session[\"id\"]).first()\n            if not track:\n                visit = Tracking(ip=get_ip(), user_id=session[\"id\"])\n                db.session.add(visit)\n            else:\n                track.date = datetime.datetime.utcnow()\n\n            try:\n                db.session.commit()\n            except (InvalidRequestError, IntegrityError):\n                db.session.rollback()\n                logout_user()\n\n            if authed():\n                user = get_current_user()\n                team = get_current_team()\n\n                if request.path.startswith(\"/themes\") is False:\n                    if user and user.banned:\n                        return (\n                            render_template(\n                                \"errors/403.html\",\n                                error=\"You have been banned from this CTF\",\n                            ),\n                            403,\n                        )\n\n                    if team and team.banned:\n                        return (\n                            render_template(\n                                \"errors/403.html\",\n                                error=\"Your team has been banned from this CTF\",\n                            ),\n                            403,\n                        )\n\n            db.session.close()\n\n    @app.before_request\n    def tokens():\n        token = request.headers.get(\"Authorization\")\n        if token and request.content_type == \"application/json\":\n            try:\n                token_type, token = token.split(\" \", 1)\n                user = lookup_user_token(token)\n            except UserNotFoundException:\n                abort(401)\n            except UserTokenExpiredException:\n                abort(401)\n            except Exception:\n                abort(401)\n            else:\n                login_user(user)\n\n    @app.before_request\n    def csrf():\n        try:\n            func = app.view_functions[request.endpoint]\n        except KeyError:\n            abort(404)\n        if hasattr(func, \"_bypass_csrf\"):\n            return\n        if request.headers.get(\"Authorization\"):\n            return\n        if not session.get(\"nonce\"):\n            session[\"nonce\"] = generate_nonce()\n        if request.method not in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            if request.content_type == \"application/json\":\n                if session[\"nonce\"] != request.headers.get(\"CSRF-Token\"):\n                    abort(403)\n            if request.content_type != \"application/json\":\n                if session[\"nonce\"] != request.form.get(\"nonce\"):\n                    abort(403)\n\n    application_root = app.config.get(\"APPLICATION_ROOT\")\n    if application_root != \"/\":\n\n        @app.before_request\n        def force_subdirectory_redirect():\n            if request.path.startswith(application_root) is False:\n                return redirect(\n                    application_root + request.script_root + request.full_path\n                )\n\n        app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {application_root: app})\n", "path": "CTFd/utils/initialization/__init__.py"}]}