Skip to content

Commit 1cd12bf

Browse files
fix(auth): associate unAuth identityId to newly authenticated user's identityId (#14207)
* fix: associate unauth identityId to auth identityId * chore:remove signout fix changes * chore: address comments and update tests path * chore: update debug log and add some unit tests * chore: address nits
1 parent e924f12 commit 1cd12bf

File tree

4 files changed

+85
-57
lines changed

4 files changed

+85
-57
lines changed

packages/auth/__tests__/providers/cognito/credentialsProvider.test.ts renamed to packages/auth/__tests__/providers/cognito/credentialsProvider/credentialsProvider.test.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,17 @@ import {
1111
import {
1212
CognitoAWSCredentialsAndIdentityIdProvider,
1313
DefaultIdentityIdStore,
14-
} from '../../../src/providers/cognito';
15-
import { AuthError } from '../../../src/errors/AuthError';
16-
17-
import { authAPITestParams } from './testUtils/authApiTestParams';
14+
} from '../../../../src/providers/cognito';
15+
import { AuthError } from '../../../../src/errors/AuthError';
16+
import { authAPITestParams } from '../testUtils/authApiTestParams';
1817

1918
jest.mock('@aws-amplify/core', () => ({
2019
...jest.requireActual('@aws-amplify/core'),
2120
getCredentialsForIdentity: jest.fn(),
2221
}));
2322

