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,9 @@ 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
+ # In Token Authentication we can pass the token both in query parametar and header
93
+ # This disables the query parameter token
94
+ app .config ["SECURITY_TOKEN_AUTHENTICATION_KEY" ] = None
91
95
92
96
# The database object needs to be created after we configure the flask application
93
97
db = MongoEngine (app )
@@ -109,12 +113,31 @@ class CustomConfirmRegisterForm(ConfirmRegisterForm):
109
113
"Email" , default = "dummy@dummy.com" , validators = [validate_no_user_exists_already ]
110
114
)
111
115
116
+ from flask_login import user_loaded_from_request
117
+
118
+ @user_loaded_from_request .connect
119
+ def user_loaded_from_request (self , user = None ):
120
+ g .login_via_request = True
121
+
122
+ class CustomSessionInterface (SecureCookieSessionInterface ):
123
+ """Prevent creating session from API requests."""
124
+
125
+ def should_set_cookie (self , * args , ** kwargs ):
126
+ return False
127
+
128
+ def save_session (self , * args , ** kwargs ):
129
+ if g .get ("login_via_request" ):
130
+ return
131
+ return super (CustomSessionInterface , self ).save_session (* args , ** kwargs )
132
+
112
133
app .security = Security (
113
134
app ,
114
135
user_datastore ,
115
136
confirm_register_form = CustomConfirmRegisterForm ,
116
137
)
117
138
139
+ app .session_interface = CustomSessionInterface ()
140
+
118
141
119
142
def init_app_config (app , mongo_url , data_dir : Path ):
120
143
app .config ["MONGO_URI" ] = mongo_url
0 commit comments