Skip to content

Commit

Permalink
Fix SonarCloud code quality issues
Browse files Browse the repository at this point in the history
No-Issue
  • Loading branch information
cutwater committed Sep 17, 2024
1 parent 44b6ccf commit 3cfeec9
Show file tree
Hide file tree
Showing 17 changed files with 52 additions and 62 deletions.
17 changes: 8 additions & 9 deletions galaxy_ng/app/access_control/access_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,10 @@ def scope_queryset(self, view, qs):
# if access_policy := self.get_access_policy(view):
if access_policy.queryset_scoping:
scope = access_policy.queryset_scoping["function"]
if scope == "scope_queryset" or not (function := getattr(self, scope, None)):
if scope == "scope_queryset" or not (func := getattr(self, scope, None)):
return qs
kwargs = access_policy.queryset_scoping.get("parameters") or {}
qs = function(view, qs, **kwargs)
qs = func(view, qs, **kwargs)
return qs

# Define global conditions here
Expand Down Expand Up @@ -333,9 +333,8 @@ def has_ansible_repo_perms(self, request, view, action, permission):

repo = obj.repository.cast()

if permission == "ansible.view_ansiblerepository":
if not repo.private:
return True
if permission == "ansible.view_ansiblerepository" and not repo.private:
return True

return request.user.has_perm(permission, repo)

Expand Down Expand Up @@ -605,15 +604,15 @@ class AIDenyIndexAccessPolicy(AccessPolicyBase):

