Moved security part from request to security middleware

This commit is contained in:
Adolfo Gómez García 2021-10-23 22:36:12 +02:00
parent ea79ccbee1
commit c09ea0eb63
2 changed files with 25 additions and 14 deletions

View File

@ -49,9 +49,6 @@ from uds.models import User
logger = logging.getLogger(__name__)
# Simple Bot detection
bot = re.compile('bot|spider', re.IGNORECASE)
# How often to check the requests cache for stuck objects
CHECK_SECONDS = 3600 * 24 # Once a day is more than enough
@ -75,18 +72,13 @@ class GlobalRequestMiddleware:
# Add IP to request
GlobalRequestMiddleware.fillIps(request)
# If bot, break now
ua = request.META.get('HTTP_USER_AGENT', 'Unknown')
if bot.search(ua):
# Return emty response if bot is detected
logger.info('Denied Bot %s from %s to %s', ua, request.ip, request.path)
return HttpResponse(content='Forbbiden', status=403)
# Store request on cache
setRequest(request=request)
# Ensures request contains os
request.os = OsDetector.getOsFromUA(ua)
request.os = OsDetector.getOsFromUA(
request.META.get('HTTP_USER_AGENT', 'Unknown')
)
# Ensures that requests contains the valid user
GlobalRequestMiddleware.getUser(request)

View File

@ -25,21 +25,26 @@
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import re
import logging
import typing
logger = logging.getLogger(__name__)
from django.http import HttpResponseForbidden
from django.http import HttpResponse
if typing.TYPE_CHECKING:
from django.http import HttpRequest, HttpResponse
from django.http import HttpRequest
# Simple Bot detection
bot = re.compile(r'bot|spider', re.IGNORECASE)
class UDSSecurityMiddleware:
'''
This class contains all the security checks done by UDS in order to add some extra protection.
'''
get_response: typing.Any # typing.Callable[['HttpRequest'], 'HttpResponse']
def __init__(
@ -48,5 +53,19 @@ class UDSSecurityMiddleware:
self.get_response = get_response
def __call__(self, request: 'HttpRequest') -> 'HttpResponse':
# TODO: Implement security checks here
# If bot, break now
ua = request.META.get('HTTP_USER_AGENT', 'Connection Maybe a bot. No user agent detected.')
if bot.search(ua):
# Return emty response if bot is detected
logger.info(
'Denied Bot %s from %s to %s',
ua,
request.META.get(
'REMOTE_ADDR',
request.META.get('HTTP_X_FORWARDED_FOR', '').split(",")[-1],
),
request.path,
)
return HttpResponse(content='Forbbiden', status=403)
return self.get_response(request)