1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
import re
try:
from django.urls import reverse, NoReverseMatch
except ImportError:
from django.core.urlresolvers import reverse, NoReverseMatch
from django.conf import settings
from django.contrib.auth.decorators import login_required
STRONGHOLD_PUBLIC_URLS = getattr(settings, "STRONGHOLD_PUBLIC_URLS", ())
STRONGHOLD_DEFAULTS = getattr(settings, "STRONGHOLD_DEFAULTS", True)
STRONGHOLD_PUBLIC_NAMED_URLS = getattr(settings, "STRONGHOLD_PUBLIC_NAMED_URLS", ())
def is_authenticated(user):
""" make compatible with django 1 and 2 """
try:
return user.is_authenticated()
except TypeError:
return user.is_authenticated
def test_request(request, view_func, view_args, view_kwargs):
"""
Default test against request in middleware.
Set this in STRONGHOLD_USER_TEST_FUNC in your django.conf.settings if you
want to use the request details to deny permission.
"""
return True
STRONGHOLD_USER_TEST_FUNC = getattr(settings, "STRONGHOLD_USER_TEST_FUNC", is_authenticated)
STRONGHOLD_REQUEST_TEST_FUNC = getattr(settings, "STRONGHOLD_REQUEST_TEST_FUNC", test_request)
if STRONGHOLD_DEFAULTS:
if "django.contrib.auth" in settings.INSTALLED_APPS:
STRONGHOLD_PUBLIC_NAMED_URLS += ("login", "logout")
# Do not login protect the logout url, causes an infinite loop
logout_url = getattr(settings, "LOGOUT_URL", None)
if logout_url:
STRONGHOLD_PUBLIC_URLS += (r"^%s.+$" % logout_url,)
if settings.DEBUG:
# In Debug mode we serve the media urls as public by default as a
# convenience. We make no other assumptions
static_url = getattr(settings, "STATIC_URL", None)
media_url = getattr(settings, "MEDIA_URL", None)
if static_url:
STRONGHOLD_PUBLIC_URLS += (r"^%s.+$" % static_url,)
if media_url:
STRONGHOLD_PUBLIC_URLS += (r"^%s.+$" % media_url,)
# named urls can be unsafe if a user puts the wrong url in. Right now urls that
# dont reverse are just ignored with a warning. Maybe in the future make this
# so it breaks?
named_urls = []
for named_url in STRONGHOLD_PUBLIC_NAMED_URLS:
try:
url = reverse(named_url)
named_urls.append(url)
except NoReverseMatch:
# print "Stronghold: Could not reverse Named URL: '%s'. Is it in your `urlpatterns`? Ignoring." % named_url
# ignore non-matches
pass
STRONGHOLD_PUBLIC_URLS += tuple(["^%s$" % url for url in named_urls])
if STRONGHOLD_PUBLIC_URLS:
STRONGHOLD_PUBLIC_URLS = [re.compile(v) for v in STRONGHOLD_PUBLIC_URLS]
|