def can_edit_ai_deny_index(self, request, view, permission):
"""This permission applies to Namespace or LegacyNamespace on ai_deny_index/."""
object = view.get_object()
obj = view.get_object()
has_permission = False
if isinstance(object, models.Namespace):
if isinstance(obj, models.Namespace):
has_permission = has_model_or_object_permissions(
request.user,
"galaxy.change_namespace",
object
obj
)
elif isinstance(object, LegacyNamespace):
elif isinstance(obj, LegacyNamespace):
has_permission = LegacyAccessPolicy().is_namespace_owner(
request, view, permission
)
Expand Down
2 changes: 1 addition & 1 deletion galaxy_ng/app/api/ui/v1/views/landing_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def get(self, request, *args, **kwargs):
"shape": {
"title": "Learn about namespaces",
"description": (
"Organize collections content into " "namespaces users can access."
"Organize collections content into namespaces users can access."
),
"link": {
"title": "Learn more",
Expand Down
21 changes: 14 additions & 7 deletions galaxy_ng/app/api/ui/v1/views/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,8 @@ def get_queryset(self):

def get_search_results(self, filter_params, sort):
"""Validates filter_params, builds each queryset and then unionize and apply filters."""
type = filter_params.get("type", "").lower()
if type not in ("role", "collection", ""):
type_ = filter_params.get("type", "").lower()
if type_ not in ("role", "collection", ""):
raise ValidationError("'type' must be ['collection', 'role']")

search_type = filter_params.get("search_type", DEFAULT_SEARCH_TYPE)
Expand All @@ -171,7 +171,14 @@ def get_search_results(self, filter_params, sort):

collections = self.get_collection_queryset(query=query)
roles = self.get_role_queryset(query=query)
result_qs = self.filter_and_sort(collections, roles, filter_params, sort, type, query=query)
result_qs = self.filter_and_sort(
collections,
roles,
filter_params,
sort,
type_,
query=query
)
return result_qs

def get_filter_params(self, request):
Expand Down Expand Up @@ -268,7 +275,7 @@ def get_role_queryset(self, query=None):
).values(*QUERYSET_VALUES)
return qs

def filter_and_sort(self, collections, roles, filter_params, sort, type="", query=None):
def filter_and_sort(self, collections, roles, filter_params, sort, type_="", query=None):
"""Apply filters individually on each queryset and then combine to sort."""
facets = {}
if deprecated := filter_params.get("deprecated"):
Expand Down Expand Up @@ -297,7 +304,7 @@ def filter_and_sort(self, collections, roles, filter_params, sort, type="", quer
if query:
collections = collections.filter(search=query)
roles = roles.filter(search=query)
elif keywords := filter_params.get("keywords"): # search_type=sql
elif keywords := filter_params.get("keywords"):
query = (
Q(name__icontains=keywords)
| Q(namespace_name__icontains=keywords)
Expand All @@ -308,9 +315,9 @@ def filter_and_sort(self, collections, roles, filter_params, sort, type="", quer
collections = collections.filter(query)
roles = roles.filter(query)

if type.lower() == "role":
if type_.lower() == "role":
qs = roles.order_by(*sort)
elif type.lower() == "collection":
elif type_.lower() == "collection":
qs = collections.order_by(*sort)
else:
qs = collections.union(roles, all=True).order_by(*sort)
Expand Down
1 change: 0 additions & 1 deletion galaxy_ng/app/api/ui/v1/viewsets/my_synclist.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ def get_queryset(self):
return get_objects_for_user(
self.request.user,
"galaxy.change_synclist",
# any_perm=True,
qs=models.SyncList.objects.all(),
)

Expand Down
14 changes: 8 additions & 6 deletions galaxy_ng/app/api/ui/v2/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,19 @@ def has_object_permission(self, request, view, obj):
return False

# we can't allow the last superuser to get demoted
if request.data.get('is_superuser') is False:
if User.objects.filter(is_superuser=True).count() == 1 and obj.is_superuser:
return False
if (
request.data.get('is_superuser') is False
and User.objects.filter(is_superuser=True).count() == 1
and obj.is_superuser
):
return False

# superuser can set the value to True or False
if request.user.is_superuser:
return True

# user can set themself only to False
if request.user == obj:
if request.data.get('is_superuser') is False:
return True
if request.user == obj and request.data.get('is_superuser') is False:
return True

return False
1 change: 0 additions & 1 deletion galaxy_ng/app/api/ui/v2/serializers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from django.contrib.auth import password_validation
Expand Down
1 change: 0 additions & 1 deletion galaxy_ng/app/api/ui/v2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ class UserViewSet(BaseViewSet):
queryset = User.objects.all().order_by('id')
filterset_class = UserViewFilter
permission_classes = [ComplexUserPermissions]
# permission_classes = [IsSuperUserOrReadOnly]

def get_serializer_class(self):
# FIXME - a single serializer for this viewset
Expand Down
2 changes: 1 addition & 1 deletion galaxy_ng/app/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

LOCALHOST = "localhost"
FILENAME_REGEXP = re.compile(
r"^(?P<namespace>\w+)-(?P<name>\w+)-" r"(?P<version>[0-9a-zA-Z.+-]+)\.tar\.gz$"
r"^(?P<namespace>\w+)-(?P<name>\w+)-(?P<version>[0-9a-zA-Z.+-]+)\.tar\.gz$"
)
VERSION_REGEXP = re.compile(r"""
^
Expand Down
6 changes: 2 additions & 4 deletions galaxy_ng/app/api/v1/filtersets.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class LegacyNamespaceFilter(filterset.FilterSet):
sort = filters.OrderingFilter(
fields=(
('created', 'created'),
('name', 'name')
('name', 'name'),
)
)

Expand Down Expand Up @@ -63,14 +63,12 @@ class LegacyUserFilter(filterset.FilterSet):

sort = filters.OrderingFilter(
fields=(
# ('created', 'created'),
('username', 'username')
('username', 'username'),
)
)

class Meta:
model = User
# fields = ['created', 'username']
fields = ['username']

def username_filter(self, queryset, name, value):
Expand Down
4 changes: 1 addition & 3 deletions galaxy_ng/app/api/v1/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,6 @@ class LegacyUserSerializer(serializers.ModelSerializer):
summary_fields = serializers.SerializerMethodField()
date_joined = serializers.SerializerMethodField()
created = serializers.SerializerMethodField()
# active = serializers.SerializerMethodField()
full_name = serializers.SerializerMethodField()
url = serializers.SerializerMethodField()
username = serializers.SerializerMethodField()
Expand Down Expand Up @@ -158,7 +157,6 @@ def get_created(self, obj):
return self.get_date_joined(obj)

def get_date_joined(self, obj):
# return obj.created
if hasattr(obj, '_created'):
return obj._created
if hasattr(obj, 'date_joined'):
Expand Down Expand Up @@ -557,7 +555,7 @@ class LegacySyncSerializer(serializers.Serializer):
class Meta:
model = None
fields = [
'baseurl'
'baseurl',
'github_user',
'role_name',
'role_version',
Expand Down
6 changes: 1 addition & 5 deletions galaxy_ng/app/api/v1/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
)


# logger = logging.getLogger(__name__)
logger = logging.getLogger("galaxy_ng.app.api.v1.tasks.legacy_role_import")


Expand Down Expand Up @@ -158,7 +157,7 @@ def do_git_checkout(clone_url, checkout_path, github_reference):
)
if pid.returncode != 0:
error = pid.stdout.decode('utf-8')
logger.error('{cmd} failed: {error}')
logger.error(f'{cmd} failed: {error}')
raise Exception(f'{cmd} failed')

last_commit = [x for x in gitrepo.iter_commits()][0]
Expand Down Expand Up @@ -500,7 +499,6 @@ def legacy_role_import(
'imported': datetime.datetime.now().isoformat(),
'clone_url': clone_url,
'tags': galaxy_info.get("galaxy_tags", []),
'commit': github_commit,
'github_user': real_github_user,
'github_repo': real_github_repo,
'github_branch': github_reference,
Expand Down Expand Up @@ -627,7 +625,6 @@ def legacy_sync_from_upstream(
rkey = (github_user, role_name)
remote_id = rdata['id']
role_versions = rversions[:]
# github_user = rdata['github_user']
github_repo = rdata['github_repo']
github_branch = rdata['github_branch']
clone_url = f'https://github.com/{github_user}/{github_repo}'
Expand All @@ -637,7 +634,6 @@ def legacy_sync_from_upstream(
commit_msg = rdata.get('commit_message')
commit_url = rdata.get('commit_url')
issue_tracker = rdata.get('issue_tracker_url', clone_url + '/issues')
# role_versions = sfields.get('versions', [])
role_description = rdata.get('description')
role_license = rdata.get('license')
role_readme = rdata.get('readme')
Expand Down
1 change: 0 additions & 1 deletion galaxy_ng/app/api/v1/viewsets/namespaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ class LegacyNamespaceOwnersViewSet(viewsets.GenericViewSet, mixins.ListModelMixi
authentication_classes = GALAXY_AUTHENTICATION_CLASSES

def get_queryset(self):
# return get_object_or_404(LegacyNamespace, pk=self.kwargs["pk"]).owners.all()
ns = get_object_or_404(LegacyNamespace, pk=self.kwargs["pk"])
if ns.namespace:
return get_v3_namespace_owners(ns.namespace)
Expand Down
4 changes: 1 addition & 3 deletions galaxy_ng/app/api/v1/viewsets/roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,7 @@ def list(self, request):
counter.save()
except DatabaseInternalError as e:
# Fail gracefully if the database is in read-only mode.
if "read-only" in str(e):
pass
else:
if "read-only" not in str(e):
raise e

return super().list(request)
Expand Down
16 changes: 9 additions & 7 deletions galaxy_ng/app/api/v1/viewsets/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,18 +73,20 @@ def get_task(self, request, id=None):
}

# generate a message for the response
# FIXME(cutwater): Begin of the code that does nothing
msg = ''
if state == 'SUCCESS':
msg = 'role imported successfully'
elif state == 'RUNNING':
msg = 'running'
if this_task.error:
if this_task.error.get('traceback'):
msg = (
this_task.error['description']
+ '\n'
+ this_task.error['traceback']
)

if this_task.error and this_task.error.get('traceback'):
msg = (
this_task.error['description']
+ '\n'
+ this_task.error['traceback']
)
# FIXME(cutwater): End of the code that does nothing

task_messages = []

Expand Down
5 changes: 0 additions & 5 deletions galaxy_ng/app/common/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,6 @@ def preprocess_debug_logger(endpoints, **kwargs):
path, path_regex, method, callback)

return endpoints
# return [
# (path, path_regex, method, callback) for path, path_regex, method, callback in endpoints
# if log.debug('path=%s, path_regex=%s, method=%s, callback=%s',
# path, path_regex, method, callback)
# ]


def preprocess_exclude_endpoints(endpoints, **kwargs):
Expand Down
6 changes: 0 additions & 6 deletions galaxy_ng/app/dynaconf_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ def configure_keycloak(settings: Dynaconf) -> Dict[str, Any]:
"SOCIAL_AUTH_LOGIN_REDIRECT_URL", default="/ui/"
)
data["SOCIAL_AUTH_JSONFIELD_ENABLED"] = True
# data["SOCIAL_AUTH_JSONFIELD_CUSTOM"] = "django.db.models.JSONField"
data["SOCIAL_AUTH_URL_NAMESPACE"] = "social"
data["SOCIAL_AUTH_KEYCLOAK_EXTRA_DATA"] = [
("refresh_token", "refresh_token"),
Expand Down Expand Up @@ -209,11 +208,6 @@ def configure_socialauth(settings: Dynaconf) -> Dict[str, Any]:

data = {}

# SOCIAL_AUTH_GITHUB_BASE_URL = \
# settings.get('SOCIAL_AUTH_GITHUB_BASE_URL', default='https://github.com')
# SOCIAL_AUTH_GITHUB_API_URL = \
# settings.get('SOCIAL_AUTH_GITHUB_BASE_URL', default='https://api.github.com')

SOCIAL_AUTH_GITHUB_KEY = settings.get("SOCIAL_AUTH_GITHUB_KEY", default=None)
SOCIAL_AUTH_GITHUB_SECRET = settings.get("SOCIAL_AUTH_GITHUB_SECRET", default=None)

Expand Down
7 changes: 6 additions & 1 deletion galaxy_ng/app/tasks/namespaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,14 @@ def _download_avatar(url, namespace_name):
try:
downloader = HttpDownloader(url, session=session)
img = downloader.fetch()
except: # noqa
except Exception: # noqa
# FIXME(cutwater): Handling base exception class is a bad practice, as well as ignoring it.
return
finally:
# FIXME(cutwater): The `asyncio.get_event_loop()` must not be used in the code.
# It is deprecated and it's original behavior may change in future.
# Users must not rely on the original behavior.
# https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop
asyncio.get_event_loop().run_until_complete(session.close())

# Limit size of the avatar to avoid memory issues when validating it
Expand Down

0 comments on commit 3cfeec9

Please sign in to comment.