2423
jest.mock(
25-
'./../../../src/providers/cognito/credentialsProvider/IdentityIdProvider',
24+
'./../../../../src/providers/cognito/credentialsProvider/IdentityIdProvider',
2625
() => ({
2726
cognitoIdentityIdProvider: jest
2827
.fn()

packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts renamed to packages/auth/__tests__/providers/cognito/credentialsProvider/identityIdProvider.test.ts

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,18 @@ import {
88
} from '@aws-amplify/core/internals/aws-clients/cognitoIdentity';
99
import { CognitoIdentityPoolConfig } from '@aws-amplify/core/internals/utils';
1010

11-
import { DefaultIdentityIdStore } from '../../../src/providers/cognito/credentialsProvider/IdentityIdStore';
12-
import { cognitoIdentityIdProvider } from '../../../src/providers/cognito/credentialsProvider/IdentityIdProvider';
13-
14-
import { authAPITestParams } from './testUtils/authApiTestParams';
11+
import { DefaultIdentityIdStore } from '../../../../src/providers/cognito/credentialsProvider/IdentityIdStore';
12+
import { cognitoIdentityIdProvider } from '../../../../src/providers/cognito/credentialsProvider/IdentityIdProvider';
13+
import { authAPITestParams } from '../testUtils/authApiTestParams';
1514

1615
jest.mock('@aws-amplify/core', () => ({
1716
...jest.requireActual('@aws-amplify/core'),
1817
getId: jest.fn(),
1918
}));
2019
jest.mock('@aws-amplify/core/internals/aws-clients/cognitoIdentity');
21-
jest.mock('../../../src/providers/cognito/credentialsProvider/IdentityIdStore');
20+
jest.mock(
21+
'../../../../src/providers/cognito/credentialsProvider/IdentityIdStore',
22+
);
2223

2324
const ampConfig: ResourcesConfig = {
2425
Auth: {
@@ -140,4 +141,59 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => {
140141
).toBe(authAPITestParams.PrimaryIdentityId.id);
141142
expect(mockGetId).toHaveBeenCalledTimes(1);
142143
});
144+
test('Should return the identityId irresspective of the type if present', async () => {
145+
mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce(
146+
async () => {
147+
return authAPITestParams.PrimaryIdentityId as Identity;
148+
},
149+
);
150+
expect(
151+
await cognitoIdentityIdProvider({
152+
tokens: authAPITestParams.ValidAuthTokens,
153+
authConfig: {
154+
identityPoolId: 'XXXXXXXXXXXXXXXXX',
155+
},
156+
identityIdStore: mockDefaultIdentityIdStoreInstance,
157+
}),
158+
).toBe(authAPITestParams.PrimaryIdentityId.id);
159+
160+
mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce(
161+
async () => {
162+
return authAPITestParams.GuestIdentityId as Identity;
163+
},
164+
);
165+
expect(
166+
await cognitoIdentityIdProvider({
167+
tokens: authAPITestParams.ValidAuthTokens,
168+
authConfig: {
169+
identityPoolId: 'XXXXXXXXXXXXXXXXX',
170+
},
171+
identityIdStore: mockDefaultIdentityIdStoreInstance,
172+
}),
173+
).toBe(authAPITestParams.GuestIdentityId.id);
174+
expect(mockGetId).toHaveBeenCalledTimes(0);
175+
});
176+
test('Should fetch from Cognito when there is no identityId cached', async () => {
177+
mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce(
178+
async () => {
179+
return undefined;
180+
},
181+
);
182+
mockDefaultIdentityIdStoreInstance.storeIdentityId.mockImplementationOnce(
183+
async (identity: Identity) => {
184+
expect(identity.id).toBe(authAPITestParams.PrimaryIdentityId.id);
185+
expect(identity.type).toBe(authAPITestParams.PrimaryIdentityId.type);
186+
},
187+
);
188+
expect(
189+
await cognitoIdentityIdProvider({
190+
tokens: authAPITestParams.ValidAuthTokens,
191+
authConfig: {
192+
identityPoolId: 'us-east-1:test-id',
193+
},
194+
identityIdStore: mockDefaultIdentityIdStoreInstance,
195+
}),
196+
).toBe(authAPITestParams.PrimaryIdentityId.id);
197+
expect(mockGetId).toHaveBeenCalledTimes(1);
198+
});
143199
});

packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts

Lines changed: 14 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
// SPDX-License-Identifier: Apache-2.0
33

4-
import { AuthTokens, ConsoleLogger, Identity, getId } from '@aws-amplify/core';
4+
import { AuthTokens, Identity, getId } from '@aws-amplify/core';
55
import { CognitoIdentityPoolConfig } from '@aws-amplify/core/internals/utils';
66

77
import { AuthError } from '../../../errors/AuthError';
@@ -11,7 +11,6 @@ import { GetIdException } from '../types/errors';
1111
import { IdentityIdStore } from './types';
1212
import { formLoginsMap } from './utils';
1313

14-
const logger = new ConsoleLogger('CognitoIdentityIdProvider');
1514
/**
1615
* Provides a Cognito identityId
1716
*
@@ -33,46 +32,22 @@ export async function cognitoIdentityIdProvider({
3332
identityIdStore.setAuthConfig({ Cognito: authConfig });
3433

3534
// will return null only if there is no identityId cached or if there is an error retrieving it
36-
let identityId: Identity | null = await identityIdStore.loadIdentityId();
35+
const identityId: Identity | null = await identityIdStore.loadIdentityId();
3736

38-
// Tokens are available so return primary identityId
39-
if (tokens) {
40-
// If there is existing primary identityId in-memory return that
41-
if (identityId && identityId.type === 'primary') {
42-
return identityId.id;
43-
} else {
44-
const logins = tokens.idToken
45-
? formLoginsMap(tokens.idToken.toString())
46-
: {};
47-
48-
const generatedIdentityId = await generateIdentityId(logins, authConfig);
49-
50-
if (identityId && identityId.id === generatedIdentityId) {
51-
logger.debug(
52-
`The guest identity ${identityId.id} has become the primary identity.`,
53-
);
54-
}
55-
identityId = {
56-
id: generatedIdentityId,
57-
type: 'primary',
58-
};
59-
}
60-
} else {
61-
// If there is existing guest identityId cached return that
62-
if (identityId && identityId.type === 'guest') {
63-
return identityId.id;
64-
} else {
65-
identityId = {
66-
id: await generateIdentityId({}, authConfig),
67-
type: 'guest',
68-
};
69-
}
37+
if (identityId) {
38+
return identityId.id;
7039
}
40+
const logins = tokens?.idToken
41+
? formLoginsMap(tokens.idToken.toString())
42+
: {};
43+
const generatedIdentityId = await generateIdentityId(logins, authConfig);
44+
// Store generated identityId
45+
identityIdStore.storeIdentityId({
46+
id: generatedIdentityId,
47+
type: tokens ? 'primary' : 'guest',
48+
});
7149

72-
// Store in-memory or local storage depending on guest or primary identityId
73-
identityIdStore.storeIdentityId(identityId);
74-
75-
return identityId.id;
50+
return generatedIdentityId;
7651
}
7752

7853
async function generateIdentityId(

packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -138,11 +138,10 @@ export class CognitoAWSCredentialsAndIdentityIdProvider
138138
},
139139
identityId,
140140
};
141-
const identityIdRes = clientResult.IdentityId;
142-
if (identityIdRes) {
143-
res.identityId = identityIdRes;
141+
if (clientResult.IdentityId) {
142+
res.identityId = clientResult.IdentityId;
144143
this._identityIdStore.storeIdentityId({
145-
id: identityIdRes,
144+
id: clientResult.IdentityId,
146145
type: 'guest',
147146
});
148147
}
@@ -216,11 +215,10 @@ export class CognitoAWSCredentialsAndIdentityIdProvider
216215
};
217216
this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;
218217

219-
const identityIdRes = clientResult.IdentityId;
220-
if (identityIdRes) {
221-
res.identityId = identityIdRes;
218+
if (clientResult.IdentityId) {
219+
res.identityId = clientResult.IdentityId;
222220
this._identityIdStore.storeIdentityId({
223-
id: identityIdRes,
221+
id: clientResult.IdentityId,
224222
type: 'primary',
225223
});
226224
}

0 commit comments

Comments
 (0)