Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: refactor country disable logic into the Embargo app #36202

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 0 additions & 7 deletions cms/envs/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -2925,10 +2925,3 @@ def _should_send_learning_badge_events(settings):
# See https://www.meilisearch.com/docs/learn/security/tenant_tokens
MEILISEARCH_INDEX_PREFIX = ""
MEILISEARCH_API_KEY = "devkey"

# .. setting_name: DISABLED_COUNTRIES
# .. setting_default: []
# .. setting_description: List of country codes that should be disabled
# .. for now it wil impact country listing in auth flow and user profile.
# .. eg ['US', 'CA']
DISABLED_COUNTRIES = []
7 changes: 0 additions & 7 deletions cms/envs/production.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,10 +690,3 @@ def get_env_setting(setting):
}

BEAMER_PRODUCT_ID = ENV_TOKENS.get('BEAMER_PRODUCT_ID', BEAMER_PRODUCT_ID)

# .. setting_name: DISABLED_COUNTRIES
# .. setting_default: []
# .. setting_description: List of country codes that should be disabled
# .. for now it wil impact country listing in auth flow and user profile.
# .. eg ['US', 'CA']
DISABLED_COUNTRIES = ENV_TOKENS.get('DISABLED_COUNTRIES', [])
9 changes: 0 additions & 9 deletions lms/envs/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -5550,15 +5550,6 @@ def _should_send_learning_badge_events(settings):
# .. setting_description: Dictionary with additional information that you want to share in the report.
SURVEY_REPORT_EXTRA_DATA = {}


# .. setting_name: DISABLED_COUNTRIES
# .. setting_default: []
# .. setting_description: List of country codes that should be disabled
# .. for now it wil impact country listing in auth flow and user profile.
# .. eg ['US', 'CA']
DISABLED_COUNTRIES = []


LMS_COMM_DEFAULT_FROM_EMAIL = "[email protected]"


Expand Down
17 changes: 16 additions & 1 deletion openedx/core/djangoapps/embargo/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from django.contrib import admin

from .forms import IPFilterForm, RestrictedCourseForm
from .models import CountryAccessRule, IPFilter, RestrictedCourse
from .models import CountryAccessRule, GlobalRestrictedCountry, IPFilter, RestrictedCourse


class IPFilterAdmin(ConfigurationModelAdmin):
Expand Down Expand Up @@ -41,5 +41,20 @@ class RestrictedCourseAdmin(admin.ModelAdmin):
search_fields = ('course_key',)


class GlobalRestrictedCountryAdmin(admin.ModelAdmin):
"""
Admin configuration for the Global Country Restriction model.
"""
list_display = ("country",)

def delete_queryset(self, request, queryset):
"""
Override the delete_queryset method to clear the cache when objects are deleted in bulk.
"""
super().delete_queryset(request, queryset)
GlobalRestrictedCountry.update_cache()


admin.site.register(IPFilter, IPFilterAdmin)
admin.site.register(RestrictedCourse, RestrictedCourseAdmin)
admin.site.register(GlobalRestrictedCountry, GlobalRestrictedCountryAdmin)
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 4.2.18 on 2025-01-29 08:19

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('embargo', '0002_data__add_countries'),
]

operations = [
migrations.CreateModel(
name='GlobalRestrictedCountry',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('country', models.ForeignKey(help_text='The country to be restricted.', on_delete=django.db.models.deletion.CASCADE, to='embargo.country', unique=True)),
],
options={
'verbose_name': 'Global Restricted Country',
'verbose_name_plural': 'Global Restricted Countries',
},
),
]
75 changes: 75 additions & 0 deletions openedx/core/djangoapps/embargo/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,81 @@ class Meta:
get_latest_by = 'timestamp'


class GlobalRestrictedCountry(models.Model):
"""
Model to restrict access to specific countries globally.
"""
country = models.ForeignKey(
"Country",
help_text="The country to be restricted.",
on_delete=models.CASCADE,
unique=True
)

CACHE_KEY = "embargo.global.restricted_countries"

