Skip to content

Instantly share code, notes, and snippets.

@sir-dunxalot
Last active May 26, 2020 20:48
Show Gist options
  • Select an option

  • Save sir-dunxalot/f88ce6eb51611ec72ce27fa1002440f3 to your computer and use it in GitHub Desktop.

Select an option

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-auehtnticated user's username */
let cachedUsername;
Cypress.Commands.add('_login', /* ... */);
Cypress.Commands.add('login', () => {
/* 2. We see if a session cookie already exists */
cy.getCookie(sessionCookieName).then((cookieValue) => {
/* 3. We see if the user is the same user previously auethenticated */
const cachedUserIsCurrentUser = cachedUsername && cachedUsername === username;
/* 4. 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'),
};
/* 5. 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) => {
/* https://github.com/auth0/nextjs-auth0/blob/master/src/handlers/callback.ts#L44 */
/* https://github.com/auth0/nextjs-auth0/blob/master/src/handlers/callback.ts#L47 */
/* https://github.com/auth0/nextjs-auth0/blob/master/src/session/cookie-store/index.ts#L57 */
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