2019-02-27 00:45:00 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2022-08-12 10:36:17 +00:00
|
|
|
import ipaddress
|
2022-08-17 07:20:42 +00:00
|
|
|
from urllib.parse import urljoin, urlparse
|
2021-09-27 11:06:26 +00:00
|
|
|
|
2021-11-08 07:12:12 +00:00
|
|
|
from django.conf import settings
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2022-05-07 08:20:12 +00:00
|
|
|
|
|
|
|
from audits.const import DEFAULT_CITY
|
2023-07-24 03:52:25 +00:00
|
|
|
from audits.models import UserLoginLog
|
|
|
|
from common.utils import get_logger
|
|
|
|
from common.utils import validate_ip, get_ip_city, get_request_ip
|
2022-05-07 08:20:12 +00:00
|
|
|
from .notifications import DifferentCityLoginMessage
|
2020-06-30 09:12:38 +00:00
|
|
|
|
|
|
|
logger = get_logger(__file__)
|
|
|
|
|
|
|
|
|
2021-11-08 07:12:12 +00:00
|
|
|
def check_different_city_login_if_need(user, request):
|
|
|
|
if not settings.SECURITY_CHECK_DIFFERENT_CITY_LOGIN:
|
|
|
|
return
|
|
|
|
|
2021-09-27 11:06:26 +00:00
|
|
|
ip = get_request_ip(request) or '0.0.0.0'
|
2022-08-12 10:36:17 +00:00
|
|
|
city_white = [_('LAN'), 'LAN']
|
|
|
|
is_private = ipaddress.ip_address(ip).is_private
|
2023-10-09 06:39:13 +00:00
|
|
|
if is_private:
|
|
|
|
return
|
|
|
|
last_user_login = UserLoginLog.objects.exclude(
|
|
|
|
city__in=city_white
|
|
|
|
).filter(username=user.username, status=True).first()
|
|
|
|
if not last_user_login:
|
|
|
|
return
|
|
|
|
|
|
|
|
city = get_ip_city(ip)
|
|
|
|
last_city = get_ip_city(last_user_login.ip)
|
|
|
|
if city == last_city:
|
|
|
|
return
|
2021-11-02 07:41:25 +00:00
|
|
|
|
2023-10-09 06:39:13 +00:00
|
|
|
DifferentCityLoginMessage(user, ip, city).publish_async()
|
2022-08-04 06:40:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
def build_absolute_uri(request, path=None):
|
|
|
|
""" Build absolute redirect """
|
|
|
|
if path is None:
|
|
|
|
path = '/'
|
2022-08-17 07:20:42 +00:00
|
|
|
site_url = urlparse(settings.SITE_URL)
|
|
|
|
scheme = site_url.scheme or request.scheme
|
|
|
|
host = request.get_host()
|
|
|
|
url = f'{scheme}://{host}'
|
|
|
|
redirect_uri = urljoin(url, path)
|
2022-08-04 06:40:33 +00:00
|
|
|
return redirect_uri
|
|
|
|
|
|
|
|
|
|
|
|
def build_absolute_uri_for_oidc(request, path=None):
|
|
|
|
""" Build absolute redirect uri for OIDC """
|
|
|
|
if path is None:
|
|
|
|
path = '/'
|
|
|
|
if settings.BASE_SITE_URL:
|
|
|
|
# OIDC 专用配置项
|
|
|
|
redirect_uri = urljoin(settings.BASE_SITE_URL, path)
|
2022-08-17 07:20:42 +00:00
|
|
|
return redirect_uri
|
|
|
|
return build_absolute_uri(request, path=path)
|