Merge "django2: is_authenticated/is_anonymous is now property only"

This commit is contained in:
Zuul 2018-03-01 14:46:49 +00:00 committed by Gerrit Code Review
commit b82b7d4167
12 changed files with 27 additions and 66 deletions

View File

@ -48,7 +48,7 @@ def require_auth(view_func):
@functools.wraps(view_func, assigned=available_attrs(view_func))
def dec(request, *args, **kwargs):
if request.user.is_authenticated():
if request.user.is_authenticated:
return view_func(request, *args, **kwargs)
raise NotAuthenticated(_("Please log in to continue."))
return dec
@ -79,7 +79,7 @@ def require_perms(view_func, required):
@functools.wraps(view_func, assigned=available_attrs(view_func))
def dec(request, *args, **kwargs):
if request.user.is_authenticated():
if request.user.is_authenticated:
if request.user.has_perms(view_func._required_perms):
return view_func(request, *args, **kwargs)
raise NotAuthorized(_("You are not authorized to access %s")

View File

@ -49,7 +49,7 @@ class HorizonMiddleware(object):
request.horizon = {'dashboard': None,
'panel': None,
'async_messages': []}
if not hasattr(request, "user") or not request.user.is_authenticated():
if not hasattr(request, "user") or not request.user.is_authenticated:
# proceed no further if the current request is already known
# not to be authenticated
# it is CRITICAL to perform this check as early as possible

View File

@ -116,7 +116,7 @@ class OperationLogMiddleware(object):
user = getattr(request, 'user', None)
if not user:
return
if not request.user.is_authenticated():
if not request.user.is_authenticated:
return
method = request.method.upper()
if not (method in self.target_methods):

View File

@ -243,7 +243,7 @@ class KeystoneBackend(object):
The permissions are returned as ``"openstack.{{ role.name }}"``.
"""
if user.is_anonymous() or obj is not None:
if user.is_anonymous or obj is not None:
return set()
# TODO(gabrielhurley): Integrate policy-driven RBAC
# when supported by Keystone.

View File

@ -15,11 +15,9 @@ import datetime
import hashlib
import logging
import django
from django.conf import settings
from django.contrib.auth import models
from django.db import models as db_models
from django.utils import deprecation
from keystoneauth1 import exceptions as keystone_exceptions
from keystoneclient.common import cms as keystone_cms
import six
@ -278,50 +276,21 @@ class User(models.AbstractBaseUser, models.AnonymousUser):
return None
return not utils.is_token_valid(self.token, margin)
if django.VERSION >= (1, 10):
@property
def is_authenticated(self):
"""Checks for a valid authentication."""
if (self.token is not None and utils.is_token_valid(self.token)):
return deprecation.CallableTrue
else:
return deprecation.CallableFalse
@property
def is_authenticated(self):
"""Checks for a valid authentication."""
if (self.token is not None and utils.is_token_valid(self.token)):
return True
else:
return False
@property
def is_anonymous(self):
"""Return if the user is not authenticated.
@property
def is_anonymous(self):
"""Return if the user is not authenticated.
:returns: ``True`` if not authenticated,``False`` otherwise.
"""
return deprecation.CallableBool(not self.is_authenticated)
else:
def is_authenticated(self, margin=None):
"""Checks for a valid authentication.
:param margin:
A security time margin in seconds before end of authentication.
Will return ``False`` if authentication ends in less than
``margin`` seconds of time.
A default margin can be set by the TOKEN_TIMEOUT_MARGIN in the
django settings.
"""
return (self.token is not None and
utils.is_token_valid(self.token, margin))
def is_anonymous(self, margin=None):
"""Return if the user is not authenticated.
:returns: ``True`` if not authenticated,``False`` otherwise.
:param margin:
A security time margin in seconds before end of an eventual
authentication.
Will return ``True`` even if authenticated but that
authentication ends in less than ``margin`` seconds of time.
A default margin can be set by the TOKEN_TIMEOUT_MARGIN in the
django settings.
"""
return not self.is_authenticated(margin)
:returns: ``True`` if not authenticated,``False`` otherwise.
"""
return not self.is_authenticated
@property
def is_active(self):
@ -340,7 +309,7 @@ class User(models.AbstractBaseUser, models.AnonymousUser):
@property
def authorized_tenants(self):
"""Returns a memoized list of tenants this user may access."""
if self.is_authenticated() and self._authorized_tenants is None:
if self.is_authenticated and self._authorized_tenants is None:
endpoint = self.endpoint
try:
self._authorized_tenants = utils.get_project_list(

View File

@ -69,7 +69,7 @@ def login(request, template_name=None, extra_context=None, **kwargs):
# dashboard straight away, unless the 'next' parameter is set as it
# usually indicates requesting access to a page that requires different
# permissions.
if (request.user.is_authenticated() and
if (request.user.is_authenticated and
auth.REDIRECT_FIELD_NAME not in request.GET and
auth.REDIRECT_FIELD_NAME not in request.POST):
return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)
@ -114,7 +114,7 @@ def login(request, template_name=None, extra_context=None, **kwargs):
# Set the session data here because django's session key rotation
# will erase it if we set it earlier.
if request.user.is_authenticated():
if request.user.is_authenticated:
auth_user.set_session_from_user(request, request.user)
regions = dict(forms.Login.get_region_choices())
region = request.user.endpoint

View File

@ -105,7 +105,7 @@ def ajax(authenticated=True, data_required=False,
@functools.wraps(function,
assigned=decorators.available_attrs(function))
def _wrapped(self, request, *args, **kw):
if authenticated and not request.user.is_authenticated():
if authenticated and not request.user.is_authenticated:
return JSONResponse('not logged in', 401)
if not request.is_ajax():
return JSONResponse('request must be AJAX', 400)

View File

@ -44,7 +44,7 @@ def openstack(request):
# Auth/Keystone context
context.setdefault('authorized_tenants', [])
if request.user.is_authenticated():
if request.user.is_authenticated:
context['authorized_tenants'] = [
tenant for tenant in
request.user.authorized_tenants if tenant.enabled]

View File

@ -72,7 +72,7 @@ class ProfilerMiddleware(object):
@staticmethod
def is_authenticated(request):
return hasattr(request, "user") and request.user.is_authenticated()
return hasattr(request, "user") and request.user.is_authenticated
def is_enabled(self, request):
return self.is_authenticated(request) and settings.DEBUG

View File

@ -438,7 +438,7 @@ class TestCase(horizon_helpers.TestCase):
@staticmethod
def mock_rest_request(**args):
mock_args = {
'user.is_authenticated.return_value': True,
'user.is_authenticated': True,
'is_ajax.return_value': True,
'policy.check.return_value': True,
'body': ''

View File

@ -23,7 +23,6 @@ class RestUtilsTestCase(test.TestCase):
return 'ok'
request = self.mock_rest_request()
response = f(None, request)
request.user.is_authenticated.assert_called_once_with()
self.assertStatusCode(response, 200)
self.assertEqual("ok", response.json)
@ -33,7 +32,6 @@ class RestUtilsTestCase(test.TestCase):
return 'ok'
request = self.mock_rest_request()
response = f(None, request)
request.user.is_authenticated.assert_not_called()
self.assertStatusCode(response, 200)
self.assertEqual("ok", response.json)
@ -42,10 +40,9 @@ class RestUtilsTestCase(test.TestCase):
def f(self, request):
return 'ok'
request = self.mock_rest_request(**{
'user.is_authenticated.return_value': False
'user.is_authenticated': False
})
response = f(None, request)
request.user.is_authenticated.assert_called_once_with()
self.assertStatusCode(response, 401)
self.assertEqual("not logged in", response.json)
@ -111,7 +108,6 @@ class RestUtilsTestCase(test.TestCase):
return utils.CreatedResponse('/api/spam/spam123')
request = self.mock_rest_request()
response = f(None, request)
request.user.is_authenticated.assert_called_once_with()
self.assertStatusCode(response, 201)
self.assertEqual('/api/spam/spam123', response['location'])
self.assertEqual(b'', response.content)
@ -122,7 +118,6 @@ class RestUtilsTestCase(test.TestCase):
return utils.CreatedResponse('/api/spam/spam123', 'spam!')
request = self.mock_rest_request()
response = f(None, request)
request.user.is_authenticated.assert_called_once_with()
self.assertStatusCode(response, 201)
self.assertEqual('/api/spam/spam123', response['location'])
self.assertEqual("spam!", response.json)
@ -185,7 +180,6 @@ class JSONEncoderTestCase(test.TestCase):
request = self.mock_rest_request()
response = f(self, request)
request.user.is_authenticated.assert_called_once_with()
self.assertStatusCode(response, 200)
self.assertEqual('application/json', response['content-type'])
self.assertEqual(b'NaN', response.content)
@ -197,7 +191,6 @@ class JSONEncoderTestCase(test.TestCase):
request = self.mock_rest_request()
response = f(self, request)
request.user.is_authenticated.assert_called_once_with()
self.assertStatusCode(response, 200)
self.assertEqual('application/json', response['content-type'])
self.assertEqual(b'1e+999', response.content)
@ -209,7 +202,6 @@ class JSONEncoderTestCase(test.TestCase):
request = self.mock_rest_request()
response = f(self, request)
request.user.is_authenticated.assert_called_once_with()
self.assertStatusCode(response, 200)
self.assertEqual('application/json', response['content-type'])
self.assertEqual(b'-1e+999', response.content)

View File

@ -56,7 +56,7 @@ def get_user_home(user):
@django.views.decorators.vary.vary_on_cookie
def splash(request):
if not request.user.is_authenticated():
if not request.user.is_authenticated:
raise exceptions.NotAuthenticated()
response = shortcuts.redirect(horizon.get_user_home(request.user))