@@ -662,6 +662,81 @@ class Meta:
662662 get_latest_by = 'timestamp'
663663
664664
665+ class GlobalRestrictedCountry (models .Model ):
666+ """
667+ Model to restrict access to specific countries globally.
668+ """
669+ country = models .ForeignKey (
670+ "Country" ,
671+ help_text = "The country to be restricted." ,
672+ on_delete = models .CASCADE ,
673+ unique = True
674+ )
675+
676+ CACHE_KEY = "embargo.global.restricted_countries"
677+
678+ @classmethod
679+ def get_countries (cls ):
680+ """
681+ Retrieve the set of restricted country codes from the cache or refresh it if not available.
682+
683+ Returns:
684+ set: A set of restricted country codes.
685+ """
686+ return cache .get_or_set (cls .CACHE_KEY , cls ._fetch_restricted_countries )
687+
688+ @classmethod
689+ def is_country_restricted (cls , country_code ):
690+ """
691+ Check if the given country code is restricted.
692+
693+ Args:
694+ country_code (str): The country code to check.
695+
696+ Returns:
697+ bool: True if the country is restricted, False otherwise.
698+ """
699+ return country_code in cls .get_countries ()
700+
701+ @classmethod
702+ def _fetch_restricted_countries (cls ):
703+ """
704+ Fetch the set of restricted country codes from the database.
705+
706+ Returns:
707+ set: A set of restricted country codes.
708+ """
709+ return set (cls .objects .values_list ("country__country" , flat = True ))
710+
711+ @classmethod
712+ def update_cache (cls ):
713+ """
714+ Update the cache with the latest restricted country codes.
715+ """
716+ cache .set (cls .CACHE_KEY , cls ._fetch_restricted_countries ())
717+
718+ def save (self , * args , ** kwargs ):
719+ """
720+ Override save method to update cache on insert/update.
721+ """
722+ super ().save (* args , ** kwargs )
723+ self .update_cache ()
724+
725+ def delete (self , * args , ** kwargs ):
726+ """
727+ Override delete method to update cache on deletion.
728+ """
729+ super ().delete (* args , ** kwargs )
730+ self .update_cache ()
731+
732+ def __str__ (self ):
733+ return f"{ self .country .country .name } ({ self .country .country } )"
734+
735+ class Meta :
736+ verbose_name = "Global Restricted Country"
737+ verbose_name_plural = "Global Restricted Countries"
738+
739+
665740# Connect the signals to the receivers so we record a history
666741# of changes to the course access rules.
667742post_save .connect (CourseAccessRuleHistory .snapshot_post_save_receiver , sender = RestrictedCourse )
0 commit comments