We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
CTFd permission error by using custom Vagrant
**Environment**:

  - CTFd Version/Commit:master
  - Operating System: VERSION="16.04.6 LTS (Xenial Xerus)"  (vagrant machine)


**What happened?**
Permission denied 
**How to reproduce your issue**
Create the following Vagrantfile
```ruby
 # Defines our Vagrant environment
 #
 # -*- mode: ruby -*-
 # vi: set ft=ruby :
 
 Vagrant.configure("2") do |config|
 
   DOCKER_REBUILD = true
   DOCKER_DESTROY = false
   config.vm.define :dockermachine do |config|
   config.vm.box = "ubuntu/xenial64"
   config.vm.hostname = "dsp"
   config.vm.provision :docker
   config.vm.provision :docker_compose
 
   # Run docker compose networks
   config.vm.synced_folder ".", "/vagrant", disabled: true
   config.vm.synced_folder "./provision/", "/provision", disabled: false
   config.vm.network "forwarded_port", guest: 8000, host: 8000
   config.ssh.keep_alive = true
   config.vm.provider "virtualbox" do |vb|
       vb.gui = false
       vb.default_nic_type = nil
       vb.memory = "2048"
     end
   end
```
Install docker plugin prerequisite: 
```
vagrant plugin install vagrant-docker-compose
```
Start machine and manually set ctfd
```bash
vagrant up 
vagrant ssh
git clone https://github.com/CTFd/CTFd.git
cd CTFd
#add secret key in docker-compose
    environment:
      - SECRET_KEY=password  
docker-compose up
```
- Issue no.1: 
The first issue is about log directory permission; the user created in Dockerfile (uid=1001) is different than the current user id(1000) . 
You can solve it by changing the userid in Dockerfile and by sending docker-compose build and docker-compose up: 
```
sed -i "s/1001/$UID/g" Dockerfile
sudo chown -hR vagrant:vagrant .data
docker-compose up --build
```  
- Issue 2:  
After these steps, the application runs, but it is not possible to go over the setup phase: 
<img width="617" alt="Schermata 2019-04-20 alle 12 58 05" src="https://user-images.githubusercontent.com/18548727/56456394-f71c7a80-636b-11e9-9c82-8d8e0319fb09.png">

<img width="1008" alt="Schermata 2019-04-20 alle 12 59 00" src="https://user-images.githubusercontent.com/18548727/56456401-216e3800-636c-11e9-876e-46d05470bce2.png">


I am not able to overcome this problem. Could you give me any hint about it? 
Thanks very much


**Any associated stack traces or error logs**
Permission denied (issue no.1): 
```
ctfd_1   | IOError: [Errno 13] Permission denied: '/var/log/CTFd/logins.log'
ctfd_ctfd_1 exited with code 1
ctfd_1   | Waiting for db: to be ready
ctfd_1   | .db is ready
ctfd_1   | Traceback (most recent call last):
ctfd_1   |   File "manage.py", line 8, in <module>
ctfd_1   |     app = create_app()
ctfd_1   |   File "/opt/CTFd/CTFd/__init__.py", line 225, in create_app
ctfd_1   |     init_logs(app)
ctfd_1   |   File "/opt/CTFd/CTFd/utils/initialization/__init__.py", line 90, in init_logs
ctfd_1   |     open(log, 'a').close()
ctfd_1   | IOError: [Errno 13] Permission denied: '/var/log/CTFd/logins.log'
ctfd_1   | Waiting for db: to be ready
ctfd_1   | db is ready
ctfd_1   | Traceback (most recent call last):
ctfd_1   |   File "manage.py", line 8, in <module>
ctfd_1   |     app = create_app()
ctfd_1   |   File "/opt/CTFd/CTFd/__init__.py", line 225, in create_app
ctfd_1   |     init_logs(app)
ctfd_1   |   File "/opt/CTFd/CTFd/utils/initialization/__init__.py", line 90, in init_logs
ctfd_1   |     open(log, 'a').close()
ctfd_1   | IOError: [Errno 13] Permission denied: '/var/log/CTFd/logins.log'
ctfd_1   | Waiting for db: to be ready
ctfd_1   | db is ready
ctfd_1   | Traceback (most recent call last):
ctfd_1   |   File "manage.py", line 8, in <module>
ctfd_1   |     app = create_app()
ctfd_1   |   File "/opt/CTFd/CTFd/__init__.py", line 225, in create_app
ctfd_1   |     init_logs(app)
ctfd_1   |   File "/opt/CTFd/CTFd/utils/initialization/__init__.py", line 90, in init_logs
ctfd_1   |     open(log, 'a').close()
ctfd_1   | IOError: [Errno 13] Permission denied: '/var/log/CTFd/logins.log'
```

