def set_user_from_request(self, request: HttpRequest, realm='') -> 'DjangoAuditLogger': user = request.user if hasattr(request, 'user') else None roles = list(user.groups.values_list('name', flat=True)) if user else [] self.set_user( authenticated=user.is_authenticated if user else False, provider=request.session.get('_auth_user_backend', '') if hasattr(request, 'session') else '', realm=realm, email=getattr(user, 'email', '') if user else '', roles=roles, ip=get_client_ip(request) ) return self
def test_get_client_ip_exception(self, mocked_logger): self.assertEqual(get_client_ip(request=None), 'failed to get ip') mocked_logger.assert_called_with('Failed to get ip for audit log', exc_info=True)
def test_get_client_ip(self): request = HttpRequest() request.META['REMOTE_ADDR'] = '2.3.4.5' self.assertEqual(get_client_ip(request), '2.3.4.5')
def test_get_client_ip_forwarded(self): request = HttpRequest() request.META['HTTP_X_FORWARDED_FOR'] = '1.2.3.4' self.assertEqual(get_client_ip(request), '1.2.3.4')