Skip to content

Instantly share code, notes, and snippets.

@alastair-todd
Last active February 27, 2024 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alastair-todd/c6392fb092c6ffd9498d2b85738a8b68 to your computer and use it in GitHub Desktop.
Save alastair-todd/c6392fb092c6ffd9498d2b85738a8b68 to your computer and use it in GitHub Desktop.
Cypress extension for logging in with amplify-js auth
/**
* amplify-js / cognito auth helper
* specific personas are logged-in and their tokens are cached to save on round-trips.
*/
import { Amplify } from 'aws-amplify';
import { signIn, SignInOutput, signOut } from '@aws-amplify/auth';
import { ResourcesConfig } from '@aws-amplify/core';
console.log('configuring amplify');
// configure amplify
const auth = Cypress.env().auth;
const cognitoConfig: ResourcesConfig = {
Auth: {
Cognito: {
userPoolId: auth.userPoolId,
userPoolClientId: auth.userPoolClientId
}
}
};
Amplify.configure(cognitoConfig);
type StorageValue = string | null;
type StorageMap = Map<string, StorageValue>;
const exportStorage = (): StorageMap => {
const keyValueStore = new Map<string, StorageValue>(); // storageMap();
for (let i = 0, l = localStorage.length; i < l; i++) {
const key = localStorage.key(i) as string;
keyValueStore.set(key, localStorage.getItem(key));
}
return keyValueStore;
};
const importStorage = (storage: StorageMap, clearBefore: boolean) => {
if (clearBefore) {
localStorage.clear();
}
storage.forEach((value: StorageValue, key: string) => {
localStorage.setItem(key, value as string);
});
};
const cognitoUserCache = new Map<string, StorageMap>(); // userCache();
Cypress.Commands.add('signInAs', (persona) => {
const userStorage = cognitoUserCache.get(persona.username);
if (userStorage) {
console.log('recycling user', persona.username);
importStorage(userStorage, true);
return;
}
console.log('signing in', persona.username);
return signIn({
username: persona.username,
password: persona.password,
options: {
authFlowType: 'CUSTOM_WITH_SRP'
}
})
.then((output: SignInOutput) => {
cognitoUserCache.set(persona.username, exportStorage());
if (!output.isSignedIn) throw new Error('User could not be signed in');
})
.catch((err: any) => {
console.error(err);
});
});
Cypress.Commands.add('signOut', () => {
console.log('signing out');
return signOut();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment