---
permalink: /plugins/auth
editLink: false
sidebar: auto
title: auth
---

<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

## auth

Logs user in for the first test and reuses session for next tests.
Works by saving cookies into memory or file.
If a session expires automatically logs in again.

> For better development experience cookies can be saved into file, so a session can be reused while writing tests.

#### Usage

1.  Enable this plugin and configure as described below
2.  Define user session names (example: `user`, `editor`, `admin`, etc).
3.  Define how users are logged in and how to check that user is logged in
4.  Use `login` object inside your tests to log in:

```js
// inside a test file
// use login to inject auto-login function
Feature('Login');

Before(({ login }) => {
   login('user'); // login using user session
});

// Alternatively log in for one scenario.
Scenario('log me in', ( { I, login } ) => {
   login('admin');
   I.see('I am logged in');
});
```

#### Configuration

*   `saveToFile` (default: false) - save cookies to file. Allows to reuse session between execution.
*   `inject` (default: `login`) - name of the login function to use
*   `users` - an array containing different session names and functions to:
    *   `login` - sign in into the system
    *   `check` - check that user is logged in
    *   `fetch` - to get current cookies (by default `I.grabCookie()`)
    *   `restore` - to set cookies (by default `I.amOnPage('/'); I.setCookie(cookie)`)

#### How It Works

1.  `restore` method is executed. It should open a page and set credentials.
2.  `check` method is executed. It should reload a page (so cookies are applied) and check that this page belongs to logged-in user. When you pass the second args `session`, you could perform the validation using passed session.
3.  If `restore` and `check` were not successful, `login` is executed
4.  `login` should fill in login form
5.  After successful login, `fetch` is executed to save cookies into memory or file.

#### Example: Simple login

```js
auth: {
  enabled: true,
  saveToFile: true,
  inject: 'login',
  users: {
    admin: {
      // loginAdmin function is defined in `steps_file.js`
      login: (I) => I.loginAdmin(),
      // if we see `Admin` on page, we assume we are logged in
      check: (I) => {
         I.amOnPage('/');
         I.see('Admin');
      }
    }
  }
}
```

#### Example: Multiple users

```js
auth: {
  enabled: true,
  saveToFile: true,
  inject: 'loginAs', // use `loginAs` instead of login
  users: {
    user: {
      login: (I) => {
         I.amOnPage('/login');
         I.fillField('email', 'user@site.com');
         I.fillField('password', '123456');
         I.click('Login');
      },
      check: (I) => {
         I.amOnPage('/');
         I.see('User', '.navbar');
      },
    },
    admin: {
      login: (I) => {
         I.amOnPage('/login');
         I.fillField('email', 'admin@site.com');
         I.fillField('password', '123456');
         I.click('Login');
      },
      check: (I) => {
         I.amOnPage('/');
         I.see('Admin', '.navbar');
      },
    },
  }
}
```

#### Example: Keep cookies between tests

If you decide to keep cookies between tests you don't need to save/retrieve cookies between tests.
But you need to login once work until session expires.
For this case, disable `fetch` and `restore` methods.

```js
helpers: {
   WebDriver: {
     // config goes here
     keepCookies: true; // keep cookies for all tests
   }
},
plugins: {
   auth: {
     users: {
       admin: {
         login: (I) => {
           I.amOnPage('/login');
           I.fillField('email', 'admin@site.com');
           I.fillField('password', '123456');
           I.click('Login');
         },
         check: (I) => {
           I.amOnPage('/dashboard');
           I.see('Admin', '.navbar');
         },
         fetch: () => {}, // empty function
         restore: () => {}, // empty funciton
       }
    }
  }
}
```

#### Example: Getting sessions from local storage

If your session is stored in local storage instead of cookies you still can obtain sessions.

```js
plugins: {
   auth: {
    admin: {
      login: (I) => I.loginAsAdmin(),
      check: (I) => I.see('Admin', '.navbar'),
      fetch: (I) => {
        return I.executeScript(() => localStorage.getItem('session_id'));
      },
      restore: (I, session) => {
        I.amOnPage('/');
        I.executeScript((session) => localStorage.setItem('session_id', session), session);
      },
    }
  }
}
```

#### Tips: Using async function in the auth

If you use async functions in the auth plugin, login function should be used with `await` keyword.

```js
auth: {
  enabled: true,
  saveToFile: true,
  inject: 'login',
  users: {
    admin: {
      login: async (I) => {  // If you use async function in the auth plugin
         const phrase = await I.grabTextFrom('#phrase')
         I.fillField('username', 'admin'),
         I.fillField('password', 'password')
         I.fillField('phrase', phrase)
      },
      check: (I) => {
         I.amOnPage('/');
         I.see('Admin');
      },
    }
  }
}
```

```js
Scenario('login', async ( {I, login} ) => {
  await login('admin') // you should use `await`
})
```

#### Tips: Using session to validate user

Instead of asserting on page elements for the current user in `check`, you can use the `session` you saved in `fetch`

```js
auth: {
  enabled: true,
  saveToFile: true,
  inject: 'login',
  users: {
    admin: {
      login: async (I) => {  // If you use async function in the auth plugin
         const phrase = await I.grabTextFrom('#phrase')
         I.fillField('username', 'admin'),
         I.fillField('password', 'password')
         I.fillField('phrase', phrase)
      },
      check: (I, session) => {
         // Throwing an error in `check` will make CodeceptJS perform the login step for the user
         if (session.profile.email !== the.email.you.expect@some-mail.com) {
              throw new Error ('Wrong user signed in');
        }
      },
    }
  }
}
```

```js
Scenario('login', async ( {I, login} ) => {
  await login('admin') // you should use `await`
})
```

### Parameters

*   `config` &#x20;
