2019-08-02 12:57:53 +00:00
|
|
|
# -*- mode: python; coding: utf-8 -*-
|
|
|
|
# Copyright (C) 2017-2019 by BDE ENS Paris-Saclay
|
|
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
|
|
|
|
import ipaddress
|
|
|
|
|
2017-07-28 03:35:45 +00:00
|
|
|
from django.shortcuts import redirect
|
2019-08-02 12:57:53 +00:00
|
|
|
|
2017-07-16 00:41:44 +00:00
|
|
|
from med.settings import AUTHORIZED_IP_RANGE, AUTHORIZED_IP6_RANGE
|
2019-08-02 12:57:53 +00:00
|
|
|
|
2017-07-16 00:41:44 +00:00
|
|
|
|
|
|
|
def user_is_in_campus(function):
|
|
|
|
def wrap(request, *args, **kwargs):
|
|
|
|
if not request.user.is_authenticated:
|
|
|
|
remote_ip = get_ip(request)
|
2019-08-02 12:57:53 +00:00
|
|
|
if not ipaddress.ip_address(remote_ip) in ipaddress.ip_network(
|
|
|
|
AUTHORIZED_IP_RANGE) and not ipaddress.ip_address(remote_ip) in ipaddress.ip_network(
|
|
|
|
AUTHORIZED_IP6_RANGE):
|
2017-07-28 03:35:45 +00:00
|
|
|
return redirect("/")
|
2017-07-16 00:41:44 +00:00
|
|
|
return function(request, *args, **kwargs)
|
2019-08-02 12:57:53 +00:00
|
|
|
|
2017-07-16 00:41:44 +00:00
|
|
|
wrap.__doc__ = function.__doc__
|
|
|
|
wrap.__name__ = function.__name__
|
|
|
|
return wrap
|
|
|
|
|
2019-08-02 12:57:53 +00:00
|
|
|
|
2017-07-16 00:41:44 +00:00
|
|
|
def get_ip(request):
|
|
|
|
"""Returns the IP of the request, accounting for the possibility of being
|
|
|
|
behind a proxy.
|
|
|
|
"""
|
|
|
|
ip = request.META.get("HTTP_X_FORWARDED_FOR", None)
|
|
|
|
if ip:
|
|
|
|
# X_FORWARDED_FOR returns client1, proxy1, proxy2,...
|
|
|
|
ip = ip.split(", ")[0]
|
|
|
|
else:
|
|
|
|
ip = request.META.get("REMOTE_ADDR", "")
|
|
|
|
return ip
|