--- 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 from flask import request, session, redirect, url_for, abort, render_template
2 from werkzeug.wsgi import DispatcherMiddleware
3 from CTFd.models import db, Tracking
4 
5 from CTFd.utils import markdown, get_config
6 from CTFd.utils.dates import unix_time_millis, unix_time, isoformat
7 
8 from CTFd.utils import config
9 from CTFd.utils.config import can_send_mail, ctf_logo, ctf_name, ctf_theme
10 from CTFd.utils.config.pages import get_pages
11 from CTFd.utils.events import EventManager, RedisEventManager
12 from CTFd.utils.plugins import (
13     get_registered_stylesheets,
14     get_registered_scripts,
15     get_configurable_plugins,
16     get_registered_admin_scripts,
17     get_registered_admin_stylesheets
18 )
19 
20 from CTFd.utils.countries import get_countries, lookup_country_code
21 from CTFd.utils.user import authed, get_ip, get_current_user, get_current_team
22 from CTFd.utils.modes import generate_account_url
23 from CTFd.utils.config import is_setup
24 from CTFd.utils.security.csrf import generate_nonce
25 
26 from CTFd.utils.config.visibility import (
27     accounts_visible,
28     challenges_visible,
29     registration_visible,
30     scores_visible
31 )
32 
33 from sqlalchemy.exc import InvalidRequestError, IntegrityError
34 
35 import datetime
36 import logging
37 import os
38 
39 
40 def init_template_filters(app):
41     app.jinja_env.filters['markdown'] = markdown
42     app.jinja_env.filters['unix_time'] = unix_time
43     app.jinja_env.filters['unix_time_millis'] = unix_time_millis
44     app.jinja_env.filters['isoformat'] = isoformat
45 
46 
47 def init_template_globals(app):
48     app.jinja_env.globals.update(config=config)
49     app.jinja_env.globals.update(get_pages=get_pages)
50     app.jinja_env.globals.update(can_send_mail=can_send_mail)
51     app.jinja_env.globals.update(get_ctf_name=ctf_name)
52     app.jinja_env.globals.update(get_ctf_logo=ctf_logo)
53     app.jinja_env.globals.update(get_ctf_theme=ctf_theme)
54     app.jinja_env.globals.update(get_configurable_plugins=get_configurable_plugins)
55     app.jinja_env.globals.update(get_registered_scripts=get_registered_scripts)
56     app.jinja_env.globals.update(get_registered_stylesheets=get_registered_stylesheets)
57     app.jinja_env.globals.update(get_registered_admin_scripts=get_registered_admin_scripts)
58     app.jinja_env.globals.update(get_registered_admin_stylesheets=get_registered_admin_stylesheets)
59     app.jinja_env.globals.update(get_config=get_config)
60     app.jinja_env.globals.update(generate_account_url=generate_account_url)
61     app.jinja_env.globals.update(get_countries=get_countries)
62     app.jinja_env.globals.update(lookup_country_code=lookup_country_code)
63     app.jinja_env.globals.update(accounts_visible=accounts_visible)
64     app.jinja_env.globals.update(challenges_visible=challenges_visible)
65     app.jinja_env.globals.update(registration_visible=registration_visible)
66     app.jinja_env.globals.update(scores_visible=scores_visible)
67 
68 
69 def init_logs(app):
70     logger_submissions = logging.getLogger('submissions')
71     logger_logins = logging.getLogger('logins')
72     logger_registrations = logging.getLogger('registrations')
73 
74     logger_submissions.setLevel(logging.INFO)
75     logger_logins.setLevel(logging.INFO)
76     logger_registrations.setLevel(logging.INFO)
77 
78     log_dir = app.config['LOG_FOLDER']
79     if not os.path.exists(log_dir):
80         os.makedirs(log_dir)
81 
82     logs = {
83         'submissions': os.path.join(log_dir, 'submissions.log'),
84         'logins': os.path.join(log_dir, 'logins.log'),
85         'registrations': os.path.join(log_dir, 'registrations.log')
86     }
87 
88     for log in logs.values():
89         if not os.path.exists(log):
90             open(log, 'a').close()
91 
92     submission_log = logging.handlers.RotatingFileHandler(logs['submissions'], maxBytes=10000)
93     login_log = logging.handlers.RotatingFileHandler(logs['logins'], maxBytes=10000)
94     registration_log = logging.handlers.RotatingFileHandler(logs['registrations'], maxBytes=10000)
95 
96     logger_submissions.addHandler(
97         submission_log
98     )
99     logger_logins.addHandler(
100         login_log
101     )
102     logger_registrations.addHandler(
103         registration_log
104     )
105 
106     logger_submissions.propagate = 0
107     logger_logins.propagate = 0
108     logger_registrations.propagate = 0
109 
110 
111 def init_events(app):
112     if app.config.get('CACHE_TYPE') == 'redis':
113         app.events_manager = RedisEventManager()
114     elif app.config.get('CACHE_TYPE') == 'filesystem':
115         app.events_manager = EventManager()
116     else:
117         app.events_manager = EventManager()
118 
119 
120 def init_request_processors(app):
121     @app.context_processor
122     def inject_user():
123         if session:
124             return dict(session)
125         return dict()
126 
127     @app.url_defaults
128     def inject_theme(endpoint, values):
129         if 'theme' not in values and app.url_map.is_endpoint_expecting(endpoint, 'theme'):
130             values['theme'] = ctf_theme()
131 
132     @app.before_request
133     def needs_setup():
134         if request.path == url_for('views.setup') or request.path.startswith('/themes'):
135             return
136         if not is_setup():
137             return redirect(url_for('views.setup'))
138 
139     @app.before_request
140     def tracker():
141         # TODO: This function shouldn't cause a DB hit for lookups if possible
142         if authed():
143             track = Tracking.query.filter_by(ip=get_ip(), user_id=session['id']).first()
144             if not track:
145                 visit = Tracking(ip=get_ip(), user_id=session['id'])
146                 db.session.add(visit)
147             else:
148                 track.date = datetime.datetime.utcnow()
149 
150             try:
151                 db.session.commit()
152             except (InvalidRequestError, IntegrityError) as e:
153                 print(e.message)
154                 db.session.rollback()
155                 session.clear()
156 
157             if authed():
158                 user = get_current_user()
159                 team = get_current_team()
160 
161                 if request.path.startswith('/themes') is False:
162                     if user and user.banned:
163                         return render_template('errors/403.html', error='You have been banned from this CTF'), 403
164 
165                     if team and team.banned:
166                         return render_template('errors/403.html', error='Your team has been banned from this CTF'), 403
167 
168             db.session.close()
169 
170     @app.before_request
171     def csrf():
172         try:
173             func = app.view_functions[request.endpoint]
174         except KeyError:
175             abort(404)
176         if hasattr(func, '_bypass_csrf'):
177             return
178         if not session.get('nonce'):
179             session['nonce'] = generate_nonce()
180         if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
181             if request.content_type == 'application/json':
182                 if session['nonce'] != request.headers.get('CSRF-Token'):
183                     abort(403)
184             if request.content_type != 'application/json':
185                 if session['nonce'] != request.form.get('nonce'):
186                     abort(403)
187 
188     application_root = app.config.get('APPLICATION_ROOT')
189     if application_root != '/':
190         @app.before_request
191         def force_subdirectory_redirect():
192             if request.path.startswith(application_root) is False:
193                 return redirect(application_root + request.script_root + request.full_path)
194 
195         app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {
196             application_root: app,
197         })
198
```
--- 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
@@ -35,6 +35,7 @@
 import datetime
 import logging
 import os
+import sys
 
 
 def init_template_filters(app):
@@ -85,22 +86,37 @@
         'registrations': os.path.join(log_dir, 'registrations.log')
     }
 
-    for log in logs.values():
-        if not os.path.exists(log):
-            open(log, 'a').close()
-
-    submission_log = logging.handlers.RotatingFileHandler(logs['submissions'], maxBytes=10000)
-    login_log = logging.handlers.RotatingFileHandler(logs['logins'], maxBytes=10000)
-    registration_log = logging.handlers.RotatingFileHandler(logs['registrations'], maxBytes=10000)
+    try:
+        for log in logs.values():
+            if not os.path.exists(log):
+                open(log, 'a').close()
+
+        submission_log = logging.handlers.RotatingFileHandler(logs['submissions'], maxBytes=10000)
+        login_log = logging.handlers.RotatingFileHandler(logs['logins'], maxBytes=10000)
+        registration_log = logging.handlers.RotatingFileHandler(logs['registrations'], maxBytes=10000)
+
+        logger_submissions.addHandler(
+            submission_log
+        )
+        logger_logins.addHandler(
+            login_log
+        )
+        logger_registrations.addHandler(
+            registration_log
+        )
+    except IOError:
+        pass
+
+    stdout = logging.StreamHandler(stream=sys.stdout)
 
     logger_submissions.addHandler(
-        submission_log
+        stdout
     )
     logger_logins.addHandler(
-        login_log
+        stdout
     )
     logger_registrations.addHandler(
-        registration_log
+        stdout
     )
 
     logger_submissions.propagate = 0

{"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@@ -35,6 +35,7 @@\n import datetime\n import logging\n import os\n+import sys\n \n \n def init_template_filters(app):\n@@ -85,22 +86,37 @@\n         'registrations': os.path.join(log_dir, 'registrations.log')\n     }\n \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(logs['submissions'], maxBytes=10000)\n-    login_log = logging.handlers.RotatingFileHandler(logs['logins'], maxBytes=10000)\n-    registration_log = logging.handlers.RotatingFileHandler(logs['registrations'], maxBytes=10000)\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(logs['submissions'], maxBytes=10000)\n+        login_log = logging.handlers.RotatingFileHandler(logs['logins'], maxBytes=10000)\n+        registration_log = logging.handlers.RotatingFileHandler(logs['registrations'], maxBytes=10000)\n+\n+        logger_submissions.addHandler(\n+            submission_log\n+        )\n+        logger_logins.addHandler(\n+            login_log\n+        )\n+        logger_registrations.addHandler(\n+            registration_log\n+        )\n+    except IOError:\n+        pass\n+\n+    stdout = logging.StreamHandler(stream=sys.stdout)\n \n     logger_submissions.addHandler(\n-        submission_log\n+        stdout\n     )\n     logger_logins.addHandler(\n-        login_log\n+        stdout\n     )\n     logger_registrations.addHandler(\n-        registration_log\n+        stdout\n     )\n \n     logger_submissions.propagate = 0\n", "issue": "CTFd permission error by using custom Vagrant\n**Environment**:\r\n\r\n  - CTFd Version/Commit:master\r\n  - Operating System: VERSION=\"16.04.6 LTS (Xenial Xerus)\"  (vagrant machine)\r\n\r\n\r\n**What happened?**\r\nPermission denied \r\n**How to reproduce your issue**\r\nCreate the following Vagrantfile\r\n```ruby\r\n # Defines our Vagrant environment\r\n #\r\n # -*- mode: ruby -*-\r\n # vi: set ft=ruby :\r\n \r\n Vagrant.configure(\"2\") do |config|\r\n \r\n   DOCKER_REBUILD = true\r\n   DOCKER_DESTROY = false\r\n   config.vm.define :dockermachine do |config|\r\n   config.vm.box = \"ubuntu/xenial64\"\r\n   config.vm.hostname = \"dsp\"\r\n   config.vm.provision :docker\r\n   config.vm.provision :docker_compose\r\n \r\n   # Run docker compose networks\r\n   config.vm.synced_folder \".\", \"/vagrant\", disabled: true\r\n   config.vm.synced_folder \"./provision/\", \"/provision\", disabled: false\r\n   config.vm.network \"forwarded_port\", guest: 8000, host: 8000\r\n   config.ssh.keep_alive = true\r\n   config.vm.provider \"virtualbox\" do |vb|\r\n       vb.gui = false\r\n       vb.default_nic_type = nil\r\n       vb.memory = \"2048\"\r\n     end\r\n   end\r\n```\r\nInstall docker plugin prerequisite: \r\n```\r\nvagrant plugin install vagrant-docker-compose\r\n```\r\nStart machine and manually set ctfd\r\n```bash\r\nvagrant up \r\nvagrant ssh\r\ngit clone https://github.com/CTFd/CTFd.git\r\ncd CTFd\r\n#add secret key in docker-compose\r\n    environment:\r\n      - SECRET_KEY=password  \r\ndocker-compose up\r\n```\r\n- Issue no.1: \r\nThe first issue is about log directory permission; the user created in Dockerfile (uid=1001) is different than the current user id(1000) . \r\nYou can solve it by changing the userid in Dockerfile and by sending docker-compose build and docker-compose up: \r\n```\r\nsed -i \"s/1001/$UID/g\" Dockerfile\r\nsudo chown -hR vagrant:vagrant .data\r\ndocker-compose up --build\r\n```  \r\n- Issue 2:  \r\nAfter these steps, the application runs, but it is not possible to go over the setup phase: \r\n<img width=\"617\" alt=\"Schermata 2019-04-20 alle 12 58 05\" src=\"https://user-images.githubusercontent.com/18548727/56456394-f71c7a80-636b-11e9-9c82-8d8e0319fb09.png\">\r\n\r\n<img width=\"1008\" alt=\"Schermata 2019-04-20 alle 12 59 00\" src=\"https://user-images.githubusercontent.com/18548727/56456401-216e3800-636c-11e9-876e-46d05470bce2.png\">\r\n\r\n\r\nI am not able to overcome this problem. Could you give me any hint about it? \r\nThanks very much\r\n\r\n\r\n**Any associated stack traces or error logs**\r\nPermission denied (issue no.1): \r\n```\r\nctfd_1   | IOError: [Errno 13] Permission denied: '/var/log/CTFd/logins.log'\r\nctfd_ctfd_1 exited with code 1\r\nctfd_1   | Waiting for db: to be ready\r\nctfd_1   | .db is ready\r\nctfd_1   | Traceback (most recent call last):\r\nctfd_1   |   File \"manage.py\", line 8, in <module>\r\nctfd_1   |     app = create_app()\r\nctfd_1   |   File \"/opt/CTFd/CTFd/__init__.py\", line 225, in create_app\r\nctfd_1   |     init_logs(app)\r\nctfd_1   |   File \"/opt/CTFd/CTFd/utils/initialization/__init__.py\", line 90, in init_logs\r\nctfd_1   |     open(log, 'a').close()\r\nctfd_1   | IOError: [Errno 13] Permission denied: '/var/log/CTFd/logins.log'\r\nctfd_1   | Waiting for db: to be ready\r\nctfd_1   | db is ready\r\nctfd_1   | Traceback (most recent call last):\r\nctfd_1   |   File \"manage.py\", line 8, in <module>\r\nctfd_1   |     app = create_app()\r\nctfd_1   |   File \"/opt/CTFd/CTFd/__init__.py\", line 225, in create_app\r\nctfd_1   |     init_logs(app)\r\nctfd_1   |   File \"/opt/CTFd/CTFd/utils/initialization/__init__.py\", line 90, in init_logs\r\nctfd_1   |     open(log, 'a').close()\r\nctfd_1   | IOError: [Errno 13] Permission denied: '/var/log/CTFd/logins.log'\r\nctfd_1   | Waiting for db: to be ready\r\nctfd_1   | db is ready\r\nctfd_1   | Traceback (most recent call last):\r\nctfd_1   |   File \"manage.py\", line 8, in <module>\r\nctfd_1   |     app = create_app()\r\nctfd_1   |   File \"/opt/CTFd/CTFd/__init__.py\", line 225, in create_app\r\nctfd_1   |     init_logs(app)\r\nctfd_1   |   File \"/opt/CTFd/CTFd/utils/initialization/__init__.py\", line 90, in init_logs\r\nctfd_1   |     open(log, 'a').close()\r\nctfd_1   | IOError: [Errno 13] Permission denied: '/var/log/CTFd/logins.log'\r\n```\n", "before_files": [{"content": "from flask import request, session, redirect, url_for, abort, render_template\nfrom werkzeug.wsgi import DispatcherMiddleware\nfrom CTFd.models import db, Tracking\n\nfrom CTFd.utils import markdown, get_config\nfrom CTFd.utils.dates import unix_time_millis, unix_time, isoformat\n\nfrom CTFd.utils import config\nfrom CTFd.utils.config import can_send_mail, ctf_logo, ctf_name, ctf_theme\nfrom CTFd.utils.config.pages import get_pages\nfrom CTFd.utils.events import EventManager, RedisEventManager\nfrom CTFd.utils.plugins import (\n    get_registered_stylesheets,\n    get_registered_scripts,\n    get_configurable_plugins,\n    get_registered_admin_scripts,\n    get_registered_admin_stylesheets\n)\n\nfrom CTFd.utils.countries import get_countries, lookup_country_code\nfrom CTFd.utils.user import authed, get_ip, get_current_user, get_current_team\nfrom CTFd.utils.modes import generate_account_url\nfrom CTFd.utils.config import is_setup\nfrom CTFd.utils.security.csrf import generate_nonce\n\nfrom CTFd.utils.config.visibility import (\n    accounts_visible,\n    challenges_visible,\n    registration_visible,\n    scores_visible\n)\n\nfrom sqlalchemy.exc import InvalidRequestError, IntegrityError\n\nimport datetime\nimport logging\nimport os\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(get_registered_admin_scripts=get_registered_admin_scripts)\n    app.jinja_env.globals.update(get_registered_admin_stylesheets=get_registered_admin_stylesheets)\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\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    for log in logs.values():\n        if not os.path.exists(log):\n            open(log, 'a').close()\n\n    submission_log = logging.handlers.RotatingFileHandler(logs['submissions'], maxBytes=10000)\n    login_log = logging.handlers.RotatingFileHandler(logs['logins'], maxBytes=10000)\n    registration_log = logging.handlers.RotatingFileHandler(logs['registrations'], maxBytes=10000)\n\n    logger_submissions.addHandler(\n        submission_log\n    )\n    logger_logins.addHandler(\n        login_log\n    )\n    logger_registrations.addHandler(\n        registration_log\n    )\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(endpoint, 'theme'):\n            values['theme'] = ctf_theme()\n\n    @app.before_request\n    def needs_setup():\n        if request.path == url_for('views.setup') or request.path.startswith('/themes'):\n            return\n        if not is_setup():\n            return redirect(url_for('views.setup'))\n\n    @app.before_request\n    def tracker():\n        # TODO: This function shouldn't cause a DB hit for lookups if possible\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) as e:\n                print(e.message)\n                db.session.rollback()\n                session.clear()\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 render_template('errors/403.html', error='You have been banned from this CTF'), 403\n\n                    if team and team.banned:\n                        return render_template('errors/403.html', error='Your team has been banned from this CTF'), 403\n\n            db.session.close()\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 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        @app.before_request\n        def force_subdirectory_redirect():\n            if request.path.startswith(application_root) is False:\n                return redirect(application_root + request.script_root + request.full_path)\n\n        app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {\n            application_root: app,\n        })\n", "path": "CTFd/utils/initialization/__init__.py"}], "after_files": [{"content": "from flask import request, session, redirect, url_for, abort, render_template\nfrom werkzeug.wsgi import DispatcherMiddleware\nfrom CTFd.models import db, Tracking\n\nfrom CTFd.utils import markdown, get_config\nfrom CTFd.utils.dates import unix_time_millis, unix_time, isoformat\n\nfrom CTFd.utils import config\nfrom CTFd.utils.config import can_send_mail, ctf_logo, ctf_name, ctf_theme\nfrom CTFd.utils.config.pages import get_pages\nfrom CTFd.utils.events import EventManager, RedisEventManager\nfrom CTFd.utils.plugins import (\n    get_registered_stylesheets,\n    get_registered_scripts,\n    get_configurable_plugins,\n    get_registered_admin_scripts,\n    get_registered_admin_stylesheets\n)\n\nfrom CTFd.utils.countries import get_countries, lookup_country_code\nfrom CTFd.utils.user import authed, get_ip, get_current_user, get_current_team\nfrom CTFd.utils.modes import generate_account_url\nfrom CTFd.utils.config import is_setup\nfrom CTFd.utils.security.csrf import generate_nonce\n\nfrom CTFd.utils.config.visibility import (\n    accounts_visible,\n    challenges_visible,\n    registration_visible,\n    scores_visible\n)\n\nfrom sqlalchemy.exc import InvalidRequestError, IntegrityError\n\nimport datetime\nimport logging\nimport os\nimport sys\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(get_registered_admin_scripts=get_registered_admin_scripts)\n    app.jinja_env.globals.update(get_registered_admin_stylesheets=get_registered_admin_stylesheets)\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\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(logs['submissions'], maxBytes=10000)\n        login_log = logging.handlers.RotatingFileHandler(logs['logins'], maxBytes=10000)\n        registration_log = logging.handlers.RotatingFileHandler(logs['registrations'], maxBytes=10000)\n\n        logger_submissions.addHandler(\n            submission_log\n        )\n        logger_logins.addHandler(\n            login_log\n        )\n        logger_registrations.addHandler(\n            registration_log\n        )\n    except IOError:\n        pass\n\n    stdout = logging.StreamHandler(stream=sys.stdout)\n\n    logger_submissions.addHandler(\n        stdout\n    )\n    logger_logins.addHandler(\n        stdout\n    )\n    logger_registrations.addHandler(\n        stdout\n    )\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(endpoint, 'theme'):\n            values['theme'] = ctf_theme()\n\n    @app.before_request\n    def needs_setup():\n        if request.path == url_for('views.setup') or request.path.startswith('/themes'):\n            return\n        if not is_setup():\n            return redirect(url_for('views.setup'))\n\n    @app.before_request\n    def tracker():\n        # TODO: This function shouldn't cause a DB hit for lookups if possible\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) as e:\n                print(e.message)\n                db.session.rollback()\n                session.clear()\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 render_template('errors/403.html', error='You have been banned from this CTF'), 403\n\n                    if team and team.banned:\n                        return render_template('errors/403.html', error='Your team has been banned from this CTF'), 403\n\n            db.session.close()\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 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        @app.before_request\n        def force_subdirectory_redirect():\n            if request.path.startswith(application_root) is False:\n                return redirect(application_root + request.script_root + request.full_path)\n\n        app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {\n            application_root: app,\n        })\n", "path": "CTFd/utils/initialization/__init__.py"}]}