· 5 years ago · Oct 26, 2019, 02:32 AM
1Cypress.Commands.add(
2 'login',
3 (username, password, appState = { target: '/' }) => {
4 cy.log(`Logging in as ${username}`);
5 const options = {
6 method: 'POST',
7 url: Cypress.env('Auth0TokenUrl'),
8 body: {
9 grant_type: 'password',
10 username,
11 password,
12 audience: Cypress.env('Auth0Audience'),
13 scope: 'openid profile email',
14 client_id: Cypress.env('Auth0ClientId'),
15 client_secret: Cypress.env('Auth0ClientSecret')
16 }
17 };
18 cy.request(options).then(({ body }) => {
19 const { access_token, expires_in, id_token } = body;
20
21 cy.server();
22
23 // intercept Auth0 request for token and return what we have
24 cy.route({
25 url: 'oauth/token',
26 method: 'POST',
27 response: {
28 access_token,
29 expires_in,
30 id_token,
31 token_type: 'Bearer'
32 }
33 });
34
35 // Auth0 SPA SDK will check for value in cookie to get appState
36 // and validate nonce (which has been removed for simplicity)
37 const stateId = 'test';
38 const encodedAppState = encodeURI(JSON.stringify(appState));
39 cy.setCookie(
40 `a0.spajs.txs.${stateId}`,
41 `{%22appState%22:${encodedAppState}%2C%22scope%22:%22openid%20profile%20email%22%2C%22audience%22:%22default%22}`
42 );
43
44 const callbackUrl = `/auth/callback?code=test-code&state=${stateId}`;
45 return cy.visit(callbackUrl);
46 });
47 }
48);
49
50declare namespace Cypress {
51 interface Chainable<Subject> {
52 login(
53 username: string,
54 password: string,
55 appState?: any
56 ): Chainable<Subject>;
57 }
58}