Skip to content

Commit

Permalink
Various SAST fixes (#7644)
Browse files Browse the repository at this point in the history
* cleanup auth

* clean Unexpected empty object pattern

* clenaup empty object patterns

* fix identical sub-expressions

* fix missing title on iframe

* Do not pass children as props

* update node assigment

* fix typing

* fix variables that shadow builtins

* revert StylishText change
  • Loading branch information
matmair authored Jul 17, 2024
1 parent 234b0ed commit 547fa17
Show file tree
Hide file tree
Showing 16 changed files with 38 additions and 34 deletions.
14 changes: 9 additions & 5 deletions src/backend/InvenTree/plugin/api.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""API for the plugin app."""

from typing import Optional

from django.core.exceptions import ValidationError
from django.urls import include, path, re_path
from django.utils.translation import gettext_lazy as _
Expand Down Expand Up @@ -266,7 +268,9 @@ class PluginSettingList(ListAPI):
filterset_fields = ['plugin__active', 'plugin__key']


def check_plugin(plugin_slug: str, plugin_pk: int) -> InvenTreePlugin:
def check_plugin(
plugin_slug: Optional[str], plugin_pk: Optional[int]
) -> InvenTreePlugin:
"""Check that a plugin for the provided slug exists and get the config.
Args:
Expand All @@ -286,16 +290,16 @@ def check_plugin(plugin_slug: str, plugin_pk: int) -> InvenTreePlugin:
raise NotFound(detail='Plugin not specified')

# Define filter
filter = {}
filters = {}
if plugin_slug:
filter['key'] = plugin_slug
filters['key'] = plugin_slug
elif plugin_pk:
filter['pk'] = plugin_pk
filters['pk'] = plugin_pk
ref = plugin_slug or plugin_pk

# Check that the 'plugin' specified is valid
try:
plugin_cgf = PluginConfig.objects.filter(**filter).first()
plugin_cgf = PluginConfig.objects.filter(**filters).first()
except PluginConfig.DoesNotExist:
raise NotFound(detail=f"Plugin '{ref}' not installed")

Expand Down
8 changes: 4 additions & 4 deletions src/backend/InvenTree/report/templatetags/barcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def qrcode(data, **kwargs):
fill_color = kwargs.pop('fill_color', 'black')
back_color = kwargs.pop('back_color', 'white')

format = kwargs.pop('format', 'PNG')
img_format = kwargs.pop('format', 'PNG')

params.update(**kwargs)

Expand All @@ -51,15 +51,15 @@ def qrcode(data, **kwargs):
qri = qr.make_image(fill_color=fill_color, back_color=back_color)

# Render to byte-encoded image
return image_data(qri, fmt=format)
return image_data(qri, fmt=img_format)


@register.simple_tag()
def barcode(data, barcode_class='code128', **kwargs):
"""Render a barcode."""
constructor = python_barcode.get_barcode_class(barcode_class)

format = kwargs.pop('format', 'PNG')
img_format = kwargs.pop('format', 'PNG')

data = str(data).zfill(constructor.digits)

Expand All @@ -70,4 +70,4 @@ def barcode(data, barcode_class='code128', **kwargs):
image = barcode_image.render(writer_options=kwargs)

# Render to byte-encoded image
return image_data(image, fmt=format)
return image_data(image, fmt=img_format)
4 changes: 2 additions & 2 deletions src/backend/InvenTree/templates/js/dynamic/nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ function generateTreeStructure(data, options) {
};

if (options.processNode) {
node = options.processNode(node);
data[data.indexOf(node)] = options.processNode(node);
}
}

