Classe ReverseProxied WSGI pour ré-écriture des URL http/https

This commit is contained in:
Emmanuel Viennet 2021-09-16 16:05:37 +02:00
parent c8949e870f
commit 8b6a569a31
3 changed files with 25 additions and 6 deletions

View File

@ -133,8 +133,24 @@ class ScoSMTPHandler(SMTPHandler):
return subject return subject
class ReverseProxied(object):
"""Adaptateur wsgi qui nous permet d'avoir toutes les URL calculées en https
sauf quand on est en dev.
La variable HTTP_X_FORWARDED_PROTO est positionnée par notre config nginx"""
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
scheme = environ.get("HTTP_X_FORWARDED_PROTO")
if scheme:
environ["wsgi.url_scheme"] = scheme # ou forcer à https ici ?
return self.app(environ, start_response)
def create_app(config_class=DevConfig): def create_app(config_class=DevConfig):
app = Flask(__name__, static_url_path="/ScoDoc/static", static_folder="static") app = Flask(__name__, static_url_path="/ScoDoc/static", static_folder="static")
app.wsgi_app = ReverseProxied(app.wsgi_app)
app.logger.setLevel(logging.DEBUG) app.logger.setLevel(logging.DEBUG)
app.config.from_object(config_class) app.config.from_object(config_class)

View File

@ -43,12 +43,14 @@ class ZRequest(object):
"Emulating Zope 2 REQUEST" "Emulating Zope 2 REQUEST"
def __init__(self): def __init__(self):
if current_app.config["DEBUG"]: # if current_app.config["DEBUG"]:
self.URL = request.base_url
self.BASE0 = request.url_root # le ReverseProxied se charge maintenant de mettre le bon protocole http ou https
else: self.URL = request.base_url
self.URL = request.base_url.replace("http://", "https://") self.BASE0 = request.url_root
self.BASE0 = request.url_root.replace("http://", "https://") # else:
# self.URL = request.base_url.replace("http://", "https://")
# self.BASE0 = request.url_root.replace("http://", "https://")
self.URL0 = self.URL self.URL0 = self.URL
# query_string is bytes: # query_string is bytes:
self.QUERY_STRING = request.query_string.decode("utf-8") self.QUERY_STRING = request.query_string.decode("utf-8")

View File

@ -27,6 +27,7 @@ server {
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
} }
location /ScoDoc/static { location /ScoDoc/static {
# handle static files directly, without forwarding to the application # handle static files directly, without forwarding to the application