npm package: @merl.ooo/sso-login
Description: merl.ooo-sso frontend login lib
Author: Christian Hotz
Latest version: 0.5.1

[![npm version](https://badge.fury.io/js/@merl.ooo%2Fsso-login.svg)](https://badge.fury.io/js/@merl.ooo%2Fsso-login)

# @merl.ooo/sso-login

Frontend library for logging in to merl.ooo-sso, checking if logged in and logging out

## Installation

```shell
npm i @merl.ooo/sso-login
```

## Usage

Have a look at the demo page at [sso-login.demo.merl.ooo](https://sso-login.demo.merl.ooo/).
[It](https://gitlab.com/merl.ooo/libs/sso-login/-/blob/master/demo/src/index.js) is basically just
using the below methods on the corresponding buttons and adding some in-browser logging.

### SSO.login()

Use the following to log the user in.

This opens a tab of the `sso.merl.ooo/login` page (which redirects to OAuth approval page).
The OAuth redirect is caught,
the user data bubbles up to the parent window (your app) via postMessage,
and this library handles it back to you.
You can then use the user `access_token` to authorize API requests.

```js
import SSO from '@merl.ooo/sso-login';

SSO.login()
  .then(user => console.log('user logged in, access_token =', user.access_token));
  .catch(err => {
    if (err instanceof sso.AuthorizationFailedError) console.log('authorization failed (probably a CORB issue)');
    else console.error(err); // some internal error
  })
```

### SSO.refreshLogin()

Use the following to refresh the login of a user every once in a while.

This is also internally used by [`.check()`](#SSOcheck), if the users cookie exists but token expired.

This opens the `sso.merl.ooo/login` page in a hidden iframe, hoping the user already accepted
the OAuth stuff and the OAuth page requires no user interaction.
If so, it handles the gained user data back to you.

**NOTE**: If interaction is needed, it will run into a timeout.
So, for your convenience you should only call this if you're sure the current token is not expired
(e.g. after immediately after calling [`.check()`](#SSOcheck))

```js
import SSO from '@merl.ooo/sso-login';

SSO.refreshLogin()
  .then(user => {
    if (user === null) console.log('there is no user logged in');
    else console.log('user logged in, access_token =', user.access_token);
  })
  .catch(err => {
    if (err instanceof sso.AuthorizationFailedError) console.log('authorization failed (probably a CORB issue or oauth page requires interaction)');
    else console.error(err); // some internal error
  });
```

### SSO.check()

Use the following to check if a user is logged in.

This calls the `GET sso.merl.ooo/sso` endpoint which returns auth cookie content
and handles it back to you.
By passing the `{ asynchronous: false }` option, you can make the HTTP call synchronouse
(Caution: this blocks your page, but it's necessary if you want to call [`.login()`](#login).
If you would call check asynchronously, then the window.open in `.login` will be blocked by browsers.)

```js
import SSO from '@merl.ooo/sso-login';

SSO.check()
  .then(user => {
    if (user === null) console.log('there is no user logged in with this browser');
    else console.log('user logged in, access_token =', user.access_token);
  });

// OR synchonously

const user = SSO.check({ asynchronous: false });
// here you can do something like window.open() without being blocked by the browser
```

### SSO.logout()

Use the following to log the user out of your app (and only this app, not sso entirely).

NOTE:
This DOES NOT call the `DELETE sso.merl.ooo/sso` endpoint which deletes the sso auth cookie if set.

```js
import SSO from '@merl.ooo/sso-login';

SSO.logout()
  .then(() => console.log('logged out from <your app>'));
```

### SSO.logoutGlobally()

Use the following to log the user out of SSO entirely.

This calls the `DELETE sso.merl.ooo/sso` endpoint which deletes the sso auth cookie if set.

```js
import SSO from '@merl.ooo/sso-login';

SSO.logoutGlobally()
  .then(() => console.log('logged out from SSO entirely'));
```

### Custom Instance

You can change all of the above default behaviour by instanciating your own instance of the
underlying `SSO` class with some different options (defaults shown below).

```js
import SSO from '@merl.ooo/sso-login';

const sso = SSO.create({
  baseUrl: 'https://sso.merl.ooo', // url of the SSO service
  timeout: 5000, // timeout for http requests and hidden iframe callbacks of the SSO service
  storage: window.sessionStorage, // globalThis.Storage compliant storage used for user data
  storageKey: 'merl-sso-user', // key to be used for user data in the storage given above
  endpoints: { // request endpoints for requests to the SSO service (relative to `baseUrl`)
    login: { method: 'GET', url: 'login' }, // login page (method ignored, will be opened _blank)
    check: { method: 'POST', url: 'sso' }, // endpoint where user data is returned if logged in
    logout: { method: 'DELETE', url: 'sso' }, // endpoint to end login session (eg. remove cookie)
  },
});

sso.login()
  .then(user => console.log('user logged in, access_token =', user.access_token))
  .then(sso.check)
  .then(user => console.log('user still logged in, access_token =', user.access_token))
  .then(sso.refreshLogin)
  .then(user => console.log('user still logged in, access_token =', user.access_token))
  .then(sso.logout)
  .then(() => console.log('logged out from <your app>'));
  .then(sso.logoutGlobally)
  .then(() => console.log('logged out from SSO entirely'));
```