File size: 1,981 Bytes
3206347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import * as React from 'react';

import { processStep } from 'helpers/authenticationSteps';
import computeAuthStepVariables from 'helpers/computeAuthStepVariables';
import useAppAuth from './useAppAuth';

function getSteps(auth, hasConnection, useShared) {
  if (hasConnection) {
    if (useShared) {
      return auth?.sharedReconnectionSteps;
    }
    return auth?.reconnectionSteps;
  }

  if (useShared) {
    return auth?.sharedAuthenticationSteps;
  }

  return auth?.authenticationSteps;
}

export default function useAuthenticateApp(payload) {
  const { appKey, appAuthClientId, connectionId, useShared = false } = payload;
  const { data: auth } = useAppAuth(appKey);
  const [authenticationInProgress, setAuthenticationInProgress] =
    React.useState(false);
  const steps = getSteps(auth?.data, !!connectionId, useShared);

  const authenticate = React.useMemo(() => {
    if (!steps?.length) return;

    return async function authenticate(payload = {}) {
      const { fields } = payload;
      setAuthenticationInProgress(true);
      const response = {
        key: appKey,
        appAuthClientId: appAuthClientId || payload.appAuthClientId,
        connection: {
          id: connectionId,
        },
        fields,
      };
      let stepIndex = 0;

      while (stepIndex < steps?.length) {
        const step = steps[stepIndex];
        const variables = computeAuthStepVariables(step.arguments, response);

        try {
          const stepResponse = await processStep(step, variables);
          response[step.name] = stepResponse;
        } catch (err) {
          console.log(err);
          setAuthenticationInProgress(false);
          throw err;
        }
        stepIndex++;

        if (stepIndex === steps.length) {
          return response;
        }
        setAuthenticationInProgress(false);
      }
    };
  }, [steps, appKey, appAuthClientId, connectionId]);

  return {
    authenticate,
    inProgress: authenticationInProgress,
  };
}