Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Introduce get_client_ip
Patryk Zawadzki29cc532a2242
diff --git a/saleor/core/__init__.py b/saleor/core/__init__.pyindex d8f4ddadb4..d38f3038eb 100644--- a/saleor/core/__init__.py+++ b/saleor/core/__init__.py@@ -1,33 +1,12 @@from __future__ import unicode_literals-from babel.numbers import get_territory_currenciesfrom django.conf import settingsfrom django.core.checks import register, Warning-from django_countries import countries-from django_countries.fields import Country-from geolite2 import geolite2TOKEN_PATTERN = ('(?P<token>[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}''-[0-9a-z]{12})')-def get_country_by_ip(ip_address):- reader = geolite2.reader()- geo_data = reader.get(ip_address)- geolite2.close()- if geo_data and 'country' in geo_data and 'iso_code' in geo_data['country']:- country_iso_code = geo_data['country']['iso_code']- if country_iso_code in countries:- return Country(country_iso_code)---def get_currency_for_country(country):- currencies = get_territory_currencies(country.code)- if len(currencies):- return currencies[0]- return settings.DEFAULT_CURRENCY--@register()def check_session_caching(app_configs, **kwargs): # pragma: no covererrors = []diff --git a/saleor/core/middleware.py b/saleor/core/middleware.pyindex d88d0e613b..b6466b7d2c 100644--- a/saleor/core/middleware.py+++ b/saleor/core/middleware.py@@ -4,8 +4,9 @@ from django.conf import settingsfrom django.utils.translation import get_languagefrom django_countries.fields import Country-from . import analytics, get_country_by_ip, get_currency_for_country+from . import analyticsfrom ..discount.models import Sale+from .utils import get_client_ip, get_country_by_ip, get_currency_for_countrylogger = logging.getLogger(__name__)@@ -34,8 +35,9 @@ class DiscountMiddleware(object):class CountryMiddleware(object):def process_request(self, request):- if 'REMOTE_ADDR' in request.META:- request.country = get_country_by_ip(request.META['REMOTE_ADDR'])+ client_ip = get_client_ip(request)+ if client_ip:+ request.country = get_country_by_ip(client_ip)if not request.country:request.country = Country(settings.DEFAULT_COUNTRY)diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex b0a518d5f8..6f51ec3d5a 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -1,11 +1,15 @@# coding: utf-8from __future__ import unicode_literals+from babel.numbers import get_territory_currenciesfrom django import formsfrom django.conf import settingsfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginatorfrom django.utils.encoding import iri_to_uri, smart_text+from django_countries import countries+from django_countries.fields import Countryfrom django_prices_openexchangerates import exchange_currency+from geolite2 import geolite2from prices import PriceRangetry:@@ -38,6 +42,30 @@ def build_absolute_uri(location, is_secure=False):return iri_to_uri(location)+def get_client_ip(request):+ ip = request.META.get('HTTP_X_FORWARDED_FOR', None)+ if ip:+ return ip.split(',')[0].strip()+ return request.META.get('REMOTE_ADDR', None)+++def get_country_by_ip(ip_address):+ reader = geolite2.reader()+ geo_data = reader.get(ip_address)+ geolite2.close()+ if geo_data and 'country' in geo_data and 'iso_code' in geo_data['country']:+ country_iso_code = geo_data['country']['iso_code']+ if country_iso_code in countries:+ return Country(country_iso_code)+++def get_currency_for_country(country):+ currencies = get_territory_currencies(country.code)+ if len(currencies):+ return currencies[0]+ return settings.DEFAULT_CURRENCY++def get_paginator_items(items, paginate_by, page):paginator = Paginator(items, paginate_by)try:diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 50d283a556..b63834b566 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -36,12 +36,3 @@ def order_status_change(sender, instance, **kwargs):except Exception:# Analytics failing should not abort the checkout flowlogger.exception('Recording order in analytics failed')---def get_ip(request):- ip = request.META.get('HTTP_X_FORWARDED_FOR', None)- if ip:- ip = ip.split(', ')[0]- else:- ip = request.META.get('REMOTE_ADDR', '')- return ipdiff --git a/saleor/order/views.py b/saleor/order/views.pyindex 7cc0c34e01..902c5d9add 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -11,7 +11,8 @@ from payments import RedirectNeededfrom .forms import PaymentDeleteForm, PaymentMethodsFormfrom .models import Order, Payment-from .utils import check_order_status, get_ip+from ..core.utils import get_client_ip+from .utils import check_order_statuslogger = logging.getLogger(__name__)@@ -78,7 +79,7 @@ def start_payment(request, order, variant):'description': _('Order %(order_number)s') % {'order_number': order},'billing_country_area': billing.country_area,- 'customer_ip_address': get_ip(request)}+ 'customer_ip_address': get_client_ip(request)}variant_choices = settings.CHECKOUT_PAYMENT_CHOICESif variant not in [code for code, dummy_name in variant_choices]:raise Http404('%r is not a valid payment variant' % (variant,))diff --git a/tests/test_core.py b/tests/test_core.pyindex cc1775ef03..4b17ba8923 100644--- a/tests/test_core.py+++ b/tests/test_core.py@@ -1,20 +1,20 @@import pytestfrom mock import Mock-from saleor.core import Country, get_country_by_ip, get_currency_for_country+from saleor.core.utils import (+ Country, get_country_by_ip, get_currency_for_country)[email protected]('reader, expected_country', [- (Mock(return_value=Mock(get=Mock(return_value={- 'country': {'iso_code': 'PL'}}))), Country('PL')),- (Mock(return_value=Mock(get=Mock(return_value={- 'country': {'iso_code': 'UNKNOWN'}}))), None),- (Mock(return_value=Mock(get=Mock(return_value=None))), None),- (Mock(return_value=Mock(get=Mock(return_value={}))), None),- (Mock(return_value=Mock(get=Mock(return_value={'country': {}}))), None),-])-def test_get_country_by_ip(reader, expected_country, monkeypatch):- monkeypatch.setattr('saleor.core.geolite2.reader', reader)[email protected]('ip_data, expected_country', [+ ({'country': {'iso_code': 'PL'}}, Country('PL')),+ ({'country': {'iso_code': 'UNKNOWN'}}, None),+ (None, None),+ ({}, None),+ ({'country': {}}, None)])+def test_get_country_by_ip(ip_data, expected_country, monkeypatch):+ monkeypatch.setattr(+ 'saleor.core.utils.geolite2.reader',+ Mock(return_value=Mock(get=Mock(return_value=ip_data))))country = get_country_by_ip('127.0.0.1')assert country == expected_country