Skip to content

Instantly share code, notes, and snippets.

@sir-dunxalot
Last active May 26, 2020 20:48
Show Gist options
  • Save sir-dunxalot/f88ce6eb51611ec72ce27fa1002440f3 to your computer and use it in GitHub Desktop.
Save sir-dunxalot/f88ce6eb51611ec72ce27fa1002440f3 to your computer and use it in GitHub Desktop.
cypress-nextjs-auth0__helper--login-with-cache
import auth0 from 'auth0-js';
import Iron from '@hapi/iron';
const auth = new auth0.WebAuth({
domain: Cypress.env('auth0Domain'),
clientID: Cypress.env('auth0ClientId'),
});
const sessionCookieName = Cypress.env('sessionCookieName');
const stateCookieName = Cypress.env('stateCookieName');
/* 1. Let's plan to store the already-authenticated user's username */
let cachedUsername;
/*
2. Keep auth cookies between tests
https://docs.cypress.io/api/cypress-api/cookies.html#Defaults
*/
Cypress.Cookies.defaults({
whitelist: [sessionCookieName, stateCookieName],
});
Cypress.Commands.add('_login', /* ... */);
Cypress.Commands.add('login', () => {
/* 3. We see if a session cookie already exists */
cy.getCookie(sessionCookieName).then((cookieValue) => {
/* 4. We see if the user is the same user previously auethenticated */
const cachedUserIsCurrentUser = cachedUsername && cachedUsername === username;
/* 5. If the user is already authenticated, return true, which skips the rest of the helper code */
if (cookieValue && cachedUserIsCurrentUser) {
return true;
} else {
const credentials = {
username: Cypress.env('auth0Username'),
password: Cypress.env('auth0Password'),
};
/* 6. Clear any cookie before authenticating in case the user was changed since last authentication */
cy.clearCookies();
cy.setCookie(stateCookieName, 'some-random-state');
cy._login(credentials).then((response) => {
const { accessToken, expiresIn, idToken, scope } = response;
cy.getUserInfo(accessToken).then((user) => {
const persistedSession = {
user,
idToken,
accessToken,
accessTokenScope: scope,
accessTokenExpiresAt: Date.now() + expiresIn,
createdAt: Date.now(),
};
cy.seal(persistedSession).then((encryptedSession) => {
cy.setCookie(sessionCookieName, encryptedSession);
});
});
});
}
});
});
Cypress.Commands.add('getUserInfo', /* ... */);
Cypress.Commands.add('seal', /* ... */);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment