Skip to content

Commit

Permalink
fix(deps): update aws-amplify to v6
Browse files Browse the repository at this point in the history
  • Loading branch information
renovate[bot] authored and aadedejifearless committed Dec 20, 2024
1 parent 9a77627 commit 1033696
Show file tree
Hide file tree
Showing 4 changed files with 1,314 additions and 750 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
"wipit": "git add -A && git commit -m 'wip [skip ci]' --no-verify"
},
"dependencies": {
"@aws-amplify/auth": "5.6.1",
"@aws-amplify/core": "5.8.1",
"@aws-amplify/auth": "6.9.0",
"@aws-amplify/core": "6.7.3",
"@aws-crypto/client-node": "4.0.2",
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-sdk/client-cloudwatch-logs": "3.417.0",
Expand Down Expand Up @@ -60,6 +60,7 @@
"@storybook/addon-outline": "7.6.20",
"@types/mdast": "4.0.4",
"airtable": "0.12.2",
"aws-amplify": "6.11.0",
"axios": "1.7.8",
"babel-jest": "29.7.0",
"body-parser": "1.20.3",
Expand Down
4 changes: 2 additions & 2 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@
"endOfLine": "auto"
},
"dependencies": {
"@aws-amplify/auth": "5.6.1",
"@aws-amplify/core": "5.8.1",
"@aws-amplify/auth": "6.9.0",
"@aws-amplify/core": "6.7.3",
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-sdk/protocol-http": "3.370.0",
"@aws-sdk/s3-request-presigner": "3.417.0",
Expand Down
147 changes: 76 additions & 71 deletions web/src/lib/auth/sessionHelper.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
import { ActiveUser } from "@/lib/auth/AuthContext";
import { AccountLinkingErrorStorageFactory } from "@/lib/storage/AccountLinkingErrorStorage";
import { Auth } from "@aws-amplify/auth";
import { UpdateUserAttributesInput } from "@aws-amplify/auth/src/providers/cognito/types";
import { LegacyConfig } from "@aws-amplify/core/dist/esm/libraryUtils";
import { CredentialsAndIdentityId } from "@aws-amplify/core/src/singleton/Auth/types";
import { Sha256 } from "@aws-crypto/sha256-browser";
import { HttpRequest } from "@aws-sdk/protocol-http";
import { S3RequestPresigner } from "@aws-sdk/s3-request-presigner";
import { parseUrl } from "@aws-sdk/url-parser";
import { formatUrl } from "@aws-sdk/util-format-url";
import axios, { AxiosResponse } from "axios";
import { Amplify } from "aws-amplify/";
import {
fetchAuthSession,
getCurrentUser,
JWT,
signInWithRedirect,
SignInWithRedirectInput,
signOut,
updateUserAttributes,
} from "aws-amplify/auth";

type CognitoIdPayload = {
aud: string;
Expand Down Expand Up @@ -34,55 +45,70 @@ type CognitoIdentityPayload = {
userId: string;
};

type CognitoRefreshAuthResult = {
AuthenticationResult: {
AccessToken: string;
ExpiresIn: number;
IdToken: string;
TokenType: string;
export const getCredentialsAndIdentity = async (): Promise<CredentialsAndIdentityId> => {
const session = await fetchAuthSession({ forceRefresh: true });
const credentials = session?.credentials;
const identityId = session?.identityId;
if (!credentials || !identityId) {
throw new Error("Missing AWS credentials or IdentityId");
}
return {
credentials,
identityId,
};
};

type CognitoRefreshAuth = {
token: string;
expires_at: number;
identity_id: string;
};

export const configureAmplify = (): void => {
Auth.configure({
identityPoolRegion: process.env.AWS_REGION,
identityPoolId: process.env.COGNITO_IDENTITY_POOL_ID,
region: process.env.AWS_REGION,
userPoolId: process.env.COGNITO_USER_POOL_ID,
userPoolWebClientId: process.env.COGNITO_WEB_CLIENT_ID,
ssr: true,
oauth: {
domain: process.env.AUTH_DOMAIN,
scope: ["email", "profile", "openid", "aws.cognito.signin.user.admin"],
redirectSignIn: process.env.REDIRECT_URL,
redirectSignOut: process.env.REDIRECT_URL,
responseType: "code",
},
refreshHandlers: {
myNJ: refreshToken,
const amplifyConfig = {
Auth: {
identityPoolRegion: process.env.AWS_REGION,
identityPoolId: process.env.COGNITO_IDENTITY_POOL_ID,
region: process.env.AWS_REGION,
userPoolId: process.env.COGNITO_USER_POOL_ID,
userPoolWebClientId: process.env.COGNITO_WEB_CLIENT_ID,
ssr: true,
oauth: {
domain: process.env.AUTH_DOMAIN,
scope: ["email", "profile", "openid", "aws.cognito.signin.user.admin"],
redirectSignIn: process.env.REDIRECT_URL,
redirectSignOut: process.env.REDIRECT_URL,
responseType: "code",
},
},
});
};
Amplify.configure(amplifyConfig as LegacyConfig);
};

export const triggerSignOut = async (): Promise<void> => {
await Auth.signOut();
await signOut();
};

export const triggerSignIn = async (): Promise<void> => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
configureAmplify();
await Auth.federatedSignIn({ customProvider: "myNJ" });
const input: SignInWithRedirectInput = {
provider: {
custom: "myNJ",
},
};
await signInWithRedirect(input);
};

export const getAuthenticatedUser = async () => {
const user = await getCurrentUser();
const userName = user.username;
const authenticationFlowType = user.signInDetails?.authFlowType;

// Might need to put this above in a try catch so handle cases where username or authenticationFlowType is undefined. ??
return {
username: userName.toString(),
authenticationFlowType,
};
};
export const getSignedS3Link = async (value: string, expires?: number): Promise<string> => {
const credentials = await Auth.currentUserCredentials();
const credentialsAndIdentityId = await getCredentialsAndIdentity();
const credentials = credentialsAndIdentityId.credentials;
const presigner = new S3RequestPresigner({
credentials,
region: process.env.AWS_REGION || "us-east-1",
Expand All @@ -93,21 +119,27 @@ export const getSignedS3Link = async (value: string, expires?: number): Promise<
return formatUrl(url);
};

export const getCurrentToken = async (): Promise<string> => {
const cognitoSession = await Auth.currentSession();
return cognitoSession.getIdToken().getJwtToken();
export const getCurrentToken = async (): Promise<JWT> => {
const session = await fetchAuthSession({ forceRefresh: true });
if (!session || !session.tokens || !session.tokens.idToken) {
throw new Error("Unable to retrieve access token. Ensure the session is valid.");
}
return session.tokens.idToken;
};

export const getActiveUser = async (): Promise<ActiveUser> => {
configureAmplify();
const cognitoSession = await Auth.currentSession();
const cognitoPayload = cognitoSession.getIdToken().decodePayload() as CognitoIdPayload;
const cognitoSession = await getCurrentToken();
const cognitoPayload = cognitoSession.payload as CognitoIdPayload;
if (!cognitoPayload["custom:identityId"]) {
const user = await Auth.currentAuthenticatedUser();
const credentials = await Auth.currentUserCredentials();
await Auth.updateUserAttributes(user, {
"custom:identityId": credentials.identityId,
});
const credentialsAndIdentityId = await getCredentialsAndIdentity();
// const { username } = await getAuthenticatedUser();
const input: UpdateUserAttributesInput = {
userAttributes: {
"custom:identityId": credentialsAndIdentityId.identityId,
},
};
await updateUserAttributes(input);
}
const encounteredMyNjLinkingError = AccountLinkingErrorStorageFactory().getEncounteredMyNjLinkingError();
return cognitoPayloadToActiveUser({ cognitoPayload, encounteredMyNjLinkingError });
Expand All @@ -129,30 +161,3 @@ const cognitoPayloadToActiveUser = ({
encounteredMyNjLinkingError,
};
};

export const refreshToken = async (): Promise<CognitoRefreshAuth> => {
const cognitoSession = await Auth.currentSession();
const token = cognitoSession.getRefreshToken().getToken();
return axios
.post(
"https://cognito-idp.us-east-1.amazonaws.com/",
{
ClientId: process.env.COGNITO_WEB_CLIENT_ID,
AuthFlow: "REFRESH_TOKEN_AUTH",
AuthParameters: { REFRESH_TOKEN: token },
},
{
headers: {
"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth",
"Content-Type": "application/x-amz-json-1.1",
},
}
)
.then((response: AxiosResponse<CognitoRefreshAuthResult>) => {
return {
token: response.data.AuthenticationResult.AccessToken,
expires_at: response.data.AuthenticationResult.ExpiresIn,
identity_id: response.data.AuthenticationResult.IdToken,
};
});
};
Loading

0 comments on commit 1033696

Please sign in to comment.