def process_request(self, request): # noqa: C901 """Process request for csrf checks. Args: request (object): The request object """ if is_no_auth(request): request.user = User('', '') return try: rh_auth_header, json_rh_auth = extract_header(request, self.header) username = json_rh_auth.get('identity', {}).get('user', {}).get('username') email = json_rh_auth.get('identity', {}).get('user', {}).get('email') account = json_rh_auth.get('identity', {}).get('account_number') is_admin = json_rh_auth.get('identity', {}).get('user', {}).get('is_org_admin') is_cost_management = json_rh_auth.get('entitlements', {}).get( 'cost_management', {}).get('is_entitled', False) is_hybrid_cloud = json_rh_auth.get('entitlements', {}).get( 'hybrid_cloud', {}).get('is_entitled', False) if not is_hybrid_cloud and not is_cost_management: raise PermissionDenied() except (KeyError, JSONDecodeError): logger.warning('Could not obtain identity on request.') return if (username and email and account): # Check for customer creation & user creation query_string = '' if request.META['QUERY_STRING']: query_string = '?{}'.format(request.META['QUERY_STRING']) stmt = (f'API: {request.path}{query_string}' f' -- ACCOUNT: {account} USER: {username}') logger.info(stmt) try: customer = Customer.objects.filter(account_id=account).get() except Customer.DoesNotExist: customer = IdentityHeaderMiddleware._create_customer(account) try: user = User.objects.get(username=username) except User.DoesNotExist: user = IdentityHeaderMiddleware._create_user( username, email, customer, request) user.identity_header = { 'encoded': rh_auth_header, 'decoded': json_rh_auth } user.admin = is_admin cache = caches['rbac'] user_access = cache.get(user.uuid) if not user_access: user_access = self._get_access(user) cache.set(user.uuid, user_access, self.rbac.cache_ttl) user.access = user_access request.user = user
def test_has_perm_auth_user_get_owned(self): """Test that an authenticated user can read owned objects.""" user = Mock(spec=User, is_authenticated=True, uuid=uuid4()) req = Mock(user=user) pref = Mock(spec=UserPreference, user=User(id=user.id, uuid=user.uuid)) o_perm = IsObjectOwner() result = o_perm.has_object_permission(request=req, view=None, obj=pref) self.assertTrue(result)
def process_request(self, request): # noqa: C901 """Process request for csrf checks. Args: request (object): The request object """ if is_no_auth(request): request.user = User('', '') return try: json_rh_auth = extract_header(request, self.header) username = json_rh_auth['identity']['user']['username'] email = json_rh_auth['identity']['user']['email'] account = json_rh_auth['identity']['account_number'] except (KeyError, JSONDecodeError): logger.warning('Could not obtain identity on request.') return if (username and email and account): # Check for customer creation & user creation query_string = '' if request.META['QUERY_STRING']: query_string = '?{}'.format(request.META['QUERY_STRING']) logger.info(f'API: {request.path}{query_string}' # pylint: disable=W1203 f' -- ACCOUNT: {account} USER: {username}') try: customer = Customer.objects.filter(account_id=account).get() except Customer.DoesNotExist: customer = IdentityHeaderMiddleware._create_customer(account) try: user = User.objects.get(username=username) except User.DoesNotExist: user = IdentityHeaderMiddleware._create_user( username, email, customer, request) request.user = user
def process_request(self, request): # noqa: C901 """Process request for csrf checks. Args: request (object): The request object """ connection.set_schema_to_public() if is_no_auth(request): request.user = User("", "") return try: rh_auth_header, json_rh_auth = extract_header(request, self.header) except (KeyError, JSONDecodeError): LOG.warning("Could not obtain identity on request.") return except binascii.Error as error: LOG.error("Error decoding authentication header: %s", str(error)) raise PermissionDenied() is_cost_management = json_rh_auth.get("entitlements", {}).get( "cost_management", {}).get("is_entitled", False) skip_entitlement = is_no_entitled(request) if not skip_entitlement and not is_cost_management: LOG.warning("User is not entitled for Cost Management.") raise PermissionDenied() account = json_rh_auth.get("identity", {}).get("account_number") user = json_rh_auth.get("identity", {}).get("user", {}) username = user.get("username") email = user.get("email") is_admin = user.get("is_org_admin") req_id = None if username and email and account: # Get request ID req_id = request.META.get("HTTP_X_RH_INSIGHTS_REQUEST_ID") # Check for customer creation & user creation query_string = "" if request.META["QUERY_STRING"]: query_string = "?{}".format(request.META["QUERY_STRING"]) stmt = { "method": request.method, "path": request.path + query_string, "request_id": req_id, "account": account, "username": username, "is_admin": is_admin, } LOG.info(stmt) try: if account not in IdentityHeaderMiddleware.customer_cache: IdentityHeaderMiddleware.customer_cache[ account] = Customer.objects.filter( account_id=account).get() LOG.debug(f"Customer added to cache: {account}") customer = IdentityHeaderMiddleware.customer_cache[account] except Customer.DoesNotExist: customer = IdentityHeaderMiddleware.create_customer(account) except OperationalError as err: LOG.error("IdentityHeaderMiddleware exception: %s", err) DB_CONNECTION_ERRORS_COUNTER.inc() return HttpResponseFailedDependency({ "source": "Database", "exception": err }) try: if username not in USER_CACHE: user = User.objects.get(username=username) USER_CACHE[username] = user LOG.debug(f"User added to cache: {username}") else: user = USER_CACHE[username] except User.DoesNotExist: user = IdentityHeaderMiddleware.create_user( username, email, customer, request) user.identity_header = { "encoded": rh_auth_header, "decoded": json_rh_auth } user.admin = is_admin user.req_id = req_id cache = caches["rbac"] user_access = cache.get(user.uuid) if not user_access: if settings.DEVELOPMENT and request.user.req_id == "DEVELOPMENT": # passthrough for DEVELOPMENT_IDENTITY env var. LOG.warning( "DEVELOPMENT is Enabled. Bypassing access lookup for user: %s", json_rh_auth) user_access = request.user.access else: try: user_access = self._get_access(user) except RbacConnectionError as err: return HttpResponseFailedDependency({ "source": "Rbac", "exception": err }) cache.set(user.uuid, user_access, self.rbac.cache_ttl) user.access = user_access request.user = user
def process_request(self, request): # noqa: C901 """Process request for csrf checks. Args: request (object): The request object """ connection.set_schema_to_public() if is_no_auth(request): request.user = User("", "") return try: rh_auth_header, json_rh_auth = extract_header(request, self.header) except (KeyError, JSONDecodeError): LOG.warning("Could not obtain identity on request.") return except binascii.Error as error: LOG.error("Error decoding authentication header: %s", str(error)) raise PermissionDenied() is_openshift = json_rh_auth.get("entitlements", {}).get("openshift", {}).get("is_entitled", False) if not is_openshift: raise PermissionDenied() account = json_rh_auth.get("identity", {}).get("account_number") user = json_rh_auth.get("identity", {}).get("user", {}) username = user.get("username") email = user.get("email") is_admin = user.get("is_org_admin") if username and email and account: # Get request ID req_id = request.META.get("HTTP_X_RH_INSIGHTS_REQUEST_ID") # Check for customer creation & user creation query_string = "" if request.META["QUERY_STRING"]: query_string = "?{}".format(request.META["QUERY_STRING"]) stmt = (f"{request.method}: {request.path}{query_string}" f" -- ACCOUNT: {account} USER: {username}" f" ORG_ADMIN: {is_admin} REQ_ID: {req_id}") LOG.info(stmt) try: customer = Customer.objects.filter(account_id=account).get() except Customer.DoesNotExist: customer = IdentityHeaderMiddleware._create_customer(account) except OperationalError as err: LOG.error("IdentityHeaderMiddleware exception: %s", err) DB_CONNECTION_ERRORS_COUNTER.inc() return HttpResponseFailedDependency({ "source": "Database", "exception": err }) try: user = User.objects.get(username=username) except User.DoesNotExist: user = IdentityHeaderMiddleware._create_user( username, email, customer, request) user.identity_header = { "encoded": rh_auth_header, "decoded": json_rh_auth } user.admin = is_admin user.req_id = req_id cache = caches["rbac"] user_access = cache.get(user.uuid) if not user_access: try: user_access = self._get_access(user) except RbacConnectionError as err: return HttpResponseFailedDependency({ "source": "Rbac", "exception": err }) cache.set(user.uuid, user_access, self.rbac.cache_ttl) user.access = user_access request.user = user
def process_request(self, request): # noqa: C901 """Process request for csrf checks. Args: request (object): The request object """ if is_no_auth(request): request.user = User('', '') return try: rh_auth_header, json_rh_auth = extract_header(request, self.header) except (KeyError, JSONDecodeError): LOG.warning('Could not obtain identity on request.') return except binascii.Error as error: LOG.error('Error decoding authentication header: %s', str(error)) raise PermissionDenied() is_openshift = (json_rh_auth.get('entitlements', {}).get('openshift', {}).get('is_entitled', False)) if not is_openshift: raise PermissionDenied() account = json_rh_auth.get('identity', {}).get('account_number') user = json_rh_auth.get('identity', {}).get('user', {}) username = user.get('username') email = user.get('email') is_admin = user.get('is_org_admin') if username and email and account: # Check for customer creation & user creation query_string = '' if request.META['QUERY_STRING']: query_string = '?{}'.format(request.META['QUERY_STRING']) stmt = (f'API: {request.path}{query_string}' f' -- ACCOUNT: {account} USER: {username}') LOG.info(stmt) try: customer = Customer.objects.filter(account_id=account).get() except Customer.DoesNotExist: customer = IdentityHeaderMiddleware._create_customer(account) except OperationalError as err: LOG.error('IdentityHeaderMiddleware exception: %s', err) DB_CONNECTION_ERRORS_COUNTER.inc() return HttpResponseFailedDependency({ 'source': 'Database', 'exception': err }) try: user = User.objects.get(username=username) except User.DoesNotExist: user = IdentityHeaderMiddleware._create_user( username, email, customer, request) user.identity_header = { 'encoded': rh_auth_header, 'decoded': json_rh_auth } user.admin = is_admin cache = caches['rbac'] user_access = cache.get(user.uuid) if not user_access: try: user_access = self._get_access(user) except RbacConnectionError as err: return HttpResponseFailedDependency({ 'source': 'Rbac', 'exception': err }) cache.set(user.uuid, user_access, self.rbac.cache_ttl) user.access = user_access request.user = user