8000 fix(admin-ui): enable no-unnecessary-condition ESLint rule by pierluigilenoci · Pull Request #48218 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions js/apps/account-ui/src/api/representations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ export interface CredentialMetadataRepresentationMessage {
}

export interface CredentialMetadataRepresentation {
infoMessage: CredentialMetadataRepresentationMessage;
infoProperties: CredentialMetadataRepresentationMessage[];
warningMessageTitle: CredentialMetadataRepresentationMessage;
warningMessageDescription: CredentialMetadataRepresentationMessage;
infoMessage?: CredentialMetadataRepresentationMessage;
infoProperties?: CredentialMetadataRepresentationMessage[];
warningMessageTitle?: CredentialMetadataRepresentationMessage;
warningMessageDescription?: CredentialMetadataRepresentationMessage;
credential: CredentialRepresentation;
}

Expand Down
2 changes: 1 addition & 1 deletion js/apps/account-ui/src/organizations/Organizations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const Organizations = () => {
const { t } = useTranslation();
const context = useEnvironment<AccountEnvironment>();

const [userOrgs, setUserOrgs] = useState<OrganizationRepresentation[]>([]);
const [userOrgs, setUserOrgs] = useState<OrganizationRepresentation[]>();

usePromise(
(signal) => getUserOrganizations({ signal, context }),
Expand Down
4 changes: 2 additions & 2 deletions js/apps/account-ui/src/personal-info/PersonalInfo.tsx
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ export const PersonalInfo = () => {
}

const allFieldsReadOnly = () =>
userProfileMetadata?.attributes
?.map((a) => a.readOnly)
userProfileMetadata.attributes
.map((a) => a.readOnly)
.reduce((p, c) => p && c, true);

const {
Expand Down
6 changes: 3 additions & 3 deletions js/apps/admin-ui/src/PageNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export const PageNav = () => {
style={{ wordWrap: "break-word" }}
>
<span data-testid="currentRealm">
{resolveDisplayName(t, realmRepresentation?.displayName, realm)}
{resolveDisplayName(t, realmRepresentation.displayName, realm)}
</span>{" "}
<Label color="blue">{t("currentRealm")}</Label>
</h2>
Expand All @@ -127,7 +127,7 @@ export const PageNav = () => {
{showManage && (
<NavGroup aria-label={t("manage")} title={t("manage")}>
{isFeatureEnabled(Feature.Organizations) &&
realmRepresentation?.organizationsEnabled && (
realmRepresentation.organizationsEnabled && (
<LeftNav title="organizations" path="/organizations" />
)}
<LeftNav title="clients" path="/clients" />
Expand All @@ -145,7 +145,7 @@ export const PageNav = () => {
<LeftNav title="realmSettings" path="/realm-settings" />
<LeftNav title="authentication" path="/authentication" />
{isFeatureEnabled(Feature.AdminFineGrainedAuthzV2) &&
realmRepresentation?.adminPermissionsEnabled && (
realmRepresentation.adminPermissionsEnabled && (
<LeftNav title="permissions" path="/permissions" />
)}
<LeftNav title="identityProviders" path="/identity-providers" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { fetchWithError } from "@keycloak/keycloak-admin-client";
import {
KeycloakDataTable,
KeycloakSpinner,
ListEmptyState,
useAlerts,
} from "@keycloak/keycloak-ui-shared";
Expand Down Expand Up @@ -67,7 +66,7 @@
export default function AuthenticationSection() {
const { adminClient } = useAdminClient();
const { t } = useTranslation();
const { realm: realmName, realmRepresentation: realm } = useRealm();
const { realm: realmName } = useRealm();
const [key, setKey] = useState(0);
const refresh = () => setKey(key + 1);
const { addAlert, addError } = useAlerts();
Expand Down Expand Up @@ -99,11 +98,11 @@
};

const useTab = (tab: AuthenticationTab) =>
useRoutableTab(toAuthentication({ realm: realmName, tab }));

Check warning on line 101 in js/apps/admin-ui/src/authentication/AuthenticationSection.tsx

View workflow job for this annotation

GitHub Actions / Admin UI

Hooks must be called at the top level in the body of a function component or custom hook, and may not be called within function expressions. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)

const flowsTab = useTab("flows");

Check warning on line 103 in js/apps/admin-ui/src/authentication/AuthenticationSection.tsx

View workflow job for this annotation

GitHub Actions / Admin UI

Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks
const requiredActionsTab = useTab("required-actions");

Check warning on line 104 in js/apps/admin-ui/src/authentication/AuthenticationSection.tsx

View workflow job for this annotation

GitHub Actions / Admin UI

Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks
const policiesTab = useTab("policies");

Check warning on line 105 in js/apps/admin-ui/src/authentication/AuthenticationSection.tsx

View workflow job for this annotation

GitHub Actions / Admin UI

Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks

const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
titleKey: "deleteConfirmFlow",
Expand All @@ -128,8 +127,6 @@
},
});

if (!realm) return <KeycloakSpinner />;

return (
<>
<DeleteConfirm />
Expand Down
5 changes: 0 additions & 5 deletions js/apps/admin-ui/src/authentication/policies/Policies.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Tab, Tabs, TabTitleText } from "@patternfly/react-core";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { KeycloakSpinner } from "@keycloak/keycloak-ui-shared";
import { useRealm } from "../../context/realm-context/RealmContext";
import { CibaPolicy } from "./CibaPolicy";
import { OtpPolicy } from "./OtpPolicy";
Expand All @@ -13,10 +12,6 @@ export const Policies = () => {
const [subTab, setSubTab] = useState(1);
const { realmRepresentation: realm, refresh } = useRealm();

if (!realm) {
return <KeycloakSpinner />;
}

return (
<Tabs
activeKey={subTab}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ export const WebauthnPolicy = ({
labelPrefix="attestationPreference"
validate={(value) => {
const hasValidAAGUIDs = acceptableAAGUIDs.some(
(guid: string) => guid?.trim().length > 0,
(guid: string) => guid.trim().length > 0,
);

if (
Expand Down
2 changes: 1 addition & 1 deletion js/apps/admin-ui/src/client-scopes/EditClientScope.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ export default function EditClientScope() {
save={assignRoles}
/>
</Tab>
{realmRepresentation?.adminEventsEnabled &&
{realmRepresentation.adminEventsEnabled &&
hasAccess("view-events") && (
<Tab
data-testid="admin-events-tab"
Expand Down
10 changes: 5 additions & 5 deletions js/apps/admin-ui/src/client-scopes/details/ScopeForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,15 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
const isDynamicScopesEnabled = isFeatureEnabled(Feature.DynamicScopes);

// Get available hash algorithms from server info
const hashAlgorithms = serverInfo?.providers?.hash?.providers
const hashAlgorithms = serverInfo.providers?.hash.providers
? Object.keys(serverInfo.providers.hash.providers).map((alg) =>
alg.toLowerCase(),
)
: [];

// Get available asymmetric signature algorithms from server info
const asymmetricAlgorithms = useMemo(
() => serverInfo?.cryptoInfo?.clientSignatureAsymmetricAlgorithms ?? [],
() => serverInfo.cryptoInfo?.clientSignatureAsymmetricAlgorithms ?? [],
[serverInfo],
);

Expand Down Expand Up @@ -120,7 +120,7 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
// Filter only active keys suitable for signing credentials AND using asymmetric algorithms
const keyOptions = useMemo(() => {
const options = [{ key: "", value: t("useDefaultKey") }];
if (realmKeys && realmKeys.length > 0) {
if (realmKeys.length > 0) {
const keyOptions = realmKeys
.filter(
(key) =>
Expand Down Expand Up @@ -178,7 +178,7 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
const isOid4vcProtocol = selectedProtocol === OID4VC_PROTOCOL;
const isOid4vcEnabled =
isFeatureEnabled(Feature.OpenId4VCI) &&
realmRepresentation?.verifiableCredentialsEnabled;
realmRepresentation.verifiableCredentialsEnabled;
const isNotSaml = selectedProtocol != "saml";
const recommendedTokenJwsType =
selectedFormat === VC_FORMAT_SD_JWT
Expand Down Expand Up @@ -456,7 +456,7 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
</HelperText>
</FormHelperText>
)}
{realmKeys && realmKeys.length > 0 && (
{realmKeys.length > 0 && (
<SelectControl
id="kc-signing-key-id"
name={convertAttributeNameToForm<ClientScopeDefaultOptionalType>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const removeEmptyOid4vcAttributes = (

for (const fieldName of fieldNames) {
const attrKey = fieldName.replace(/^attributes\./, "");
if (isEmptyValue(cleanedAttributes?.[attrKey])) {
if (isEmptyValue(cleanedAttributes[attrKey])) {
delete cleanedAttributes[attrKey];
}
}
Expand Down
2 changes: 1 addition & 1 deletion js/apps/admin-ui/src/clients/AdvancedTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ export const AdvancedTab = ({ save, client }: AdvancedProps) => {
isHidden:
(protocol !== PROTOCOL_OIDC && protocol !== PROTOCOL_OID4VC) ||
!isFeatureEnabled(Feature.OpenId4VCI) ||
!realmRepresentation?.verifiableCredentialsEnabled,
!realmRepresentation.verifiableCredentialsEnabled,
panel: (
<>
<Text className="pf-v5-u-pb-lg">
Expand Down
2 changes: 1 addition & 1 deletion js/apps/admin-ui/src/clients/add/GeneralSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const GeneralSettings = () => {
const { realmRepresentation } = useRealm();
const providers = useLoginProviders();

const filteredProviders = realmRepresentation?.verifiableCredentialsEnabled
const filteredProviders = realmRepresentation.verifiableCredentialsEnabled
? providers
: providers.filter((provider) => provider !== PROTOCOL_OID4VC);

Expand Down
2 changes: 1 addition & 1 deletion js/apps/admin-ui/src/clients/add/NewClientForm.tsx
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const NewClientFooter = (newClientForm: any) => {
if (!(await trigger())) {
return;
}
onNext?.();
onNext();
};

return (
Expand Down
18 changes: 7 additions & 11 deletions js/apps/admin-ui/src/clients/advanced/AdvancedSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const AdvancedSettings = ({

const { control, watch, register } = useFormContext();

const acrUriMapRealm = realm?.attributes?.["acr.uri.map"]
const acrUriMapRealm = realm.attributes?.["acr.uri.map"]
? Object.values(JSON.parse(realm.attributes["acr.uri.map"]))
: [];

Expand Down Expand Up @@ -151,45 +151,41 @@ export const AdvancedSettings = ({
name={convertAttributeNameToForm(
"attributes.access.token.lifespan",
)}
defaultValue={realm?.accessTokenLifespan}
defaultValue={realm.accessTokenLifespan}
units={["minute", "day", "hour"]}
/>
<TokenLifespan
id="clientSessionIdle"
name={convertAttributeNameToForm(
"attributes.client.session.idle.timeout",
)}
defaultValue={realm?.clientSessionIdleTimeout}
defaultValue={realm.clientSessionIdleTimeout}
units={["minute", "day", "hour"]}
/>
<TokenLifespan
id="clientSessionMax"
name={convertAttributeNameToForm(
"attributes.client.session.max.lifespan",
)}
defaultValue={realm?.clientSessionMaxLifespan}
defaultValue={realm.clientSessionMaxLifespan}
units={["minute", "day", "hour"]}
/>
<TokenLifespan
id="clientOfflineSessionIdle"
name={convertAttributeNameToForm(
"attributes.client.offline.session.idle.timeout",
)}
defaultValue={realm?.offlineSessionIdleTimeout}
defaultValue={realm.offlineSessionIdleTimeout}
units={["minute", "day", "hour"]}
/>

{realm?.offlineSessionMaxLifespanEnabled && (
{realm.offlineSessionMaxLifespanEnabled && (
<TokenLifespan
id="clientOfflineSessionMax"
name={convertAttributeNameToForm(
"attributes.client.offline.session.max.lifespan",
)}
defaultValue={
realm?.offlineSessionMaxLifespanEnabled
? realm.offlineSessionMaxLifespan
: undefined
}
defaultValue={realm.offlineSessionMaxLifespan}
units={["minute", "day", "hour"]}
/>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export const ClusteringPanel = ({
ariaLabelKey="registeredClusterNodes"
loader={() =>
Promise.resolve<Node[]>(
Object.entries(nodes || {}).map((entry) => {
Object.entries(nodes).map((entry) => {
return { host: entry[0], registration: entry[1] };
}),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export const AuthorizationEvaluateResourcePolicies = ({
<Td>
{outerPolicy.status === DecisionEffect.Deny &&
resource.policies?.[rowIndex]?.scopes?.length
? resource.policies[rowIndex].scopes?.join(", ")
? resource.policies[rowIndex].scopes.join(", ")
: "-"}
</Td>
</Tr>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,12 +219,12 @@ export const ResourcesPolicySelect = ({
) => {
return (
<ChipGroup>
{selected?.map((item) => (
{selected.map((item) => (
<Chip
key={item.id}
=> {
field.onChange(field.value?.filter((id) => id !== item.id) || []);
setSelected(selected?.filter((p) => p.id !== item.id) || []);
setSelected(selected.filter((p) => p.id !== item.id));
}}
>
{!isAdminPermissionsClient ? (
Expand Down
3 changes: 0 additions & 3 deletions js/apps/admin-ui/src/clients/authorization/ScopeDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,6 @@ export default function ScopeDetails() {
id,
scopeId,
});
if (!scope) {
throw new Error(t("notFound"));
}
return scope;
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ export const ClientScope = () => {

useFetch(
() => adminClient.clientScopes.find(),
(scopes = []) => {
const clientScopes = getValues("clientScopes") || [];
(scopes) => {
const clientScopes = getValues("clientScopes");
setSelectedScopes(
clientScopes.map((s) => scopes.find((c) => c.id === s.id)!),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,13 @@ export default function PolicyDetails() {
if (policyId) {
const result = await Promise.all([
adminClient.clients.findOnePolicyWithType({
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- permissionClientId is undefined when navigating from client authorization tab
id: permissionClientId ?? id,
type: policyType!,
policyId,
}) as PolicyRepresentation | undefined,
adminClient.clients.getAssociatedPolicies({
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- permissionClientId is undefined when navigating from client authorization tab
id: permissionClientId ?? id,
permissionId: policyId,
}),
Expand All @@ -103,6 +105,7 @@ export default function PolicyDetails() {
}
if (!isValidComponentType(policyType!)) {
const providers = await adminClient.clients.listPolicyProviders({
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- permissionClientId is undefined when navigating from client authorization tab
id: permissionClientId ?? id,
});
const provider = providers.find((p) => p.type === policyType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default function DetailProvider() {
const updatedComponent = {
...component,
subType: subTab,
parentId: realmRepresentation?.id,
parentId: realmRepresentation.id,
providerType:
"org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy",
providerId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,7 @@ export const MultiValuedListComponent = ({
newValue = values;
}
field.onChange(
stringify && variant === SelectVariant.typeaheadMulti
? toStringValue(newValue)
: newValue,
stringify ? toStringValue(newValue) : newValue,
);
} else {
field.onChange(option);
Expand Down
5 changes: 2 additions & 3 deletions js/apps/admin-ui/src/components/group/GroupPickerDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -236,15 +236,14 @@ export const GroupPickerDialog = ({
setFirst(0);
}}
type={type}
isSearching={filter !== ""}
setIsSearching={(boolean) => setFilter(boolean ? "" : filter)}
isSearching={false}
selectedRows={selectedRows}
setSelectedRows={setSelectedRows}
canBrowse={canBrowse}
/>
))
: groups
?.map((g) => deepGroup([g]))
.map((g) => deepGroup([g]))
.flat()
.map((g) => (
<GroupRow
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { useTranslation } from "react-i18next";
import { FormErrorText } from "@keycloak/keycloak-ui-shared";

function stringToMultiline(value?: string): string[] {
return typeof value === "string" ? value.split("##") : [value || ""];
return typeof value === "string" ? value.split("##") : [""];
}

function toStringValue(formValue: string[]): string {
Expand Down
Loading
Loading
0