2018-08-23 18:25:09 +00:00
import importlib
2019-02-28 07:57:33 +00:00
2013-04-16 10:31:36 +00:00
from django . conf import settings
2015-06-04 09:44:42 +00:00
from django . core . exceptions import ImproperlyConfigured
2014-05-02 10:04:41 +00:00
2019-02-28 07:57:33 +00:00
from . conf import settings as rosetta_settings
2013-04-16 10:31:36 +00:00
def can_translate ( user ) :
return get_access_control_function ( ) ( user )
def get_access_control_function ( ) :
"""
2019-02-28 07:57:33 +00:00
Return a predicate for determining if a user can
access the Rosetta views
2013-04-16 10:31:36 +00:00
"""
2019-10-11 22:22:59 +00:00
access_function = getattr ( settings , ' ROSETTA_ACCESS_CONTROL_FUNCTION ' , None )
if access_function is None :
2013-04-16 10:31:36 +00:00
return is_superuser_staff_or_in_translators_group
2019-10-11 22:22:59 +00:00
elif isinstance ( access_function , str ) :
# Dynamically load a permissions function
perm_module , perm_func = access_function . rsplit ( ' . ' , 1 )
perm_module = importlib . import_module ( perm_module )
return getattr ( perm_module , perm_func )
elif callable ( access_function ) :
return access_function
else :
raise TypeError ( access_function )
2013-04-16 10:31:36 +00:00
# Default access control test
def is_superuser_staff_or_in_translators_group ( user ) :
if not getattr ( settings , ' ROSETTA_REQUIRES_AUTH ' , True ) :
return True
2015-06-04 09:44:42 +00:00
try :
2017-09-23 19:16:16 +00:00
if not user . is_authenticated :
2015-06-04 09:44:42 +00:00
return False
elif user . is_superuser and user . is_staff :
return True
else :
return user . groups . filter ( name = ' translators ' ) . exists ( )
except AttributeError :
if not hasattr ( user , ' is_authenticated ' ) or not hasattr ( user , ' is_superuser ' ) or not hasattr ( user , ' groups ' ) :
raise ImproperlyConfigured ( ' If you are using custom User Models you must implement a custom authentication method for Rosetta. See ROSETTA_ACCESS_CONTROL_FUNCTION here: https://django-rosetta.readthedocs.org/en/latest/settings.html ' )
raise
2014-05-02 10:04:41 +00:00
def can_translate_language ( user , langid ) :
2015-06-04 09:44:42 +00:00
try :
if not rosetta_settings . ROSETTA_LANGUAGE_GROUPS :
return can_translate ( user )
2017-09-23 19:16:16 +00:00
elif not user . is_authenticated :
2015-06-04 09:44:42 +00:00
return False
elif user . is_superuser and user . is_staff :
return True
else :
return user . groups . filter ( name = ' translators- %s ' % langid ) . exists ( )
except AttributeError :
if not hasattr ( user , ' is_authenticated ' ) or not hasattr ( user , ' is_superuser ' ) or not hasattr ( user , ' groups ' ) :
raise ImproperlyConfigured ( ' If you are using custom User Models you must implement a custom authentication method for Rosetta. See ROSETTA_ACCESS_CONTROL_FUNCTION here: https://django-rosetta.readthedocs.org/en/latest/settings.html ' )
raise