4
4
from typing import Iterable , Set , Type
5
5
6
6
import flask_restful
7
- from flask import Flask , Response , send_from_directory
7
+ from flask import Flask , Response , g , send_from_directory
8
+ from flask .sessions import SecureCookieSessionInterface
8
9
from flask_mongoengine import MongoEngine
9
10
from flask_security import ConfirmRegisterForm , MongoEngineUserDatastore , Security
10
11
from werkzeug .exceptions import NotFound
@@ -88,6 +89,8 @@ def setup_authentication(app, data_dir):
88
89
# Ignore CSRF, because it's irrelevant for javascript applications
89
90
app .config ["WTF_CSRF_CHECK_DEFAULT" ] = False
90
91
app .config ["SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS" ] = True
92
+ # Forbid sending authentication token in URL parameters
93
+ app .config ["SECURITY_TOKEN_AUTHENTICATION_KEY" ] = None
91
94
92
95
# The database object needs to be created after we configure the flask application
93
96
db = MongoEngine (app )
@@ -114,6 +117,13 @@ class CustomConfirmRegisterForm(ConfirmRegisterForm):
114
117
user_datastore ,
115
118
confirm_register_form = CustomConfirmRegisterForm ,
116
119
)
120
+ from flask_login import user_loaded_from_request
121
+
122
+ @user_loaded_from_request .connect
123
+ def user_loaded_from_request (self , user = None ):
124
+ g .login_via_request = True
125
+
126
+ app .session_interface = disable_session_cookies ()
117
127
118
128
119
129
def init_app_config (app , mongo_url , data_dir : Path ):
@@ -135,6 +145,21 @@ def init_app_config(app, mongo_url, data_dir: Path):
135
145
setup_authentication (app , data_dir )
136
146
137
147
148
+ def disable_session_cookies () -> SecureCookieSessionInterface :
149
+ class CustomSessionInterface (SecureCookieSessionInterface ):
150
+ """Prevent creating session from API requests."""
151
+
152
+ def should_set_cookie (self , * args , ** kwargs ):
153
+ return False
154
+
155
+ def save_session (self , * args , ** kwargs ):
156
+ if g .get ("login_via_request" ):
157
+ return
158
+ return super (CustomSessionInterface , self ).save_session (* args , ** kwargs )
159
+
160
+ return CustomSessionInterface ()
161
+
162
+
138
163
def init_app_url_rules (app ):
139
164
app .add_url_rule ("/" , "serve_home" , serve_home )
140
165
app .add_url_rule ("/<path:static_path>" , "serve_static_file" , serve_static_file )
0 commit comments