How to use multiple user pools with AWS Amplify in React?

13 views Asked by At
export const awsExports = {
    Auth: {
        Cognito: {
            "userPoolId" : "ap-northeast-2_qp2lxxxxx",
            "userPoolClientId" : "hqhcjil010lxxxxxxx"
        }
    }
}

export const awsExportsUser = {
    Auth: {
        Cognito: {
            "userPoolId" : "ap-northeast-2_xxxxxxx",
            "userPoolClientId" : "7f2p7n87pkskfv22xxxxxxxq7"
        }
    }
}

This is my 2 user pools . One for tenant one for client.

Tenant =>

import "./TenantConfig.scss";
import { useEffect, useState } from "react";
import { Amplify } from "aws-amplify";
import { Authenticator } from "@aws-amplify/ui-react";
import { fetchUserAttributes, fetchAuthSession } from '@aws-amplify/auth';
import "@aws-amplify/ui-react/styles.css";
import { awsExports } from "../../config";
import TenantConfig from "./TenantConfig";
import { useDispatch, useSelector } from "react-redux";
import { APPDispatch, RootState } from "../redux/store/store";
import { ITenantDetail, addTenantDetail } from "../redux/slice/TenantAuthSlice";

Amplify.configure(awsExports);

export default function TenantAuth() {
  const dispatch = useDispatch<APPDispatch>();
  const {tenantState,tenant} = useSelector((state: RootState) => state.tenantAuthReducer);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const userAttributes = await fetchUserAttributes();
        const { accessToken } = (await fetchAuthSession()).tokens ?? {};
        dispatch(addTenantDetail({ email: userAttributes.email!, name: userAttributes.name!, token: accessToken?.toString() }));
      } catch (error) {
        console.log(error);
      }
    };

    fetchUser();
  }, [tenantState]);

  return (
    <Authenticator hideSignUp>
      {({ signOut,user }) => (
        <TenantConfig signOut={signOut || (() => {})} cognitoUser={user} user={tenant} />
      )}
    </Authenticator>
  );
}

user =>

import React from 'react'
import { Amplify } from "aws-amplify";
import { Authenticator } from "@aws-amplify/ui-react";
import { fetchUserAttributes, fetchAuthSession } from '@aws-amplify/auth';
import { awsExportsUser } from "../../config";
Amplify.configure(awsExportsUser);

export default function Login() {
  return (
    <Authenticator signUpAttributes={['name']}>
    {({ signOut  }) => (
      <p>Hello</p>
    )}
  </Authenticator>
  )
}

Now what is happening that whenever I am logging in to user, my tenant also gets automatically logged in and if I login in to tenant, my user automatically logs in . How to avoid that?

Its taking token from the local storage. Is there any way I can change it or something else?

0

There are 0 answers