def ready(self): # Monkeypatch session_csrf import session_csrf session_csrf.monkeypatch() # Set our admin site as admin.site django_admin.site = django_admin_sites.site = admin_site # Monkeypath hglib.client.pathto # Working around the lack of # https://bz.mercurial-scm.org/show_bug.cgi?id=4510 from hglib.client import hgclient if not hasattr(hgclient, 'pathto'): import os from hglib.util import b def pathto(self, f, cwd='.'): """ Return relative path to f. If cwd is given, use it as current working directory. The returned path uses os.sep as separator. f - file path with / as separator cwd - working directory with os.sep as separator """ return b( os.path.relpath( os.path.join( self.root().decode('latin-1'), *(f.split('/')) ), start=cwd ) ) hgclient.pathto = pathto
def monkeypatch(): """All the monkeypatching we have to do to get things running""" global _has_patched if _has_patched: return # Import for side-effect: configures logging handlers from fjord.settings.log_settings import noop noop() # Monkey-patch admin site from django.contrib import admin from django.contrib.auth.decorators import login_required from session_csrf import anonymous_csrf from adminplus.sites import AdminSitePlus # Patch the admin admin.site = AdminSitePlus() admin.site.login = login_required(anonymous_csrf(admin.site.login)) # Monkey-patch Django's csrf_protect decorator to use # session-based CSRF tokens import session_csrf session_csrf.monkeypatch() logging.debug("Note: monkeypatches executed in %s" % __file__) # Prevent it from being run again later _has_patched = True
def monkeypatch(): """All the monkeypatching we have to do to get things running""" global _has_patched if _has_patched: return # Import for side-effect: configures logging handlers from fjord.settings.log_settings import noop noop() # Monkey-patch admin site from django.contrib import admin from django.contrib.auth.decorators import login_required from session_csrf import anonymous_csrf from adminplus.sites import AdminSitePlus # Patch the admin admin.site = AdminSitePlus() admin.site.login = login_required(anonymous_csrf(admin.site.login)) # Monkey-patch Django's csrf_protect decorator to use # session-based CSRF tokens import session_csrf session_csrf.monkeypatch() logging.debug('Note: monkeypatches executed in %s' % __file__) # Prevent it from being run again later _has_patched = True
def ready(self): # Monkeypatch session_csrf import session_csrf session_csrf.monkeypatch() site = CSRFAdminSite() django_admin.site = site # Monkeypath hglib.client.pathto # Working around the lack of # https://bz.mercurial-scm.org/show_bug.cgi?id=4510 from hglib.client import hgclient if not hasattr(hgclient, 'pathto'): import os from hglib.util import b def pathto(self, f, cwd='.'): """ Return relative path to f. If cwd is given, use it as current working directory. The returned path uses os.sep as separator. f - file path with / as separator cwd - working directory with os.sep as separator """ return b( os.path.relpath(os.path.join(self.root().decode('latin-1'), *(f.split('/'))), start=cwd)) hgclient.pathto = pathto
def ready(self): # The app is now ready. Include any monkey patches here. # Monkey patch CSRF to switch to session based CSRF. Session # based CSRF will prevent attacks from apps under the same # domain. If you're planning to host your app under it's own # domain you can remove session_csrf and use Django's CSRF # library. See also # https://github.com/mozilla/sugardough/issues/38 session_csrf.monkeypatch() # Connect signals. from atmo.jobs.models import SparkJob from atmo.jobs.signals import assign_group_perm, remove_group_perm post_save.connect( assign_group_perm, sender=SparkJob, dispatch_uid="sparkjob_post_save_assign_perm", ) pre_delete.connect( remove_group_perm, sender=SparkJob, dispatch_uid="sparkjob_pre_delete_remove_perm", )
def patch(): global _has_patched if _has_patched: return # Import for side-effect: configures logging handlers. # pylint: disable-msg=W0611 import log_settings # Monkey-patch django forms to avoid having to use Jinja2's |safe # everywhere. import safe_django_forms safe_django_forms.monkeypatch() # Monkey-patch Django's csrf_protect decorator to use session-based CSRF # tokens: if 'session_csrf' in settings.INSTALLED_APPS: import session_csrf session_csrf.monkeypatch() from . import admin admin.monkeypatch() if 'compressor' in settings.INSTALLED_APPS: import jingo from compressor.contrib.jinja2ext import CompressorExtension jingo.env.add_extension(CompressorExtension) logging.debug("Note: funfactory monkey patches executed in %s" % __file__) # prevent it from being run again later _has_patched = True
def patch(): import jingo.monkey jingo.monkey.patch() import session_csrf session_csrf.monkeypatch() import jingo from compressor.contrib.jinja2ext import CompressorExtension jingo.env.add_extension(CompressorExtension)
def ready(self): # The app is now ready. Include any monkey patches here. # Monkey patch CSRF to switch to session based CSRF. Session # based CSRF will prevent attacks from apps under the same # domain. If you're planning to host your app under it's own # domain you can remove session_csrf and use Django's CSRF # library. See also # https://github.com/mozilla/sugardough/issues/38 session_csrf.monkeypatch()
def monkeypatch(self): # Only patch once, ever. if BaseConfig._has_patched: return # Monkey-patch Django's csrf_protect decorator to use # session-based CSRF tokens: session_csrf.monkeypatch() admin.site = SessionCsrfAdminSite() BaseConfig._has_patched = True
def ready(self): super(CoreConfig, self).ready() # Ignore Python warnings unless we're running in debug mode. if not settings.DEBUG: warnings.simplefilter('ignore') session_csrf.monkeypatch() self.load_product_details() self.set_recursion_limit() self.enable_urllib_certificate_checking()
def ready(self): super(CoreConfig, self).ready() # Ignore Python warnings unless we're running in debug mode. if not settings.DEBUG: warnings.simplefilter('ignore') session_csrf.monkeypatch() self.configure_logging() self.load_product_details() self.set_recursion_limit() self.enable_urllib_certificate_checking()
def patch(): global _has_patched if _has_patched: return # Monkey-patch Django's csrf_protect decorator to use session-based CSRF # tokens: if 'session_csrf' in settings.INSTALLED_APPS: import session_csrf session_csrf.monkeypatch() logging.debug("Note: funfactory monkey patches executed in %s" % __file__) # prevent it from being run again later _has_patched = True
def ready(self): super(CoreConfig, self).ready() # Ignore Python warnings unless we're running in debug mode. if not settings.DEBUG: warnings.simplefilter('ignore') jingo.monkey.patch() jingo_env = jingo.get_env() jingo_env.install_gettext_translations(translation, newstyle=True) session_csrf.monkeypatch() self.configure_logging() self.load_product_details()
def ready(self): # The app is now ready. Include any monkey patches here. # Monkey patch CSRF to switch to session based CSRF. Session # based CSRF will prevent attacks from apps under the same # domain. If you're planning to host your app under it's own # domain you can remove session_csrf and use Django's CSRF # library. See also # https://github.com/mozilla/sugardough/issues/38 session_csrf.monkeypatch() # Under some circumstances (e.g. when calling collectstatic) # REDIS_URL is not available and we can skip the job schedule registration. if settings.REDIS_URL: # Register rq scheduled jobs register_job_schedule()
def ready(self): # The app is now ready. Include any monkey patches here. admin.site.site_header = 'Brain Games Administration' admin.site.site_title = 'Mozilla Brain Games' # Monkey patch CSRF to switch to session based CSRF. Session # based CSRF will prevent attacks from apps under the same # domain. If you're planning to host your app under it's own # domain you can remove session_csrf and use Django's CSRF # library. See also # https://github.com/mozilla/sugardough/issues/38 session_csrf.monkeypatch() # Clear games cache cache.delete('games')
def patch(): # Import for side-effect: configures logging handlers. # pylint: disable-msg=W0611 import log_settings # Monkey-patch django forms to avoid having to use Jinja2's |safe # everywhere. import safe_django_forms safe_django_forms.monkeypatch() # Monkey-patch Django's csrf_protect decorator to use session-based CSRF # tokens: if 'session_csrf' in settings.INSTALLED_APPS: import session_csrf session_csrf.monkeypatch() logging.debug("Note: funfactory monkey patches executed in %s" % __file__)
def patch(): global _has_patched if _has_patched: return # # Monkey-patch django forms to avoid having to use Jinja2's |safe # # everywhere. import jingo.monkey jingo.monkey.patch() # Monkey-patch Django's csrf_protect decorator to use session-based CSRF # tokens: import session_csrf session_csrf.monkeypatch() logging.debug("Note: monkey patches executed in %s" % __file__) # Prevent it from being run again later. _has_patched = True
def patch(): global _has_patched if _has_patched: return # Import for side-effect: configures logging handlers. # pylint: disable-msg=W0611 import log_settings # noqa # Monkey-patch Django's csrf_protect decorator to use session-based CSRF # tokens: if 'session_csrf' in settings.INSTALLED_APPS: import session_csrf session_csrf.monkeypatch() logging.debug("Note: funfactory monkey patches executed in %s" % __file__) # prevent it from being run again later _has_patched = True
def patch(): global _has_patched if _has_patched: return # Import for side-effect: configures logging handlers. from fjord.settings.log_settings import noop noop() # Monkey-patch admin site. from django.contrib import admin from django.contrib.auth.decorators import login_required from session_csrf import anonymous_csrf from adminplus.sites import AdminSitePlus # Patch the admin admin.site = AdminSitePlus() admin.site.login = login_required(anonymous_csrf(admin.site.login)) # Monkey-patch django forms to avoid having to use Jinja2's |safe # everywhere. import jingo.monkey jingo.monkey.patch() # Monkey-patch Django's csrf_protect decorator to use # session-based CSRF tokens. import session_csrf session_csrf.monkeypatch() from jingo import load_helpers load_helpers() logging.debug("Note: monkey patches executed in %s" % __file__) # Prevent it from being run again later. _has_patched = True
def patch(): global _has_been_patched, URLWidget if _has_been_patched: return # Monkey patch preserves the old values, so we can pick up any changes # in CharField.widget_attrs and Field.widget_attrs # paulc filed a Django ticket for it, #14884 field_widget_attrs = fields.Field.widget_attrs charfield_widget_attrs = fields.CharField.widget_attrs def required_field_attrs(self, widget): """This function is for use on the base Field class.""" attrs = field_widget_attrs(self, widget) # required="required" isn't supported for groups of checkboxes. if ( self.required and (not "required" in attrs) and not widget.is_hidden and not isinstance(widget, widgets.CheckboxSelectMultiple) ): attrs["required"] = "required" return attrs def required_char_field_attrs(self, widget, *args, **kwargs): """This function is for use on the CharField class.""" # We need to call super() here, since Django's CharField.widget_attrs # doesn't call its super and thus won't use the required_field_attrs # above. attrs = super(fields.CharField, self).widget_attrs(widget, *args, **kwargs) original_attrs = charfield_widget_attrs(self, widget) or {} attrs.update(original_attrs) return attrs fields.Field.widget_attrs = required_field_attrs fields.CharField.widget_attrs = required_char_field_attrs fields.DateField.widget = DateWidget fields.TimeField.widget = TimeWidget fields.URLField.widget = URLWidget fields.EmailField.widget = EmailWidget # Workaround until https://code.djangoproject.com/ticket/16920 gets fixed. from django.contrib.admin import util from django.contrib.admin.util import NestedObjects from django.db import models def _collect(self, objs, source_attr=None, **kwargs): for obj in objs: if source_attr: # We just added a default of None below and that gets around # the problem. self.add_edge(getattr(obj, source_attr, None), obj) else: self.add_edge(None, obj) try: return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs) except models.ProtectedError as e: self.protected.update(e.protected_objects) util.NestedObjects.collect = _collect # Make |safe less necessary for form fields import jingo.monkey jingo.monkey.patch() # Monkey patch django's csrf import session_csrf session_csrf.monkeypatch() # Load jingo helpers from jingo import load_helpers load_helpers() _has_been_patched = True
""" MozTrap root URLconf. """ from django.conf.urls.defaults import patterns, url, include from django.conf.urls.static import static from django.conf import settings from django.contrib import admin admin.autodiscover() import session_csrf session_csrf.monkeypatch() urlpatterns = patterns( "", url(r"^$", "moztrap.view.views.home", name="home"), # runtests --------------------------------------------------------------- url(r"^runtests/", include("moztrap.view.runtests.urls")), # users ------------------------------------------------------------------ url(r"^users/", include("moztrap.view.users.urls")), # manage ----------------------------------------------------------------- url(r"^manage/", include("moztrap.view.manage.urls")), # results ---------------------------------------------------------------- url(r"^results/", include("moztrap.view.results.urls")),
def ready(self): ## Monkeypatch session_csrf import session_csrf session_csrf.monkeypatch() from funfactory import admin admin.monkeypatch()
def setup_environ(manage_file, settings=None): """Sets up a Django app within a manage.py file. Keyword Arguments **settings** An imported settings module. Without this, playdoh tries to import these modules (in order): settings_local, settings """ # sys is global to avoid undefined local global sys, current_settings, execute_manager, ROOT ROOT = os.path.dirname(os.path.abspath(manage_file)) # Adjust the python path and put local packages in front. prev_sys_path = list(sys.path) # Make settings_local importable sys.path.append(ROOT) # Give precedence to your app's parent dir, which contains __init__.py sys.path.append(os.path.abspath(os.path.join(ROOT, os.pardir))) site.addsitedir(path('apps')) site.addsitedir(path('lib')) # Local (project) vendor library site.addsitedir(path('vendor-local')) site.addsitedir(path('vendor-local/lib/python')) # Global (upstream) vendor library site.addsitedir(path('vendor')) site.addsitedir(path('vendor/lib/python')) # Move the new items to the front of sys.path. (via virtualenv) new_sys_path = [] for item in list(sys.path): if item not in prev_sys_path: new_sys_path.append(item) sys.path.remove(item) sys.path[:0] = new_sys_path from django.core.management import execute_manager, setup_environ if not settings: if os.path.isfile(os.path.join(ROOT, 'settings_local.py')): import settings_local as settings warnings.warn("Using settings_local.py is deprecated. See " "http://playdoh.readthedocs.org/en/latest/upgrading.html", DeprecationWarning) else: import settings current_settings = settings validate_settings(settings) # If we want to use django settings anywhere, we need to set up the # required environment variables. setup_environ(settings) # Import for side-effect: configures logging handlers. # pylint: disable-msg=W0611 import log_settings # Monkey-patch django forms to avoid having to use Jinja2's |safe # everywhere. import safe_django_forms safe_django_forms.monkeypatch() # Monkey-patch Django's csrf_protect decorator to use session-based CSRF # tokens: if 'session_csrf' in settings.INSTALLED_APPS: import session_csrf session_csrf.monkeypatch() # Configure Celery (optional) if 'djcelery' in settings.INSTALLED_APPS: import djcelery djcelery.setup_loader()
def patch(): global _has_been_patched, URLWidget if _has_been_patched: return # Monkey patch preserves the old values, so we can pick up any changes # in CharField.widget_attrs and Field.widget_attrs # paulc filed a Django ticket for it, #14884 field_widget_attrs = fields.Field.widget_attrs charfield_widget_attrs = fields.CharField.widget_attrs def required_field_attrs(self, widget): """This function is for use on the base Field class.""" attrs = field_widget_attrs(self, widget) # required="required" isn't supported for groups of checkboxes. if (self.required and 'required' not in attrs and not widget.is_hidden and not isinstance(widget, widgets.CheckboxSelectMultiple)): attrs['required'] = 'required' return attrs def required_char_field_attrs(self, widget, *args, **kwargs): """This function is for use on the CharField class.""" # We need to call super() here, since Django's CharField.widget_attrs # doesn't call its super and thus won't use the required_field_attrs # above. attrs = super(fields.CharField, self).widget_attrs(widget, *args, **kwargs) original_attrs = charfield_widget_attrs(self, widget) or {} attrs.update(original_attrs) return attrs fields.Field.widget_attrs = required_field_attrs fields.CharField.widget_attrs = required_char_field_attrs fields.DateField.widget = DateWidget fields.TimeField.widget = TimeWidget fields.URLField.widget = URLWidget fields.EmailField.widget = EmailWidget # Workaround until https://code.djangoproject.com/ticket/16920 gets fixed. from django.contrib.admin import util from django.contrib.admin.util import NestedObjects from django.db import models def _collect(self, objs, source_attr=None, **kwargs): for obj in objs: if source_attr: # We just added a default of None below and that gets around # the problem. self.add_edge(getattr(obj, source_attr, None), obj) else: self.add_edge(None, obj) try: return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs) except models.ProtectedError as e: self.protected.update(e.protected_objects) util.NestedObjects.collect = _collect # Monkey-patch admin site. from django.contrib import admin from adminplus.sites import AdminSitePlus # Patch the admin admin.site = AdminSitePlus() admin.site.site_header = 'Kitsune Administration' admin.site.site_title = 'Mozilla Support' # Monkey patch django's csrf import session_csrf session_csrf.monkeypatch() # In testing contexts, patch django.shortcuts.render if 'TESTING' == 'TESTING': monkeypatch_render() # Monkey patch ES def get_es(**overrides): """Monkey patch elasticutils get_es to add use_ssl and http_auth settings.""" from django.conf import settings defaults = { 'urls': settings.ES_URLS, 'timeout': getattr(settings, 'ES_TIMEOUT', 5), 'use_ssl': getattr(settings, 'ES_USE_SSL', False), 'http_auth': getattr(settings, 'ES_HTTP_AUTH', None), 'verify_certs': getattr(settings, 'ES_VERIFY_CERTS', True), } defaults.update(overrides) return base_get_es(**defaults) elasticutils_django.get_es = get_es def S_get_es(self, default_builder=get_es): """Returns the elasticsearch Elasticsearch object to use. This uses the django get_es builder by default which takes into account settings in ``settings.py``. """ return super(elasticutils_django.S, self).get_es(default_builder=default_builder) elasticutils_django.S.get_es = S_get_es _has_been_patched = True
def init_session_csrf(): """Load the `session_csrf` module and enable its monkey patches to Django's CSRF middleware.""" import session_csrf session_csrf.monkeypatch()
def patch(): import jingo.monkey jingo.monkey.patch() import session_csrf session_csrf.monkeypatch()
from django.conf.urls import patterns, include, url from django.views.generic import TemplateView import session_csrf session_csrf.monkeypatch() from django.contrib import admin admin.autodiscover() from news.urls import news_router urlpatterns = patterns( '', url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^news/', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^_ah/', include('djangae.urls')), # Note that by default this is also locked down with login:admin in app.yaml url(r'^admin/', include(admin.site.urls)), url(r'^csp/', include('cspreports.urls')), ) # additional REST endpoints urlpatterns += news_router.urls
def patch(): global _has_been_patched, URLWidget if _has_been_patched: return # Monkey patch preserves the old values, so we can pick up any changes # in CharField.widget_attrs and Field.widget_attrs # paulc filed a Django ticket for it, #14884 field_widget_attrs = fields.Field.widget_attrs charfield_widget_attrs = fields.CharField.widget_attrs def required_field_attrs(self, widget): """This function is for use on the base Field class.""" attrs = field_widget_attrs(self, widget) # required="required" isn't supported for groups of checkboxes. if (self.required and 'required' not in attrs and not widget.is_hidden and not isinstance(widget, widgets.CheckboxSelectMultiple)): attrs['required'] = 'required' return attrs def required_char_field_attrs(self, widget, *args, **kwargs): """This function is for use on the CharField class.""" # We need to call super() here, since Django's CharField.widget_attrs # doesn't call its super and thus won't use the required_field_attrs # above. attrs = super(fields.CharField, self).widget_attrs(widget, *args, **kwargs) original_attrs = charfield_widget_attrs(self, widget) or {} attrs.update(original_attrs) return attrs fields.Field.widget_attrs = required_field_attrs fields.CharField.widget_attrs = required_char_field_attrs fields.DateField.widget = DateWidget fields.TimeField.widget = TimeWidget fields.URLField.widget = URLWidget fields.EmailField.widget = EmailWidget # Workaround until https://code.djangoproject.com/ticket/16920 gets fixed. from django.contrib.admin import util from django.contrib.admin.util import NestedObjects from django.db import models def _collect(self, objs, source_attr=None, **kwargs): for obj in objs: if source_attr: # We just added a default of None below and that gets around # the problem. self.add_edge(getattr(obj, source_attr, None), obj) else: self.add_edge(None, obj) try: return super(NestedObjects, self).collect( objs, source_attr=source_attr, **kwargs) except models.ProtectedError as e: self.protected.update(e.protected_objects) util.NestedObjects.collect = _collect # Monkey-patch admin site. from django.contrib import admin from adminplus.sites import AdminSitePlus # Patch the admin admin.site = AdminSitePlus() admin.site.site_header = 'Kitsune Administration' admin.site.site_title = 'Mozilla Support' # Monkey patch django's csrf import session_csrf session_csrf.monkeypatch() # In testing contexts, patch django.shortcuts.render if 'TESTING' == 'TESTING': monkeypatch_render() # Monkey patch ES def get_es(**overrides): """Monkey patch elasticutils get_es to add use_ssl and http_auth settings.""" from django.conf import settings defaults = { 'urls': settings.ES_URLS, 'timeout': getattr(settings, 'ES_TIMEOUT', 5), 'use_ssl': getattr(settings, 'ES_USE_SSL', False), 'http_auth': getattr(settings, 'ES_HTTP_AUTH', None), 'verify_certs': getattr(settings, 'ES_VERIFY_CERTS', True), } defaults.update(overrides) return base_get_es(**defaults) elasticutils_django.get_es = get_es def S_get_es(self, default_builder=get_es): """Returns the elasticsearch Elasticsearch object to use. This uses the django get_es builder by default which takes into account settings in ``settings.py``. """ return super(elasticutils_django.S, self).get_es(default_builder=default_builder) elasticutils_django.S.get_es = S_get_es _has_been_patched = True
def patch(): import session_csrf session_csrf.monkeypatch()
def patch(): global _has_been_patched, URLWidget if _has_been_patched: return # Monkey patch preserves the old values, so we can pick up any changes # in CharField.widget_attrs and Field.widget_attrs # paulc filed a Django ticket for it, #14884 field_widget_attrs = fields.Field.widget_attrs charfield_widget_attrs = fields.CharField.widget_attrs def required_field_attrs(self, widget): """This function is for use on the base Field class.""" attrs = field_widget_attrs(self, widget) # required="required" isn't supported for groups of checkboxes. if (self.required and 'required' not in attrs and not widget.is_hidden and not isinstance(widget, widgets.CheckboxSelectMultiple)): attrs['required'] = 'required' return attrs def required_char_field_attrs(self, widget, *args, **kwargs): """This function is for use on the CharField class.""" # We need to call super() here, since Django's CharField.widget_attrs # doesn't call its super and thus won't use the required_field_attrs # above. attrs = super(fields.CharField, self).widget_attrs(widget, *args, **kwargs) original_attrs = charfield_widget_attrs(self, widget) or {} attrs.update(original_attrs) return attrs fields.Field.widget_attrs = required_field_attrs fields.CharField.widget_attrs = required_char_field_attrs fields.DateField.widget = DateWidget fields.TimeField.widget = TimeWidget fields.URLField.widget = URLWidget fields.EmailField.widget = EmailWidget # Workaround until https://code.djangoproject.com/ticket/16920 gets fixed. from django.contrib.admin import util from django.contrib.admin.util import NestedObjects from django.db import models def _collect(self, objs, source_attr=None, **kwargs): for obj in objs: if source_attr: # We just added a default of None below and that gets around # the problem. self.add_edge(getattr(obj, source_attr, None), obj) else: self.add_edge(None, obj) try: return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs) except models.ProtectedError as e: self.protected.update(e.protected_objects) util.NestedObjects.collect = _collect # Make |safe less necessary for form fields import jingo.monkey jingo.monkey.patch() # Monkey patch django's csrf import session_csrf session_csrf.monkeypatch() # Load jingo helpers from jingo import load_helpers load_helpers() _has_been_patched = True
def apply_monkeypatches(self): session_csrf.monkeypatch() admin_monkeypatch()