16947: Don't show misleading session validate errors.
[arvados-workbench2.git] / src / store / auth / auth-action-session.ts
index 9190dc1a757823666df7be9b283f5692a2c99c04..0f85e9ac5005fe5de7274d2dbe5d8526a9cfa81d 100644 (file)
@@ -5,46 +5,57 @@
 import { Dispatch } from "redux";
 import { setBreadcrumbs } from "~/store/breadcrumbs/breadcrumbs-actions";
 import { RootState } from "~/store/store";
-import { ServiceRepository } from "~/services/services";
+import { ServiceRepository, createServices, setAuthorizationHeader } from "~/services/services";
 import Axios from "axios";
-import { getUserFullname, User } from "~/models/user";
+import { User, getUserDisplayName } from "~/models/user";
 import { authActions } from "~/store/auth/auth-action";
-import { Config, ClusterConfigJSON, CLUSTER_CONFIG_PATH, DISCOVERY_DOC_PATH, ARVADOS_API_PATH } from "~/common/config";
+import {
+    Config, ClusterConfigJSON, CLUSTER_CONFIG_PATH, DISCOVERY_DOC_PATH,
+    buildConfig, mockClusterConfigJSON
+} from "~/common/config";
 import { normalizeURLPath } from "~/common/url";
 import { Session, SessionStatus } from "~/models/session";
 import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions";
-import { AuthService, UserDetailsResponse } from "~/services/auth-service/auth-service";
+import { AuthService } from "~/services/auth-service/auth-service";
 import { snackbarActions, SnackbarKind } from "~/store/snackbar/snackbar-actions";
 import * as jsSHA from "jssha";
 