Expand All @@ -188,7 +188,7 @@ function generateTreeStructure(data, options) {
if (node.state.expanded) {
while (node.parent != null) {
nodes[node.parent].state.expanded = true;
node = nodes[node.parent];
data[data.indexOf(node)] = nodes[node.parent];
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ export const PdfPreviewComponent: PreviewAreaComponent = forwardRef(
<Trans>Preview not available, click "Reload Preview".</Trans>
</div>
)}
{pdfUrl && <iframe src={pdfUrl} width="100%" height="100%" />}
{pdfUrl && (
<iframe src={pdfUrl} width="100%" height="100%" title="PDF Preview" />
)}
</>
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/src/forms/PartForms.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export function usePartFields({
/**
* Construct a set of fields for creating / editing a PartCategory instance
*/
export function partCategoryFields({}: {}): ApiFormFieldSet {
export function partCategoryFields(): ApiFormFieldSet {
let fields: ApiFormFieldSet = {
parent: {
description: t`Parent part category`,
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/src/forms/StockForms.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -902,7 +902,7 @@ export function useDeleteStockItem(props: StockOperationProps) {
});
}

export function stockLocationFields({}: {}): ApiFormFieldSet {
export function stockLocationFields(): ApiFormFieldSet {
let fields: ApiFormFieldSet = {
parent: {
description: t`Parent stock location`,
Expand Down
7 changes: 3 additions & 4 deletions src/frontend/src/functions/auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { NavigateFunction } from 'react-router-dom';

import { api, setApiDefaults } from '../App';
import { ApiEndpoints } from '../enums/ApiEndpoints';
import { apiUrl, useServerApiState } from '../states/ApiState';
import { apiUrl } from '../states/ApiState';
import { useLocalState } from '../states/LocalState';
import { useUserState } from '../states/UserState';
import { fetchGlobalStates } from '../states/states';
Expand Down Expand Up @@ -47,8 +47,7 @@ function post(path: string, params: any, method = 'post') {
*/
export const doBasicLogin = async (username: string, password: string) => {
const { host } = useLocalState.getState();
const { clearUserState, setToken, fetchUserState, isLoggedIn } =
useUserState.getState();
const { clearUserState, setToken, fetchUserState } = useUserState.getState();

if (username.length == 0 || password.length == 0) {
return;
Expand Down Expand Up @@ -96,7 +95,7 @@ export const doBasicLogin = async (username: string, password: string) => {

if (result) {
await fetchUserState();
await fetchGlobalStates();
fetchGlobalStates();
} else {
clearUserState();
}
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/src/pages/Index/Playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
} from '../../hooks/UseForm';

// Generate some example forms using the modal API forms interface
const fields = partCategoryFields({});
const fields = partCategoryFields();

function ApiFormsPlayground() {
const editCategory = useEditApiFormModal({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export function SecurityContent() {
);
}

function EmailContent({}: {}) {
function EmailContent() {
const [value, setValue] = useState<string>('');
const [newEmailValue, setNewEmailValue] = useState('');
const [user] = useUserState((state) => [state.user]);
Expand Down Expand Up @@ -321,7 +321,7 @@ function SsoContent({ dataProvider }: { dataProvider: any | undefined }) {
);
}

function MfaContent({}: {}) {
function MfaContent() {
return (
<>
MFA Details
Expand Down
4 changes: 2 additions & 2 deletions src/frontend/src/pages/part/CategoryDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import { PartListTable } from '../../tables/part/PartTable';
*
* Note: If no category ID is supplied, this acts as the top-level part category page
*/
export default function CategoryDetail({}: {}) {
export default function CategoryDetail() {
const { id: _id } = useParams();
const id = useMemo(
() => (!isNaN(parseInt(_id || '')) ? _id : undefined),
Expand Down Expand Up @@ -158,7 +158,7 @@ export default function CategoryDetail({}: {}) {
url: ApiEndpoints.category_list,
pk: id,
title: t`Edit Part Category`,
fields: partCategoryFields({}),
fields: partCategoryFields(),
onFormSuccess: refreshInstance
});

Expand Down
7 changes: 3 additions & 4 deletions src/frontend/src/pages/part/pricing/PricingPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,9 @@ function AccordionControl(props: AccordionControlProps) {
return (
<Box style={{ display: 'flex', alignItems: 'center' }}>
{props.disabled && (
<Tooltip
label={t`No data available`}
children={<IconAlertCircle size="1rem" color="gray" />}
/>
<Tooltip label={t`No data available`}>
<IconAlertCircle size="1rem" color="gray" />
</Tooltip>
)}
<Accordion.Control
{...props}
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/src/pages/stock/LocationDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ export default function Stock() {
url: ApiEndpoints.stock_location_list,
pk: id,
title: t`Edit Stock Location`,
fields: stockLocationFields({}),
fields: stockLocationFields(),
onFormSuccess: refreshInstance
});

Expand Down
2 changes: 1 addition & 1 deletion src/frontend/src/tables/InvenTreeTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,7 @@ export function InvenTreeTable<T = any>({
enableLabels={tableProps.enableLabels}
enableReports={tableProps.enableReports}
/>
{(tableProps.barcodeActions?.length ?? 0 > 0) && (
{(tableProps.barcodeActions?.length ?? 0) > 0 && (
<ButtonMenu
key="barcode-actions"
icon={<IconBarcode />}
Expand Down
4 changes: 2 additions & 2 deletions src/frontend/src/tables/part/PartCategoryTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export function PartCategoryTable({ parentId }: { parentId?: any }) {
const newCategory = useCreateApiFormModal({
url: ApiEndpoints.category_list,
title: t`New Part Category`,
fields: partCategoryFields({}),
fields: partCategoryFields(),
initialData: {
parent: parentId
},
Expand All @@ -91,7 +91,7 @@ export function PartCategoryTable({ parentId }: { parentId?: any }) {
url: ApiEndpoints.category_list,
pk: selectedCategory,
title: t`Edit Part Category`,
fields: partCategoryFields({}),
fields: partCategoryFields(),
onFormSuccess: (record: any) => table.updateRecord(record)
});

Expand Down
2 changes: 1 addition & 1 deletion src/frontend/src/tables/part/PartCategoryTemplateTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { TableFilter } from '../Filter';
import { InvenTreeTable } from '../InvenTreeTable';
import { RowDeleteAction, RowEditAction } from '../RowActions';

export default function PartCategoryTemplateTable({}: {}) {
export default function PartCategoryTemplateTable() {
const table = useTable('part-category-parameter-templates');
const user = useUserState();

Expand Down
4 changes: 2 additions & 2 deletions src/frontend/src/tables/stock/StockLocationTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export function StockLocationTable({ parentId }: { parentId?: any }) {
const newLocation = useCreateApiFormModal({
url: ApiEndpoints.stock_location_list,
title: t`Add Stock Location`,
fields: stockLocationFields({}),
fields: stockLocationFields(),
initialData: {
parent: parentId
},
Expand All @@ -112,7 +112,7 @@ export function StockLocationTable({ parentId }: { parentId?: any }) {
url: ApiEndpoints.stock_location_list,
pk: selectedLocation,
title: t`Edit Stock Location`,
fields: stockLocationFields({}),
fields: stockLocationFields(),
onFormSuccess: (record: any) => table.updateRecord(record)
});

Expand Down

0 comments on commit 547fa17

Please sign in to comment.