Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UI - use new db user settings to persist user's host table column preferences #25185

Merged
merged 18 commits into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from 14 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
2 changes: 2 additions & 0 deletions changes/23971-persist-hosts-column-settings-across-sessions
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- Implement user-level settings, use them to persist a user's selection of which columns to display
on the hosts table.
4 changes: 3 additions & 1 deletion frontend/components/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
isOnlyObserver,
isAnyTeamMaintainerOrTeamAdmin,
setAvailableTeams,
setUserSettings,
setCurrentUser,
setConfig,
setEnrollSecret,
Expand Down Expand Up @@ -165,9 +166,10 @@

const fetchCurrentUser = async () => {
try {
const { user, available_teams } = await usersAPI.me();
const { user, available_teams, settings } = await usersAPI.me();
setCurrentUser(user);
setAvailableTeams(user, available_teams);
setUserSettings(settings);
fetchConfig();
} catch (error) {
if (
Expand Down Expand Up @@ -196,7 +198,7 @@
if (authToken() && !location?.pathname.includes("/device/")) {
fetchCurrentUser();
}
}, [location?.pathname]);

Check warning on line 201 in frontend/components/App/App.tsx

View workflow job for this annotation

GitHub Actions / lint-js (ubuntu-latest)

React Hook useEffect has a missing dependency: 'fetchCurrentUser'. Either include it or remove the dependency array

// Updates title that shows up on browser tabs
useEffect(() => {
Expand All @@ -222,7 +224,7 @@
!isAnyTeamMaintainerOrTeamAdmin &&
!location?.pathname.includes("/device/");

const getEnrollSecret = async () => {

Check warning on line 227 in frontend/components/App/App.tsx

View workflow job for this annotation

GitHub Actions / lint-js (ubuntu-latest)

Expected to return a value at the end of async arrow function
try {
const { spec } = await configAPI.loadEnrollSecret();
setEnrollSecret(spec.secrets);
Expand All @@ -239,7 +241,7 @@

// "any" is used on purpose. We are using Axios but this
// function expects a native React Error type, which is incompatible.
const renderErrorOverlay = ({ error }: any) => {

Check warning on line 244 in frontend/components/App/App.tsx

View workflow job for this annotation

GitHub Actions / lint-js (ubuntu-latest)

Unexpected any. Specify a different type
// @ts-ignore
console.error(error);

Expand Down
25 changes: 24 additions & 1 deletion frontend/context/app.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { createContext, useReducer, useMemo, ReactNode } from "react";

import { IConfig } from "interfaces/config";
import { IConfig, IUserSettings } from "interfaces/config";
import { IEnrollSecret } from "interfaces/enroll_secret";
import {
APP_CONTEXT_ALL_TEAMS_SUMMARY,
Expand All @@ -15,6 +15,7 @@ import { hasLicenseExpired, willExpireWithinXDays } from "utilities/helpers";

enum ACTIONS {
SET_AVAILABLE_TEAMS = "SET_AVAILABLE_TEAMS",
SET_USER_SETTINGS = "SET_USER_SETTINGS",
SET_CURRENT_USER = "SET_CURRENT_USER",
SET_CURRENT_TEAM = "SET_CURRENT_TEAM",
SET_CONFIG = "SET_CONFIG",
Expand All @@ -36,6 +37,11 @@ interface ISetAvailableTeamsAction {
availableTeams: ITeamSummary[];
}

interface ISetUserSettingsAction {
type: ACTIONS.SET_USER_SETTINGS;
userSettings: IUserSettings;
}

interface ISetConfigAction {
type: ACTIONS.SET_CONFIG;
config: IConfig;
Expand Down Expand Up @@ -105,6 +111,7 @@ interface ISetFilteredPoliciesPathAction {
}
type IAction =
| ISetAvailableTeamsAction
| ISetUserSettingsAction
| ISetConfigAction
| ISetCurrentTeamAction
| ISetCurrentUserAction
Expand All @@ -125,6 +132,7 @@ type Props = {

type InitialStateType = {
availableTeams?: ITeamSummary[];
userSettings?: IUserSettings;
config: IConfig | null;
currentUser: IUser | null;
currentTeam?: ITeamSummary;
Expand Down Expand Up @@ -171,6 +179,7 @@ type InitialStateType = {
user: IUser | null,
availableTeams: ITeamSummary[]
) => void;
setUserSettings: (userSettings: IUserSettings) => void;
setCurrentUser: (user: IUser) => void;
setCurrentTeam: (team?: ITeamSummary) => void;
setConfig: (config: IConfig) => void;
Expand All @@ -190,6 +199,7 @@ export type IAppContext = InitialStateType;

export const initialState = {
availableTeams: undefined,
userSettings: undefined,
config: null,
currentUser: null,
currentTeam: undefined,
Expand Down Expand Up @@ -227,6 +237,7 @@ export const initialState = {
willApplePnsExpire: false,
willVppExpire: false,
setAvailableTeams: () => null,
setUserSettings: () => null,
setCurrentUser: () => null,
setCurrentTeam: () => null,
setConfig: () => null,
Expand Down Expand Up @@ -296,6 +307,13 @@ const setPermissions = (

const reducer = (state: InitialStateType, action: IAction) => {
switch (action.type) {
case ACTIONS.SET_USER_SETTINGS: {
const { userSettings } = action;
return {
...state,
userSettings,
};
}
case ACTIONS.SET_AVAILABLE_TEAMS: {
const { user, availableTeams } = action;

Expand Down Expand Up @@ -436,6 +454,7 @@ const AppProvider = ({ children }: Props): JSX.Element => {
const value = useMemo(
() => ({
availableTeams: state.availableTeams,
userSettings: state.userSettings,
config: state.config,
currentUser: state.currentUser,
currentTeam: state.currentTeam,
Expand Down Expand Up @@ -487,6 +506,9 @@ const AppProvider = ({ children }: Props): JSX.Element => {
availableTeams,
});
},
setUserSettings: (userSettings: IUserSettings) => {
dispatch({ type: ACTIONS.SET_USER_SETTINGS, userSettings });
},
setCurrentUser: (currentUser: IUser) => {
dispatch({ type: ACTIONS.SET_CURRENT_USER, currentUser });
},
Expand Down Expand Up @@ -546,6 +568,7 @@ const AppProvider = ({ children }: Props): JSX.Element => {
state.abmExpiry,
state.apnsExpiry,
state.availableTeams,
state.userSettings,
state.config,
state.currentTeam,
state.currentUser,
Expand Down
4 changes: 4 additions & 0 deletions frontend/interfaces/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,7 @@ export type IAutomationsConfig = Pick<
>;

export const CONFIG_DEFAULT_RECENT_VULNERABILITY_MAX_AGE_IN_DAYS = 30;

export interface IUserSettings {
hidden_host_columns: string[];
}
2 changes: 2 additions & 0 deletions frontend/interfaces/user.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import PropTypes from "prop-types";
import teamInterface, { ITeam } from "./team";
import { IUserSettings } from "./config";

export default PropTypes.shape({
created_at: PropTypes.string,
Expand Down Expand Up @@ -110,6 +111,7 @@ export interface IUpdateUserFormData {
sso_enabled?: boolean;
mfa_enabled?: boolean;
teams?: ITeam[];
settings?: IUserSettings;
}

export interface ICreateUserWithInvitationFormData {
Expand Down
12 changes: 8 additions & 4 deletions frontend/pages/RegistrationPage/RegistrationPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@ interface IRegistrationPageProps {
const baseClass = "registration-page";

const RegistrationPage = ({ router }: IRegistrationPageProps) => {
const { currentUser, setCurrentUser, setAvailableTeams } = useContext(
AppContext
);
const {
currentUser,
setCurrentUser,
setAvailableTeams,
setUserSettings,
} = useContext(AppContext);
const [page, setPage] = useState(1);
const [pageProgress, setPageProgress] = useState(1);
const [showSetupError, setShowSetupError] = useState(false);
Expand All @@ -58,9 +61,10 @@ const RegistrationPage = ({ router }: IRegistrationPageProps) => {
const { token } = await usersAPI.setup(formData);
local.setItem("auth_token", token);

const { user, available_teams } = await usersAPI.me();
const { user, available_teams, settings } = await usersAPI.me();
setCurrentUser(user);
setAvailableTeams(user, available_teams);
setUserSettings(settings);
router.push(DASHBOARD);
window.location.reload();
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ const TeamDetailsWrapper = ({
isGlobalAdmin,
isPremiumTier,
setAvailableTeams,
setUserSettings,
setCurrentUser,
} = useContext(AppContext);

Expand Down Expand Up @@ -140,9 +141,10 @@ const TeamDetailsWrapper = ({

const { refetch: refetchMe } = useQuery(["me"], () => usersAPI.me(), {
enabled: false,
onSuccess: ({ user, available_teams }: IGetMeResponse) => {
onSuccess: ({ user, available_teams, settings }: IGetMeResponse) => {
setCurrentUser(user);
setAvailableTeams(user, available_teams);
setUserSettings(settings);
},
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const TeamManagementPage = (): JSX.Element => {
setCurrentTeam,
setCurrentUser,
setAvailableTeams,
setUserSettings,
} = useContext(AppContext);
const [isUpdatingTeams, setIsUpdatingTeams] = useState(false);
const [showCreateTeamModal, setShowCreateTeamModal] = useState(false);
Expand All @@ -48,9 +49,10 @@ const TeamManagementPage = (): JSX.Element => {

const { refetch: refetchMe } = useQuery(["me"], () => usersAPI.me(), {
enabled: false,
onSuccess: ({ user, available_teams }: IGetMeResponse) => {
onSuccess: ({ user, available_teams, settings }: IGetMeResponse) => {
setCurrentUser(user);
setAvailableTeams(user, available_teams);
setUserSettings(settings);
},
});

Expand Down
15 changes: 6 additions & 9 deletions frontend/pages/hosts/ManageHostsPage/HostTableConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -675,27 +675,24 @@ const generateAvailableTableHeaders = ({
return allHostTableHeaders.reduce(
(columns: Column<IHost>[], currentColumn: Column<IHost>) => {
// skip over column headers that are not shown in free observer tier
if (isFreeTier && isOnlyObserver) {
if (isFreeTier) {
Copy link
Contributor Author

@jacobshandling jacobshandling Jan 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All changes in this file are cleanup, no logic updates

if (
currentColumn.id === "team_name" ||
currentColumn.id === "selection"
isOnlyObserver &&
["selection", "team_name"].includes(currentColumn.id || "")
) {
return columns;
// skip over column headers that are not shown in free admin/maintainer
}
// skip over column headers that are not shown in free admin/maintainer
} else if (isFreeTier) {
if (
currentColumn.id === "team_name" ||
currentColumn.id === "mdm.server_url" ||
currentColumn.id === "mdm.enrollment_status"
) {
return columns;
}
} else if (isOnlyObserver) {
} else if (isOnlyObserver && currentColumn.id === "selection") {
// In premium tier, we want to check user role to enable/disable select column
if (currentColumn.id === "selection") {
return columns;
}
return columns;
}

columns.push(currentColumn);
Expand Down
32 changes: 20 additions & 12 deletions frontend/pages/hosts/ManageHostsPage/ManageHostsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import { RouteProps } from "react-router/lib/Route";
import { find, isEmpty, isEqual, omit } from "lodash";
import { format } from "date-fns";
import FileSaver from "file-saver";
import classNames from "classnames";

import enrollSecretsAPI from "services/entities/enroll_secret";
import usersAPI from "services/entities/users";
import labelsAPI, { ILabelsResponse } from "services/entities/labels";
import teamsAPI, { ILoadTeamsResponse } from "services/entities/teams";
import globalPoliciesAPI from "services/entities/global_policies";
Expand Down Expand Up @@ -46,7 +46,6 @@ import {
IEnrollSecret,
IEnrollSecretsResponse,
} from "interfaces/enroll_secret";
import { getErrorReason } from "interfaces/errors";
import { ILabel } from "interfaces/label";
import { IOperatingSystemVersion } from "interfaces/operating_system";
import { IPolicy, IStoredPolicyResponse } from "interfaces/policy";
Expand Down Expand Up @@ -143,6 +142,7 @@ const ManageHostsPage = ({
isPremiumTier,
isFreeTier,
isSandboxMode,
userSettings,
setFilteredHostsPath,
setFilteredPoliciesPath,
setFilteredQueriesPath,
Expand Down Expand Up @@ -175,11 +175,6 @@ const ManageHostsPage = ({
},
});

const hostHiddenColumns = localStorage.getItem("hostHiddenColumns");
const storedHiddenColumns = hostHiddenColumns
? JSON.parse(hostHiddenColumns)
: null;
Comment on lines -178 to -181
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit torn on this, as it means breaking existing functionality for users. I confirmed that we're not clearing localstorage on logout, so the columns do persist between sessions (just not between browsers, or in incognito mode). On the other hand we wouldn't want to support this forever as eventually everyone will be using the new strategy. If it sparks a riot we can put it back in a patch, but likely no one will notice.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That was my thinking too. We could include fallback behavior to use local storage, but I don't really see the scenario where the user has logged in, is actively using Fleet, and suddenly the server is somehow unavailable for this specific functionality.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wasn't think of it as fallback behavior as much as, people right now have their columns set up and they're going to disappear when this deploys.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aaah, I see

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need a UI migration 🙂

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could, in this initial rollout, check for local storage settings, and if present, immediately send them to the server to persist and set them as current UI context, then down the line remove that code

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(or not remove it I suppose, but there would be no reason for anything to present in local storage after not too long)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could, in this initial rollout, check for local storage settings, and if present, immediately send them to the server to persist and set them as current UI context, then down the line remove that code

This is probably the way. It seems a bit heavy handed but considering the original ask, we'd ideally like the user to see the columns they expect and then also see them in another browser / incognito mode, without having to do any action to trigger persistence.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds like a plan


// Functions to avoid race conditions
const initialSortBy: ISortOption[] = (() => {
let key = DEFAULT_SORT_HEADER;
Expand Down Expand Up @@ -212,7 +207,7 @@ const ManageHostsPage = ({
const [showTransferHostModal, setShowTransferHostModal] = useState(false);
const [showDeleteHostModal, setShowDeleteHostModal] = useState(false);
const [hiddenColumns, setHiddenColumns] = useState<string[]>(
storedHiddenColumns || defaultHiddenColumns
userSettings?.hidden_host_columns || defaultHiddenColumns
);
const [selectedHostIds, setSelectedHostIds] = useState<number[]>([]);
const [isAllMatchingHostsSelected, setIsAllMatchingHostsSelected] = useState(
Expand Down Expand Up @@ -766,10 +761,23 @@ const ManageHostsPage = ({
router.push(`${PATHS.EDIT_LABEL(parseInt(labelID, 10))}`);
};

const onSaveColumns = (newHiddenColumns: string[]) => {
localStorage.setItem("hostHiddenColumns", JSON.stringify(newHiddenColumns));
setHiddenColumns(newHiddenColumns);
setShowEditColumnsModal(false);
const onSaveColumns = async (newHiddenColumns: string[]) => {
if (!currentUser) {
return;
}
try {
await usersAPI.update(currentUser.id, {
settings: { hidden_host_columns: newHiddenColumns },
});
// No success renderFlash, to make column setting more seamless
// only set state and close modal if server persist succeeds, keeping UI and server state in
// sync.
// Can also add local storage fallback behavior in next iteration if we want.
setHiddenColumns(newHiddenColumns);
setShowEditColumnsModal(false);
} catch (response) {
renderFlash("error", "Couldn't save column settings. Please try again.");
}
};

// NOTE: this is called once on initial render and every time the query changes
Expand Down
21 changes: 13 additions & 8 deletions frontend/services/entities/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
ICreateUserWithInvitationFormData,
} from "interfaces/user";
import { ITeamSummary } from "interfaces/team";
import { IUserSettings } from "interfaces/config";

export interface ISortOption {
id: number;
Expand Down Expand Up @@ -41,6 +42,7 @@ interface IRequirePasswordReset {
export interface IGetMeResponse {
user: IUser;
available_teams: ITeamSummary[];
settings: IUserSettings;
}

export default {
Expand Down Expand Up @@ -111,14 +113,17 @@ export default {
});
},
me: (): Promise<IGetMeResponse> => {
const { ME } = endpoints;

return sendRequest("GET", ME).then(({ user, available_teams }) => {
return {
user: helpers.addGravatarUrlToResource(user),
available_teams,
};
});
// include the user's settings when calling from the UI
const path = `${endpoints.ME}?include_ui_settings=true`;
return sendRequest("GET", path).then(
({ user, available_teams, settings }) => {
return {
user: helpers.addGravatarUrlToResource(user),
available_teams,
settings,
};
}
);
},
performRequiredPasswordReset: (new_password: string) => {
const { PERFORM_REQUIRED_PASSWORD_RESET } = endpoints;
Expand Down
Loading