Skip to content

Commit

Permalink
Merge branch 'next' into temp-signOut
Browse files Browse the repository at this point in the history
  • Loading branch information
jimblanc authored Aug 25, 2023
2 parents 8c7fd33 + a26820e commit e5e2751
Show file tree
Hide file tree
Showing 36 changed files with 454 additions and 242 deletions.
15 changes: 0 additions & 15 deletions packages/analytics/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"scripts": {
"test": "npm run lint && jest -w 1 --coverage",
"test:watch": "tslint 'src/**/*.ts' && jest -w 1 --watch",
"test:size": "size-limit",
"build-with-test": "npm run clean && npm test && tsc && webpack",
"build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js",
"build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm",
Expand Down Expand Up @@ -82,20 +81,6 @@
"@types/uuid": "^9.0.0",
"typescript": "5.0.2"
},
"size-limit": [
{
"name": "Analytics (Pinpoint)",
"path": "./lib-esm/index.js",
"import": "{ Amplify, Analytics, AWSPinpointProvider }",
"limit": "31.57 kB"
},
{
"name": "Analytics (Kinesis)",
"path": "./lib-esm/index.js",
"import": "{ Amplify, Analytics, AWSKinesisProvider }",
"limit": "60.82 kB"
}
],
"jest": {
"globals": {
"ts-jest": {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { AmplifyV6 as Amplify } from 'aws-amplify';
import { decodeJWT, fetchAuthSession } from '@aws-amplify/core/internals/utils';
import * as getUserClient from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider';
import { AuthError } from '../../../src/errors/AuthError';
import { GetUserException } from '../../../src/providers/cognito/types/errors';
import { GetUserCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types';
import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils';
import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data';
import { AmplifyV6 as Amplify } from 'aws-amplify';
import { decodeJWT } from '@aws-amplify/core/internals/utils';
import * as authUtils from '../../../src';
import { fetchUserAttributes } from '../../../src/providers/cognito/apis/fetchUserAttributes';

jest.mock('@aws-amplify/core/lib/clients/handlers/fetch');
jest.mock('@aws-amplify/core/internals/utils', () => ({
...jest.requireActual('@aws-amplify/core/internals/utils'),
fetchAuthSession: jest.fn(),
}));

Amplify.configure({
Auth: {
Expand All @@ -22,23 +26,17 @@ Amplify.configure({
});
const mockedAccessToken =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
const mockFetchAuthSession = fetchAuthSession as jest.Mock;

describe('fetchUserAttributes Happy Path Cases:', () => {
let getUserClientSpy;
let fetchAuthSessionsSpy;

beforeEach(() => {
fetchAuthSessionsSpy = jest
.spyOn(authUtils, 'fetchAuthSession')
.mockImplementationOnce(
async (): Promise<{ tokens: { accessToken: any } }> => {
return {
tokens: {
accessToken: decodeJWT(mockedAccessToken),
},
};
}
);
mockFetchAuthSession.mockResolvedValue({
tokens: {
accessToken: decodeJWT(mockedAccessToken),
},
});
getUserClientSpy = jest
.spyOn(getUserClient, 'getUser')
.mockImplementationOnce(async (): Promise<GetUserCommandOutput> => {
Expand All @@ -56,7 +54,7 @@ describe('fetchUserAttributes Happy Path Cases:', () => {
});
afterEach(() => {
getUserClientSpy.mockClear();
fetchAuthSessionsSpy.mockClear();
mockFetchAuthSession.mockClear();
});

test('fetchUserAttributes should return the current user attributes into a map format', async () => {
Expand All @@ -83,17 +81,12 @@ describe('fetchUserAttributes Error Path Cases:', () => {
buildMockErrorResponse(GetUserException.InvalidParameterException)
)
);
jest
.spyOn(authUtils, 'fetchAuthSession')
.mockImplementationOnce(
async (): Promise<{ tokens: { accessToken: any } }> => {
return {
tokens: {
accessToken: decodeJWT(mockedAccessToken),
},
};
}
);
mockFetchAuthSession.mockResolvedValueOnce({
tokens: {
accessToken: decodeJWT(mockedAccessToken),
},
});

try {
await fetchUserAttributes();
} catch (error) {
Expand Down
56 changes: 26 additions & 30 deletions packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { AmplifyV6 as Amplify } from 'aws-amplify';
import { decodeJWT, fetchAuthSession } from '@aws-amplify/core/internals/utils';
import { AuthError } from '../../../src/errors/AuthError';
import { getCurrentUser } from '../../../src/providers/cognito';
import { InitiateAuthException } from '../../../src/providers/cognito/types/errors';
import { AmplifyV6 as Amplify } from 'aws-amplify';
import { decodeJWT } from '@aws-amplify/core/internals/utils';
import * as authUtils from '../../../src';
import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils';
import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data';

jest.mock('@aws-amplify/core/lib/clients/handlers/fetch');
jest.mock('@aws-amplify/core/internals/utils', () => ({
...jest.requireActual('@aws-amplify/core/internals/utils'),
fetchAuthSession: jest.fn(),
}));

Amplify.configure({
Auth: {
Expand All @@ -20,33 +24,27 @@ Amplify.configure({
});
const mockedAccessToken =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

const mockFetchAuthSession = fetchAuthSession as jest.Mock;
const mockedSub = 'mockedSub';
const mockedUsername = 'XXXXXXXXXXXXXX';

describe('getUser API happy path cases', () => {
let fetchAuthSessionsSpy;
beforeEach(() => {
fetchAuthSessionsSpy = jest
.spyOn(authUtils, 'fetchAuthSession')
.mockImplementationOnce(
async (): Promise<{ tokens: { accessToken: any; idToken: any } }> => {
return {
tokens: {
accessToken: decodeJWT(mockedAccessToken),
idToken: {
payload: {
sub: mockedSub,
'cognito:username': mockedUsername,
},
},
},
};
}
);
mockFetchAuthSession.mockResolvedValue({
tokens: {
accessToken: decodeJWT(mockedAccessToken),
idToken: {
payload: {
sub: mockedSub,
'cognito:username': mockedUsername,
},
},
},
});
});

afterEach(() => {
fetchAuthSessionsSpy.mockClear();
mockFetchAuthSession.mockClear();
});

test('get current user', async () => {
Expand All @@ -58,14 +56,12 @@ describe('getUser API happy path cases', () => {
describe('getUser API error path cases:', () => {
test('getUser API should raise service error', async () => {
expect.assertions(2);
jest
.spyOn(authUtils, 'fetchAuthSession')
.mockImplementationOnce(async () => {
throw new AuthError({
name: InitiateAuthException.InternalErrorException,
message: 'error at fetchAuthSession',
});
mockFetchAuthSession.mockImplementationOnce(async () => {
throw new AuthError({
name: InitiateAuthException.InternalErrorException,
message: 'error at fetchAuthSession',
});
});
(fetchTransferHandler as jest.Mock).mockResolvedValue(
mockJsonResponse(
buildMockErrorResponse(InitiateAuthException.InternalErrorException)
Expand Down
9 changes: 0 additions & 9 deletions packages/auth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
},
"scripts": {
"test": "yarn lint --fix && jest -w 1 --coverage",
"test:size": "size-limit",
"build-with-test": "npm test && npm run build",
"build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js",
"build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm",
Expand Down Expand Up @@ -93,14 +92,6 @@
"@aws-sdk/client-cognito-identity-provider": "3.54.0",
"@jest/test-sequencer": "^24.9.0"
},
"size-limit": [
{
"name": "Auth (top-level class)",
"path": "./lib-esm/index.js",
"import": "{ Amplify, Auth }",
"limit": "57.19 kB"
}
],
"jest": {
"globals": {
"ts-jest": {
Expand Down
30 changes: 4 additions & 26 deletions packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,9 @@
// SPDX-License-Identifier: Apache-2.0

import { AmplifyV6 } from '@aws-amplify/core';
import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';
import { getUser } from '../utils/clients/CognitoIdentityProvider';
import {
GetUserException,
InitiateAuthException,
} from '../../cognito/types/errors';
import { AuthUserAttribute, fetchAuthSession } from '../../../';
import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils';
import { assertAuthTokens } from '../utils/types';
import { AuthUserAttribute } from '../../../types';
import { CognitoUserAttributeKey } from '../types';
import { toAuthUserAttribute } from '../utils/apiHelpers';
import { fetchUserAttributes as fetchUserAttributesInternal } from './internal/fetchUserAttributes';

/**
* Fetches the current user attributes while authenticated.
Expand All @@ -21,22 +13,8 @@ import { toAuthUserAttribute } from '../utils/apiHelpers';
*
* @throws AuthTokenConfigException - Thrown when the token provider config is invalid.
*/
export const fetchUserAttributes = async (): Promise<
export const fetchUserAttributes = (): Promise<
AuthUserAttribute<CognitoUserAttributeKey>
> => {
const authConfig = AmplifyV6.getConfig().Auth;
assertTokenProviderConfig(authConfig);
const { tokens } = await fetchAuthSession({
forceRefresh: false,
});
assertAuthTokens(tokens);

const { UserAttributes } = await getUser(
{ region: getRegion(authConfig.userPoolId) },
{
AccessToken: tokens.accessToken.toString(),
}
);

return toAuthUserAttribute(UserAttributes);
return fetchUserAttributesInternal(AmplifyV6);
};
22 changes: 4 additions & 18 deletions packages/auth/src/providers/cognito/apis/getCurrentUser.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { AmplifyV6 as Amplify } from '@aws-amplify/core';
import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';
import { fetchAuthSession } from '../../../';
import { GetCurrentUserRequest, AuthUser } from '../../../types';
import { assertAuthTokens } from '../utils/types';
import { InitiateAuthException } from '../types/errors';
import { AmplifyV6 } from '@aws-amplify/core';
import { AuthUser, GetCurrentUserRequest } from '../../../types';
import { getCurrentUser as getCurrentUserInternal } from './internal/getCurrentUser';

/**
* Gets the current user from the idToken.
Expand All @@ -22,16 +19,5 @@ import { InitiateAuthException } from '../types/errors';
export const getCurrentUser = async (
getCurrentUserRequest?: GetCurrentUserRequest
): Promise<AuthUser> => {
const authConfig = Amplify.getConfig().Auth;
assertTokenProviderConfig(authConfig);
const { tokens } = await fetchAuthSession({
forceRefresh: getCurrentUserRequest?.recache ?? false,
});
assertAuthTokens(tokens);
const { payload } = tokens.idToken;

return {
username: payload['cognito:username'] as string,
userId: payload['sub'] as string,
};
return getCurrentUserInternal(AmplifyV6, getCurrentUserRequest);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { AmplifyClassV6 } from '@aws-amplify/core';
import {
assertTokenProviderConfig,
fetchAuthSession,
} from '@aws-amplify/core/internals/utils';
import { getUser } from '../../utils/clients/CognitoIdentityProvider';
import { AuthUserAttribute } from '../../../..';
import { getRegion } from '../../utils/clients/CognitoIdentityProvider/utils';
import { assertAuthTokens } from '../../utils/types';
import { CognitoUserAttributeKey } from '../../types';
import { toAuthUserAttribute } from '../../utils/apiHelpers';

export const fetchUserAttributes = async (
amplify: AmplifyClassV6
): Promise<AuthUserAttribute<CognitoUserAttributeKey>> => {
const authConfig = amplify.getConfig().Auth;
assertTokenProviderConfig(authConfig);
const { tokens } = await fetchAuthSession(amplify, {
forceRefresh: false,
});
assertAuthTokens(tokens);

const { UserAttributes } = await getUser(
{ region: getRegion(authConfig.userPoolId) },
{
AccessToken: tokens.accessToken.toString(),
}
);

return toAuthUserAttribute(UserAttributes);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { AmplifyClassV6 } from '@aws-amplify/core';
import {
assertTokenProviderConfig,
fetchAuthSession,
} from '@aws-amplify/core/internals/utils';
import { GetCurrentUserRequest, AuthUser } from '../../../../types';
import { assertAuthTokens } from '../../utils/types';

export const getCurrentUser = async (
amplify: AmplifyClassV6,
getCurrentUserRequest?: GetCurrentUserRequest
): Promise<AuthUser> => {
const authConfig = amplify.getConfig().Auth;
assertTokenProviderConfig(authConfig);
const { tokens } = await fetchAuthSession(amplify, {
forceRefresh: getCurrentUserRequest?.recache ?? false,
});
assertAuthTokens(tokens);
const { payload } = tokens.idToken;

return {
username: payload['cognito:username'] as string,
userId: payload['sub'] as string,
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import {
AmplifyServer,
getAmplifyServerContext,
} from '@aws-amplify/core/internals/adapter-core';
import { AuthUserAttribute } from '../../../../types';
import { CognitoUserAttributeKey } from '../../types';
import { fetchUserAttributes as fetchUserAttributesInternal } from '../internal/fetchUserAttributes';

export const fetchUserAttributes = (
contextSpec: AmplifyServer.ContextSpec
): Promise<AuthUserAttribute<CognitoUserAttributeKey>> => {
return fetchUserAttributesInternal(
getAmplifyServerContext(contextSpec).amplify
);
};
Loading

0 comments on commit e5e2751

Please sign in to comment.