+export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) =>
+ async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+ const sessions = getState().auth.sessions;
+ const activeSession = getActiveSession(sessions);
+ let useToken: string | null = null;
+ if (token) {
+ useToken = token;
+ } else if (activeSession) {
+ useToken = activeSession.token;
+ }
+
+ if (useToken) {
+ const config = await getRemoteHostConfig(remoteHost);
+ if (!config) {
+ dispatch(snackbarActions.OPEN_SNACKBAR({
+ message: `Could not get config for ${remoteHost}`,
+ kind: SnackbarKind.ERROR
+ }));
+ return;
+ }
+
+ try {
+ dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
+ const { user, token } = await validateCluster(config, useToken);
+ const session = {
+ loggedIn: true,
+ status: SessionStatus.VALIDATED,
+ active: false,
+ email: user.email,
+ name: getUserFullname(user),
+ uuid: user.uuid,
+ baseUrl: config.baseUrl,
+ clusterId: config.uuidPrefix,
+ remoteHost,
+ token
+ };
+
+ if (sessions.find(s => s.clusterId === config.uuidPrefix)) {
+ await dispatch(authActions.UPDATE_SESSION(session));
+ } else {
+ await dispatch(authActions.ADD_SESSION(session));
+ }
+ services.authService.saveSessions(getState().auth.sessions);
+
+ return session;
+ } catch {
+ if (sendToLogin) {
+ const rootUrl = new URL(config.baseUrl);
+ rootUrl.pathname = "";
+ window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString()));
+ return;
+ }
+ }
+ }
+ return Promise.reject(new Error("Could not validate cluster"));
+ };
+
+
+export const removeSession = (clusterId: string) =>
+ async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+ await dispatch(authActions.REMOVE_SESSION(clusterId));
+ services.authService.saveSessions(getState().auth.sessions);
+ };
+
+export const toggleSession = (session: Session) =>
+ async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+ const s: Session = { ...session };
+
+ if (session.loggedIn) {
+ s.loggedIn = false;
+ dispatch(authActions.UPDATE_SESSION(s));
+ } else {
+ const sessions = getState().auth.sessions;
+ const activeSession = getActiveSession(sessions);
+ if (activeSession) {
+ try {
+ await dispatch(validateSession(s, activeSession));
+ } catch (e) {
+ dispatch(snackbarActions.OPEN_SNACKBAR({
+ message: e.message,
+ kind: SnackbarKind.ERROR
+ }));
+ s.loggedIn = false;
+ dispatch(authActions.UPDATE_SESSION(s));
+ }
+ }
+ }