@aws-northstar/ui
Version:
NorthStar Design System v2
46 lines (45 loc) • 1.83 kB
JavaScript
import { CognitoIdentityClient } from '@aws-sdk/client-cognito-identity';
import { fromCognitoIdentityPool } from '@aws-sdk/credential-provider-cognito-identity';
import EmptyArgumentError from '../../EmptyArgumentError';
import { getCachedCredentials, setCachedCredentials } from './cache';
const getCredentials = (cognitoUser, region, identityPoolId, userPoolId, disableCache) => {
return new Promise(async (resolve, reject) => {
if (!disableCache) {
const cachedCredentials = getCachedCredentials();
if (cachedCredentials) {
resolve(cachedCredentials);
return;
}
}
if (!region) {
reject(new EmptyArgumentError('region is empty'));
return;
}
if (!identityPoolId) {
reject(new EmptyArgumentError('identityPoolId is empty'));
return;
}
if (!userPoolId) {
reject(new EmptyArgumentError('userPoolId is empty'));
return;
}
cognitoUser.getSession(async (_, session) => {
const credentialsFromCognitoIdentityPool = fromCognitoIdentityPool({
client: new CognitoIdentityClient({ region }),
identityPoolId,
logins: {
[`cognito-idp.${region}.amazonaws.com/${userPoolId}`]: session.getIdToken().getJwtToken(),
},
});
const cognitoidentity = new CognitoIdentityClient({
credentials: credentialsFromCognitoIdentityPool,
});
const credential = await cognitoidentity.config.credentials();
if (!disableCache) {
setCachedCredentials(credential);
}
resolve(credential);
});
});
};
export default getCredentials;