From 1a252cb5e87d0ca1f6a4bea573ca472b64fa33de Mon Sep 17 00:00:00 2001 From: Akihiro Motoki Date: Tue, 12 Dec 2017 13:48:55 +0900 Subject: [PATCH] django2: is_authenticated/is_anonymous is now property only https://docs.djangoproject.com/en/2.0/releases/1.10/#user-is-auth-anon-deprecation blueprint django2-support Change-Id: I57a39417f0595eae8d1c06d7e61d0a67078bb231 --- horizon/decorators.py | 4 +- horizon/middleware/base.py | 2 +- horizon/middleware/operation_log.py | 2 +- openstack_auth/backend.py | 2 +- openstack_auth/user.py | 59 +++++-------------- openstack_auth/views.py | 4 +- openstack_dashboard/api/rest/utils.py | 2 +- openstack_dashboard/context_processors.py | 2 +- .../contrib/developer/profiler/middleware.py | 2 +- openstack_dashboard/test/helpers.py | 2 +- .../test/unit/api/rest/test_utils.py | 10 +--- openstack_dashboard/views.py | 2 +- 12 files changed, 27 insertions(+), 66 deletions(-) diff --git a/horizon/decorators.py b/horizon/decorators.py index dd4fe776b0..372e0c5ed6 100644 --- a/horizon/decorators.py +++ b/horizon/decorators.py @@ -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") diff --git a/horizon/middleware/base.py b/horizon/middleware/base.py index 65d8af7819..aa67c29042 100644 --- a/horizon/middleware/base.py +++ b/horizon/middleware/base.py @@ -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 diff --git a/horizon/middleware/operation_log.py b/horizon/middleware/operation_log.py index 2eb1efcd3b..a1673b83d1 100644 --- a/horizon/middleware/operation_log.py +++ b/horizon/middleware/operation_log.py @@ -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): diff --git a/openstack_auth/backend.py b/openstack_auth/backend.py index 5648cc2167..5be15e8106 100644 --- a/openstack_auth/backend.py +++ b/openstack_auth/backend.py @@ -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. diff --git a/openstack_auth/user.py b/openstack_auth/user.py index 063648bf8c..23b6c4ced7 100644 --- a/openstack_auth/user.py +++ b/openstack_auth/user.py @@ -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( diff --git a/openstack_auth/views.py b/openstack_auth/views.py index 769e594650..1998a1437d 100644 --- a/openstack_auth/views.py +++ b/openstack_auth/views.py @@ -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 diff --git a/openstack_dashboard/api/rest/utils.py b/openstack_dashboard/api/rest/utils.py index 2af037987b..6f2fb8a165 100644 --- a/openstack_dashboard/api/rest/utils.py +++ b/openstack_dashboard/api/rest/utils.py @@ -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) diff --git a/openstack_dashboard/context_processors.py b/openstack_dashboard/context_processors.py index db43711846..1bed8a50f6 100644 --- a/openstack_dashboard/context_processors.py +++ b/openstack_dashboard/context_processors.py @@ -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] diff --git a/openstack_dashboard/contrib/developer/profiler/middleware.py b/openstack_dashboard/contrib/developer/profiler/middleware.py index ba55251287..9268774cc7 100644 --- a/openstack_dashboard/contrib/developer/profiler/middleware.py +++ b/openstack_dashboard/contrib/developer/profiler/middleware.py @@ -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 diff --git a/openstack_dashboard/test/helpers.py b/openstack_dashboard/test/helpers.py index b1f54017e5..01cf8610e1 100644 --- a/openstack_dashboard/test/helpers.py +++ b/openstack_dashboard/test/helpers.py @@ -433,7 +433,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': '' diff --git a/openstack_dashboard/test/unit/api/rest/test_utils.py b/openstack_dashboard/test/unit/api/rest/test_utils.py index 68294388f9..342718fc7a 100644 --- a/openstack_dashboard/test/unit/api/rest/test_utils.py +++ b/openstack_dashboard/test/unit/api/rest/test_utils.py @@ -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) diff --git a/openstack_dashboard/views.py b/openstack_dashboard/views.py index 22553017e3..60ac9b31c2 100644 --- a/openstack_dashboard/views.py +++ b/openstack_dashboard/views.py @@ -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))