@classmethod
def get_countries(cls):
"""
Retrieve the set of restricted country codes from the cache or refresh it if not available.

Returns:
set: A set of restricted country codes.
"""
return cache.get_or_set(cls.CACHE_KEY, cls._fetch_restricted_countries)

@classmethod
def is_country_restricted(cls, country_code):
"""
Check if the given country code is restricted.

Args:
country_code (str): The country code to check.

Returns:
bool: True if the country is restricted, False otherwise.
"""
return country_code in cls.get_countries()

@classmethod
def _fetch_restricted_countries(cls):
"""
Fetch the set of restricted country codes from the database.

Returns:
set: A set of restricted country codes.
"""
return set(cls.objects.values_list("country__country", flat=True))

@classmethod
def update_cache(cls):
"""
Update the cache with the latest restricted country codes.
"""
cache.set(cls.CACHE_KEY, cls._fetch_restricted_countries())

def save(self, *args, **kwargs):
"""
Override save method to update cache on insert/update.
"""
super().save(*args, **kwargs)
self.update_cache()

def delete(self, *args, **kwargs):
"""
Override delete method to update cache on deletion.
"""
super().delete(*args, **kwargs)
self.update_cache()

def __str__(self):
return f"{self.country.country.name} ({self.country.country})"

class Meta:
verbose_name = "Global Restricted Country"
verbose_name_plural = "Global Restricted Countries"


# Connect the signals to the receivers so we record a history
# of changes to the course access rules.
post_save.connect(CourseAccessRuleHistory.snapshot_post_save_receiver, sender=RestrictedCourse)
Expand Down
11 changes: 8 additions & 3 deletions openedx/core/djangoapps/user_api/accounts/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.validators import ValidationError, validate_email
from django.utils.translation import override as override_language
from django.utils.translation import gettext as _
from django.utils.translation import override as override_language
from eventtracking import tracker
from pytz import UTC

