From 738591b05ec3a74c967299bae18d3ed64a2349b8 Mon Sep 17 00:00:00 2001 From: iou1name Date: Thu, 30 Aug 2018 23:33:25 -0400 Subject: [PATCH] expose visitor's real ip to websocket --- titivillus/asgi_middleware.py | 18 ++++++++++++++++++ titivillus/routing.py | 7 ++++++- 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 titivillus/asgi_middleware.py diff --git a/titivillus/asgi_middleware.py b/titivillus/asgi_middleware.py new file mode 100644 index 0000000..a8c2e65 --- /dev/null +++ b/titivillus/asgi_middleware.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +""" +Some custom asgi middleware for titivillus. +""" +from channels.auth import AuthMiddlewareStack + +class XRealIPMiddleware(object): + """ + Attempts to set the get the visitor's real IP by grabbing the + `X-Real-IP` header from the request. + """ + def __init__(self, inner): + self.inner = inner + def __call__(self, scope): + headers = dict(scope['headers']) + if b'x-real-ip' in headers: + scope['client'][0] = headers[b'x-real-ip'].decode('utf-8') + return self.inner(scope) diff --git a/titivillus/routing.py b/titivillus/routing.py index d506dd2..86a0dce 100644 --- a/titivillus/routing.py +++ b/titivillus/routing.py @@ -6,9 +6,14 @@ from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import quest.routing +from .asgi_middleware import XRealIPMiddleware + +CustomMiddlewareStack = lambda inner: XRealIPMiddleware( + AuthMiddlewareStack(inner) +) application = ProtocolTypeRouter({ - 'websocket': AuthMiddlewareStack( + 'websocket': CustomMiddlewareStack( URLRouter( quest.routing.websocket_urlpatterns )