Files
ncd-fe/packages/pl-fe/src/utils/auth.ts
nicole mikołajczyk fb1f445c07 nicolium: do some linting but don't enable new rules for now
Signed-off-by: nicole mikołajczyk <git@mkljczk.pl>
2026-02-26 13:36:33 +01:00

73 lines
1.7 KiB
TypeScript

import { selectAccount, selectOwnAccount } from '@/queries/accounts/selectors';
import type { RootState } from '@/store';
const validId = (id?: string | null | false) =>
typeof id === 'string' && id !== 'null' && id !== 'undefined';
const isURL = (url?: string | null) => {
if (typeof url !== 'string') return false;
try {
new URL(url);
return true;
} catch {
return false;
}
};
const parseBaseURL = (url?: string) => {
if (typeof url !== 'string') return '';
try {
return new URL(url).origin;
} catch {
return '';
}
};
const getLoggedInAccount = (state: RootState) => selectOwnAccount(state);
const isLoggedIn = (getState: () => RootState) => validId(getState().me);
const getUserToken = (state: RootState, accountId?: string | false | null) => {
if (!accountId) return;
const accountUrl = selectAccount(accountId)?.url;
if (!accountUrl) return;
return state.auth.users[accountUrl]?.access_token;
};
const getAccessToken = (state: RootState) => {
const me = state.me;
return getUserToken(state, me);
};
const getAuthUserId = (state: RootState) => {
const me = state.auth.me;
return [state.auth.users[me!]?.id, me].filter((id) => id).find(validId);
};
const getAuthUserUrl = (state: RootState) => {
const me = state.auth.me;
return [state.auth.users[me!]?.url, me].filter((url) => url).find(isURL);
};
/** Get the VAPID public key. */
const getVapidKey = (state: RootState) =>
state.auth.app?.vapid_key ?? state.instance.configuration.vapid.public_key;
const getMeUrl = (state: RootState) => selectOwnAccount(state)?.url;
export {
validId,
isURL,
parseBaseURL,
getLoggedInAccount,
isLoggedIn,
getAccessToken,
getAuthUserId,
getAuthUserUrl,
getVapidKey,
getMeUrl,
};