From e19c2e1c62f9891dd65d924a5b560b768296a03a Mon Sep 17 00:00:00 2001 From: Matthias Mair Date: Tue, 7 Jan 2025 23:34:45 +0100 Subject: [PATCH] simplify calls --- src/frontend/src/functions/auth.tsx | 69 +++++++++----- .../AccountSettings/SecurityContent.tsx | 95 ++++--------------- 2 files changed, 66 insertions(+), 98 deletions(-) diff --git a/src/frontend/src/functions/auth.tsx b/src/frontend/src/functions/auth.tsx index dc75d90d84..8fd807e6a5 100644 --- a/src/frontend/src/functions/auth.tsx +++ b/src/frontend/src/functions/auth.tsx @@ -1,6 +1,7 @@ import { t } from '@lingui/macro'; import { notifications } from '@mantine/notifications'; import axios from 'axios'; +import type { AxiosRequestConfig } from 'axios'; import type { Location, NavigateFunction } from 'react-router-dom'; import { api, setApiDefaults } from '../App'; import { ApiEndpoints } from '../enums/ApiEndpoints'; @@ -127,16 +128,12 @@ export const doBasicLogin = async ( */ export const doLogout = async (navigate: NavigateFunction) => { const { clearUserState, isLoggedIn, setSession } = useUserState.getState(); - const { session } = useUserState.getState(); // Logout from the server session if (isLoggedIn() || !!getCsrfCookie()) { - await api - .delete(apiUrl(ApiEndpoints.user_logout), { - headers: { 'X-Session-Token': session } - }) - .catch(() => {}); - + await authApi(apiUrl(ApiEndpoints.user_logout), undefined, 'delete').catch( + () => {} + ); showLoginNotification({ title: t`Logged Out`, message: t`Successfully logged out` @@ -201,21 +198,14 @@ export function handleMfaLogin( location: Location, values: { code: string } ) { - const { session, setToken, setSession } = useUserState.getState(); - - api - .post( - apiUrl(ApiEndpoints.user_login_mfa), - { - code: values.code - }, - { headers: { 'X-Session-Token': session } } - ) - .then((response) => { - setSession(response.data.meta.session_token); - setToken(response.data.meta.access_token); - followRedirect(navigate, location?.state); - }); + const { setToken, setSession } = useUserState.getState(); + authApi(apiUrl(ApiEndpoints.user_login_mfa), undefined, 'post', { + code: values.code + }).then((response) => { + setSession(response.data.meta.session_token); + setToken(response.data.meta.access_token); + followRedirect(navigate, location?.state); + }); } /** @@ -310,3 +300,38 @@ export function ProviderLogin( const url = `${host}${apiUrl(ApiEndpoints.login_provider_redirect)}`; post(url, values); } + +/** + * Makes an API request with session tokens using the provided URL, configuration, method, and data. + * + * @param url - The URL to which the request is sent. + * @param config - Optional Axios request configuration. + * @param method - The HTTP method to use for the request. Defaults to 'get'. + * @param data - Optional data to be sent with the request. + * @returns A promise that resolves to the response of the API request. + */ +export function authApi( + url: string, + config: AxiosRequestConfig | undefined = undefined, + method: 'get' | 'post' | 'put' | 'delete' = 'get', + data?: any +) { + const [session] = useUserState((state) => [state.session]); + // extend default axios instance with session token + const requestConfig = config || {}; + if (!requestConfig.headers) { + requestConfig.headers = {}; + } + requestConfig.headers['X-Session-Token'] = session; + + // set method + requestConfig.method = method; + + // set data + if (data) { + requestConfig.data = data; + } + + // use normal api + return api.post(url, requestConfig); +} diff --git a/src/frontend/src/pages/Index/Settings/AccountSettings/SecurityContent.tsx b/src/frontend/src/pages/Index/Settings/AccountSettings/SecurityContent.tsx index 703f323631..2bd2ff0bb5 100644 --- a/src/frontend/src/pages/Index/Settings/AccountSettings/SecurityContent.tsx +++ b/src/frontend/src/pages/Index/Settings/AccountSettings/SecurityContent.tsx @@ -21,9 +21,8 @@ import { api, queryClient } from '../../../../App'; import { YesNoButton } from '../../../../components/buttons/YesNoButton'; import { PlaceholderPill } from '../../../../components/items/Placeholder'; import { ApiEndpoints } from '../../../../enums/ApiEndpoints'; -import { ProviderLogin } from '../../../../functions/auth'; +import { ProviderLogin, authApi } from '../../../../functions/auth'; import { apiUrl, useServerApiState } from '../../../../states/ApiState'; -import { useUserState } from '../../../../states/UserState'; import type { Provider, SecuritySetting } from '../../../../states/states'; export function SecurityContent() { @@ -80,75 +79,25 @@ export function SecurityContent() { function EmailContent() { const [value, setValue] = useState(''); const [newEmailValue, setNewEmailValue] = useState(''); - const [session] = useUserState((state) => [state.session]); const { isLoading, data, refetch } = useQuery({ queryKey: ['emails'], queryFn: () => - api - .get(apiUrl(ApiEndpoints.user_emails), { - headers: { 'X-Session-Token': session } - }) - .then((res) => res.data.data) + authApi(apiUrl(ApiEndpoints.user_emails)).then((res) => res.data.data) }); function runServerAction( - url: ApiEndpoints, - action: 'post' | 'put' | 'delete' = 'post' + action: 'post' | 'put' | 'delete' = 'post', + data?: any ) { - let act: any; - switch (action) { - case 'post': - act = api.post; - break; - case 'put': - act = api.put; - break; - case 'delete': - act = api.delete; - break; - } - act( - apiUrl(url), - { email: value }, - { headers: { 'X-Session-Token': session } } - ) + const vals: any = data || { email: value }; + console.log('vals', vals); + authApi(apiUrl(ApiEndpoints.user_emails), undefined, action, vals) .then(() => { refetch(); }) .catch((res: any) => console.log(res.data)); } - function addEmail() { - api - .post( - apiUrl(ApiEndpoints.user_emails), - { - email: newEmailValue - }, - { headers: { 'X-Session-Token': session } } - ) - .then(() => { - refetch(); - }) - .catch((res) => console.log(res.data)); - } - - function changePrimary() { - api - .post( - apiUrl(ApiEndpoints.user_emails), - { - email: value, - primary: true - }, - { headers: { 'X-Session-Token': session } } - ) - .then(() => { - refetch(); - }) - .catch((res) => console.log(res.data)); - } - if (isLoading) return ; return ( @@ -211,23 +160,25 @@ function EmailContent() { - - - - @@ -252,15 +203,10 @@ function SsoContent({ }: Readonly<{ auth_settings: SecuritySetting | undefined }>) { const [value, setValue] = useState(''); const [currentProviders, setCurrentProviders] = useState(); - const { session } = useUserState.getState(); const { isLoading, data } = useQuery({ queryKey: ['sso-list'], queryFn: () => - api - .get(apiUrl(ApiEndpoints.user_sso), { - headers: { 'X-Session-Token': session } - }) - .then((res) => res.data.data) + authApi(apiUrl(ApiEndpoints.user_sso)).then((res) => res.data.data) }); useEffect(() => { @@ -281,10 +227,7 @@ function SsoContent({ }, [auth_settings, data]); function removeProvider() { - api - .delete(apiUrl(ApiEndpoints.user_sso), { - headers: { 'X-Session-Token': session } - }) + authApi(apiUrl(ApiEndpoints.user_sso), undefined, 'delete') .then(() => { queryClient.removeQueries({ queryKey: ['sso-list']