-const getClusterInfo = async (origin: string): Promise<{ clusterId: string, baseUrl: string } | null> => {
-    // Try the new public config endpoint
+const getClusterConfig = async (origin: string): Promise<Config | null> => {
+    let configFromDD: Config | undefined;
     try {
-        const config = (await Axios.get<ClusterConfigJSON>(`${origin}/${CLUSTER_CONFIG_PATH}`)).data;
-        return {
-            clusterId: config.ClusterID,
-            baseUrl: normalizeURLPath(`${config.Services.Controller.ExternalURL}/${ARVADOS_API_PATH}`)
+        const dd = (await Axios.get<any>(`${origin}/${DISCOVERY_DOC_PATH}`)).data;
+        configFromDD = {
+            baseUrl: normalizeURLPath(dd.baseUrl),
+            keepWebServiceUrl: dd.keepWebServiceUrl,
+            remoteHosts: dd.remoteHosts,
+            rootUrl: dd.rootUrl,
+            uuidPrefix: dd.uuidPrefix,
+            websocketUrl: dd.websocketUrl,
+            workbenchUrl: dd.workbenchUrl,
+            workbench2Url: dd.workbench2Url,
+            loginCluster: "",
+            vocabularyUrl: "",
+            fileViewersConfigUrl: "",
+            clusterConfig: mockClusterConfigJSON({}),
+            apiRevision: parseInt(dd.revision, 10),
         };
     } catch { }
 
-    // Fall back to discovery document
+    // Try the new public config endpoint
     try {
-        const config = (await Axios.get<any>(`${origin}/${DISCOVERY_DOC_PATH}`)).data;
-        return {
-            clusterId: config.uuidPrefix,
-            baseUrl: normalizeURLPath(config.baseUrl)
-        };
+        const config = (await Axios.get<ClusterConfigJSON>(`${origin}/${CLUSTER_CONFIG_PATH}`)).data;
+        return { ...buildConfig(config), apiRevision: configFromDD ? configFromDD.apiRevision : 0 };
     } catch { }
 
+    // Fall back to discovery document
+    if (configFromDD !== undefined) {
+        return configFromDD;
+    }
+
     return null;
 };
 
-interface RemoteHostInfo {
-    clusterId: string;
-    baseUrl: string;
-}
-
-const getRemoteHostInfo = async (remoteHost: string): Promise<RemoteHostInfo | null> => {
+const getRemoteHostConfig = async (remoteHost: string): Promise<Config | null> => {
     let url = remoteHost;
     if (url.indexOf('://') < 0) {
         url = 'https://' + url;
@@ -52,14 +63,14 @@ const getRemoteHostInfo = async (remoteHost: string): Promise<RemoteHostInfo | n
     const origin = new URL(url).origin;
 
     // Maybe it is an API server URL, try fetching config and discovery doc
-    let r = getClusterInfo(origin);
+    let r = await getClusterConfig(origin);
     if (r !== null) {
         return r;
     }
 
     // Maybe it is a Workbench2 URL, try getting config.json
     try {
-        r = getClusterInfo((await Axios.get<any>(`${origin}/config.json`)).data.API_HOST);
+        r = await getClusterConfig((await Axios.get<any>(`${origin}/config.json`)).data.API_HOST);
         if (r !== null) {
             return r;
         }
@@ -67,7 +78,7 @@ const getRemoteHostInfo = async (remoteHost: string): Promise<RemoteHostInfo | n
 
     // Maybe it is a Workbench1 URL, try getting status.json
     try {
-        r = getClusterInfo((await Axios.get<any>(`${origin}/status.json`)).data.apiBaseURL);
+        r = await getClusterConfig((await Axios.get<any>(`${origin}/status.json`)).data.apiBaseURL);
         if (r !== null) {
             return r;
         }
@@ -76,15 +87,6 @@ const getRemoteHostInfo = async (remoteHost: string): Promise<RemoteHostInfo | n
     return null;
 };
 
-const getUserDetails = async (baseUrl: string, token: string): Promise<UserDetailsResponse> => {
-    const resp = await Axios.get<UserDetailsResponse>(`${baseUrl}/users/current`, {
-        headers: {
-            Authorization: `OAuth2 ${token}`
-        }
-    });
-    return resp.data;
-};
-
 const invalidV2Token = "Must be a v2 token";
 
 export const getSaltedToken = (clusterId: string, token: string) => {
@@ -104,23 +106,17 @@ export const getSaltedToken = (clusterId: string, token: string) => {
 
 export const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
 
-export const validateCluster = async (info: RemoteHostInfo, useToken: string):
+export const validateCluster = async (config: Config, useToken: string):
     Promise<{ user: User; token: string }> => {
 
-    const saltedToken = getSaltedToken(info.clusterId, useToken);
-    const user = await getUserDetails(info.baseUrl, saltedToken);
+    const saltedToken = getSaltedToken(config.uuidPrefix, useToken);
+
+    const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
+    setAuthorizationHeader(svc, saltedToken);
+
+    const user = await svc.authService.getUserDetails(false);
     return {
-        user: {
-            firstName: user.first_name,
-            lastName: user.last_name,
-            uuid: user.uuid,
-            ownerUuid: user.owner_uuid,
-            email: user.email,
-            isAdmin: user.is_admin,
-            isActive: user.is_active,
-            username: user.username,
-            prefs: user.prefs
-        },
+        user,
         token: saltedToken,
     };
 };
@@ -130,37 +126,38 @@ export const validateSession = (session: Session, activeSession: Session) =>
         dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED }));
         session.loggedIn = false;
 
-        const setupSession = (baseUrl: string, user: User, token: string) => {
+        const setupSession = (baseUrl: string, user: User, token: string, apiRevision: number) => {
             session.baseUrl = baseUrl;
             session.token = token;
             session.email = user.email;
             session.uuid = user.uuid;
-            session.name = getUserFullname(user);
+            session.name = getUserDisplayName(user);
             session.loggedIn = true;
+            session.apiRevision = apiRevision;
         };
 
-        const info = await getRemoteHostInfo(session.remoteHost);
-        if (!info) {
-            throw new Error(`Could not get config for ${session.remoteHost}`);
-        }
-
         let fail: Error | null = null;
-        try {
-            const { user, token } = await validateCluster(info, session.token);
-            setupSession(info.baseUrl, user, token);
-        } catch (e) {
-            fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
+        const config = await getRemoteHostConfig(session.remoteHost);
+        if (config !== null) {
+            dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
             try {
-                const { user, token } = await validateCluster(info, activeSession.token);
-                setupSession(info.baseUrl, user, token);
-                fail = null;
+                const { user, token } = await validateCluster(config, session.token);
+                setupSession(config.baseUrl, user, token, config.apiRevision);
             } catch (e) {
-                if (e.message === invalidV2Token) {
-                    fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
+                fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
+                try {
+                    const { user, token } = await validateCluster(config, activeSession.token);
+                    setupSession(config.baseUrl, user, token, config.apiRevision);
+                    fail = null;
+                } catch (e2) {
+                    if (e.message === invalidV2Token) {
+                        fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`);
+                    }
                 }
             }
+        } else {
+            fail = new Error(`Could not get config for ${session.remoteHost}`);
         }
-
         session.status = SessionStatus.VALIDATED;
         dispatch(authActions.UPDATE_SESSION(session));
 
@@ -198,11 +195,24 @@ export const validateSessions = () =>
                     }
                 }
             }
-            services.authService.saveSessions(sessions);
+            services.authService.saveSessions(getState().auth.sessions);
             dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
         }
     };
 
+export const addRemoteConfig = (remoteHost: string) =>
+    async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+        const config = await getRemoteHostConfig(remoteHost);
+        if (!config) {
+            dispatch(snackbarActions.OPEN_SNACKBAR({
+                message: `Could not get config for ${remoteHost}`,
+                kind: SnackbarKind.ERROR
+            }));
+            return;
+        }
+        dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
+    };
+
 export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) =>
     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
         const sessions = getState().auth.sessions;
@@ -215,8 +225,8 @@ export const addSession = (remoteHost: string, token?: string, sendToLogin?: boo
         }
 
         if (useToken) {
-            const info = await getRemoteHostInfo(remoteHost);
-            if (!info) {
+            const config = await getRemoteHostConfig(remoteHost);
+            if (!config) {
                 dispatch(snackbarActions.OPEN_SNACKBAR({
                     message: `Could not get config for ${remoteHost}`,
                     kind: SnackbarKind.ERROR
@@ -225,31 +235,33 @@ export const addSession = (remoteHost: string, token?: string, sendToLogin?: boo
             }
 
             try {
-                const { user, token } = await validateCluster(info, useToken);
+                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),
+                    name: getUserDisplayName(user),
                     uuid: user.uuid,
-                    baseUrl: info.baseUrl,
-                    clusterId: info.clusterId,
+                    baseUrl: config.baseUrl,
+                    clusterId: config.uuidPrefix,
                     remoteHost,
-                    token
+                    token,
+                    apiRevision: config.apiRevision,
                 };
 
-                if (sessions.find(s => s.clusterId === info.clusterId)) {
-                    dispatch(authActions.UPDATE_SESSION(session));
+                if (sessions.find(s => s.clusterId === config.uuidPrefix)) {
+                    await dispatch(authActions.UPDATE_SESSION(session));
                 } else {
-                    dispatch(authActions.ADD_SESSION(session));
+                    await dispatch(authActions.ADD_SESSION(session));
                 }
                 services.authService.saveSessions(getState().auth.sessions);
 
                 return session;
             } catch {
                 if (sendToLogin) {
-                    const rootUrl = new URL(info.baseUrl);
+                    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;
@@ -259,6 +271,13 @@ export const addSession = (remoteHost: string, token?: string, sendToLogin?: boo
         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 };
@@ -289,7 +308,6 @@ export const toggleSession = (session: Session) =>
 export const initSessions = (authService: AuthService, config: Config, user: User) =>
     (dispatch: Dispatch<any>) => {
         const sessions = authService.buildSessions(config, user);
-        authService.saveSessions(sessions);
         dispatch(authActions.SET_SESSIONS(sessions));
         dispatch(validateSessions());
     };