Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Introduce get_client_ip

Patryk Zawadzki29cc532a2242
diff --git a/saleor/core/__init__.py b/saleor/core/__init__.py
index 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_currencies
from django.conf import settings
from django.core.checks import register, Warning
-from django_countries import countries
-from django_countries.fields import Country
-from geolite2 import geolite2
TOKEN_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 cover
errors = []
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index d88d0e613b..b6466b7d2c 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -4,8 +4,9 @@ from django.conf import settings
from django.utils.translation import get_language
from django_countries.fields import Country
-from . import analytics, get_country_by_ip, get_currency_for_country
+from . import analytics
from ..discount.models import Sale
+from .utils import get_client_ip, get_country_by_ip, get_currency_for_country
logger = 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__.py
index b0a518d5f8..6f51ec3d5a 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -1,11 +1,15 @@
# coding: utf-8
from __future__ import unicode_literals
+from babel.numbers import get_territory_currencies
from django import forms
from django.conf import settings
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.utils.encoding import iri_to_uri, smart_text
+from django_countries import countries
+from django_countries.fields import Country
from django_prices_openexchangerates import exchange_currency
+from geolite2 import geolite2
from prices import PriceRange
try:
@@ -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.py
index 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 flow
logger.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 ip
diff --git a/saleor/order/views.py b/saleor/order/views.py
index 7cc0c34e01..902c5d9add 100644
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -11,7 +11,8 @@ from payments import RedirectNeeded
from .forms import PaymentDeleteForm, PaymentMethodsForm
from .models import Order, Payment
-from .utils import check_order_status, get_ip
+from ..core.utils import get_client_ip
+from .utils import check_order_status
logger = 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_CHOICES
if 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.py
index cc1775ef03..4b17ba8923 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1,20 +1,20 @@
import pytest
from 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