from common.djangoapps.student import views as student_views
from common.djangoapps.student.models import (
AccountRecovery,
Expand All @@ -25,7 +26,7 @@
from common.djangoapps.util.password_policy_validators import validate_password
from lms.djangoapps.certificates.api import get_certificates_for_user
from lms.djangoapps.certificates.data import CertificateStatuses

from openedx.core.djangoapps.embargo.models import GlobalRestrictedCountry
from openedx.core.djangoapps.enrollments.api import get_verified_enrollments
from openedx.core.djangoapps.user_api import accounts, errors, helpers
from openedx.core.djangoapps.user_api.errors import (
Expand All @@ -39,6 +40,7 @@
from openedx.core.lib.api.view_utils import add_serializer_errors
from openedx.features.enterprise_support.utils import get_enterprise_readonly_account_fields
from openedx.features.name_affirmation_api.utils import is_name_affirmation_installed

from .serializers import AccountLegacyProfileSerializer, AccountUserSerializer, UserReadOnlySerializer, _visible_fields

name_affirmation_installed = is_name_affirmation_installed()
Expand Down Expand Up @@ -151,7 +153,10 @@ def update_account_settings(requesting_user, update, username=None):

_validate_email_change(user, update, field_errors)
_validate_secondary_email(user, update, field_errors)
if update.get('country', '') in settings.DISABLED_COUNTRIES:
if (
settings.FEATURES.get('EMBARGO', False) and
GlobalRestrictedCountry.is_country_restricted(update.get('country', ''))
):
field_errors['country'] = {
'developer_message': 'Country is disabled for registration',
'user_message': 'This country cannot be selected for user registration'
Expand Down
15 changes: 9 additions & 6 deletions openedx/core/djangoapps/user_api/accounts/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@
import itertools
import unicodedata
from unittest.mock import Mock, patch
import pytest

import ddt
import pytest
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.http import HttpResponse
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings
from django.urls import reverse
from pytz import UTC
from social_django.models import UserSocialAuth

from common.djangoapps.student.models import (
AccountRecovery,
PendingEmailChange,
Expand All @@ -28,14 +29,14 @@
from common.djangoapps.student.tests.factories import UserFactory
from common.djangoapps.student.tests.tests import UserSettingsEventTestMixin
from common.djangoapps.student.views.management import activate_secondary_email

from lms.djangoapps.certificates.data import CertificateStatuses
from openedx.core.djangoapps.ace_common.tests.mixins import EmailTemplateTagMixin
from openedx.core.djangoapps.embargo.models import Country, GlobalRestrictedCountry
from openedx.core.djangoapps.user_api.accounts import PRIVATE_VISIBILITY
from openedx.core.djangoapps.user_api.accounts.api import (
get_account_settings,
update_account_settings,
get_name_validation_error
get_name_validation_error,
update_account_settings
)
from openedx.core.djangoapps.user_api.accounts.tests.retirement_helpers import ( # pylint: disable=unused-import
RetirementTestCase,
Expand Down Expand Up @@ -574,12 +575,14 @@ def test_change_country_removes_state(self):
assert account_settings['country'] is None
assert account_settings['state'] is None

@override_settings(DISABLED_COUNTRIES=['KP'])
def test_change_to_disabled_country(self):
"""
Test that changing the country to a disabled country is not allowed
"""
# First set the country and state
country = Country.objects.create(country="KP")
GlobalRestrictedCountry.objects.create(country=country)

update_account_settings(self.user, {"country": UserProfile.COUNTRY_WITH_STATES, "state": "MA"})
account_settings = get_account_settings(self.default_request)[0]
assert account_settings['country'] == UserProfile.COUNTRY_WITH_STATES
Expand Down
30 changes: 15 additions & 15 deletions openedx/core/djangoapps/user_authn/views/registration_form.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
"""

import copy
from importlib import import_module
from eventtracking import tracker
import re
from importlib import import_module

from django import forms
from django.conf import settings
Expand All @@ -16,26 +15,25 @@
from django.urls import reverse
from django.utils.translation import gettext as _
from django_countries import countries
from eventtracking import tracker

from common.djangoapps import third_party_auth
from common.djangoapps.edxmako.shortcuts import marketing_link
from common.djangoapps.student.models import CourseEnrollmentAllowed, UserProfile, email_exists_or_retired
from common.djangoapps.util.password_policy_validators import (
password_validators_instruction_texts,
password_validators_restrictions,
validate_password
)
from openedx.core.djangoapps.embargo.models import GlobalRestrictedCountry
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
from openedx.core.djangoapps.user_api import accounts
from openedx.core.djangoapps.user_api.helpers import FormDescription
from openedx.core.djangoapps.user_authn.utils import check_pwned_password, is_registration_api_v1 as is_api_v1
from openedx.core.djangoapps.user_authn.utils import check_pwned_password
from openedx.core.djangoapps.user_authn.utils import is_registration_api_v1 as is_api_v1
from openedx.core.djangoapps.user_authn.views.utils import remove_disabled_country_from_list
from openedx.core.djangolib.markup import HTML, Text
from openedx.features.enterprise_support.api import enterprise_customer_for_request
from common.djangoapps.student.models import (
CourseEnrollmentAllowed,
UserProfile,
email_exists_or_retired,
)
from common.djangoapps.util.password_policy_validators import (
password_validators_instruction_texts,
password_validators_restrictions,
validate_password,
)


class TrueCheckbox(widgets.CheckboxInput):
Expand Down Expand Up @@ -306,7 +304,10 @@ def clean_country(self):
Check if the user's country is in the embargoed countries list.
"""
country = self.cleaned_data.get("country")
if country in settings.DISABLED_COUNTRIES:
if (
settings.FEATURES.get('EMBARGO', False) and
country in GlobalRestrictedCountry.get_countries()
):
raise ValidationError(_("Registration from this country is not allowed due to restrictions."))
return self.cleaned_data.get("country")

Expand Down Expand Up @@ -981,7 +982,6 @@ def _add_country_field(self, form_desc, required=True):
'country',
default=default_country.upper()
)

form_desc.add_field(
"country",
label=country_label,
Expand Down
Loading
Loading