{"id":16230754,"url":"https://github.com/jerelmiller/redux-simple-auth","last_synced_at":"2025-03-19T14:30:31.363Z","repository":{"id":57351568,"uuid":"88134692","full_name":"jerelmiller/redux-simple-auth","owner":"jerelmiller","description":"A library for implementing authentication and authorization for redux applications","archived":false,"fork":false,"pushed_at":"2019-02-02T10:40:48.000Z","size":583,"stargazers_count":20,"open_issues_count":6,"forks_count":5,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-17T07:51:24.055Z","etag":null,"topics":["authentication","middleware","redux"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/redux-simple-auth","language":"JavaScript","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jerelmiller.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-04-13T06:55:50.000Z","updated_at":"2022-12-06T21:35:01.000Z","dependencies_parsed_at":"2022-09-19T13:12:02.503Z","dependency_job_id":null,"html_url":"https://github.com/jerelmiller/redux-simple-auth","commit_stats":null,"previous_names":[],"tags_count":26,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jerelmiller%2Fredux-simple-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jerelmiller%2Fredux-simple-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jerelmiller%2Fredux-simple-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jerelmiller%2Fredux-simple-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jerelmiller","download_url":"https://codeload.github.com/jerelmiller/redux-simple-auth/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244444408,"owners_count":20453719,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","middleware","redux"],"created_at":"2024-10-10T13:01:16.492Z","updated_at":"2025-03-19T14:30:31.059Z","avatar_url":"https://github.com/jerelmiller.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build Status](https://travis-ci.org/jerelmiller/redux-simple-auth.svg?branch=master)](https://travis-ci.org/jerelmiller/redux-simple-auth)\n[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)\n[![npm version](https://img.shields.io/npm/v/redux-simple-auth.svg?style=flat-square)](https://www.npmjs.com/package/redux-simple-auth)\n[![lerna](https://img.shields.io/badge/maintained%20with-lerna-cc00ff.svg)](https://lernajs.io/)\n\n⚠️ **A note from the author** ⚠️\n\nWhen I first started this project, I had ambitions that I would be able to\neventually turn this into something the larger audience could use. While I am\nproud at some of the work done here, I just have too much else to focus on. Feel\nfree to use this library, fork it, build on it, etc. While I may occasionally\ncontribute to this library, I am unlikely to maintain it on a regular cadence. I\nwant to thank everyone that has used this library.\n\n# Redux Simple Auth\n\n\nRedux Simple Auth is a library for implementing authentication and authorization\nwithin redux applications. Inspired by the wonderful [Ember Simple\nAuth](http://ember-simple-auth.com/) library, its aim is to make authentication\n/ authorization simple and flexible for any application.\n\n## Table of Contents\n\n* [Installation](#installation)\n* [Development](#development)\n* [Usage](#usage)\n  * [Setup](#setup)\n    * [Middleware](#apply-the-middleware)\n    * [Reducer](#add-the-reducer)\n    * [Store enhancer](#optionally-add-the-store-enhancer)\n* [How does it work?](#how-does-it-work)\n* [Configuration](#configuration)\n* [Authenticators](#authenticators)\n  * [Built-in Authenticators](#built-in-authenticators)\n  * [Custom Authenticators](#implementing-a-custom-authenticator)\n* [Session Storage](#session-storage)\n  * [Built-in Session Stores](#built-in-session-stores)\n  * [Customize a Store](#customizing-a-built-in-store)\n  * [Custom Stores](#implementing-a-custom-session-store)\n* [Authorizer](#authorizer)\n  * [Built-in Authorizers](#built-in-authorizers)\n  * [Custom Authorizers](#implementing-a-custom-authorizer)\n  * [Store enhancer](#store-enhancer)\n* [Refreshing the session](#refreshing-the-session)\n* [Actions](#actions)\n* [Selectors](#selectors)\n* [Action Types](#action-types)\n* [TODO](#todo)\n* [License](#license)\n\n## Installation\n\nnpm:\n```\nnpm install --save redux-simple-auth\n```\n\nyarn:\n```\nyarn add redux-simple-auth\n```\n\n## Development\n\nIf you're trying to develop with this package check out the [development](./DEVELOPMENT.md)\ndocs for environment setup information.\n\n## Usage\n\n### Setup\n\nThis library ships with middleware, a reducer, and an optional store enhancer.\nYou will need to do the following:\n\n##### Apply the middleware\n\n```javascript\nimport { createStore, applyMiddleware } from 'redux'\nimport { createAuthMiddleware } from 'redux-simple-auth'\nimport rootReducer from './reducers'\n\n// Authenticators and configuration options are discussed below\nconst authMiddleware = createAuthMiddleware({ authenticator: myAuthenticator })\n\nconst store = createStore(\n  rootReducer,\n  /* initialState, */\n  applyMiddleware(authMiddleware)\n)\n```\n\n##### Add the reducer\n\nYou will need to apply the reducer as `session`. Redux Simple Auth does not\nsupport custom names for the reducer key.\n\n```javascript\nimport { combineReducers } from 'redux'\nimport { reducer as session } from 'redux-simple-auth'\n\nexport default combineReducers({\n  // ...reducers\n  session\n})\n```\n\n##### Optionally add the store enhancer\n\nIn order to use the enhancer, you will need to provide it with the storage used.\nIf you do not need a custom storage adapter, you may import the default storage.\n\n```javascript\n// ...\nimport {\n  createAuthMiddleware,\n  getInitialAuthState,\n  storage // or custom storage creator\n} from 'redux-simple-auth'\nimport { createStore, compose, applyMiddleware } from 'redux'\n\nconst authMiddleware = createAuthMiddleware(/*...*/)\n\nconst store = createStore(\n  rootReducer,\n  /* initialState, */\n  compose(\n    applyMiddleware(authMiddleware),\n    getInitialAuthState({ storage })\n  )\n)\n```\n\n## How does it work?\n\nRedux Simple Auth aims to make authentication and authorization within your\napplication as flexible as possible. To get familiar with how to build\nauthentication into your application, you will need to get familiar with a few\nterms.\n\n**Authenticator**\n\nAn authenticator defines how your application authenticates a user and creates a\nsession. An application may have one or many authenticators. The data returned\nfrom an authenticator will be saved using the specified session storage\nmechanism.\n\n**Session Storage**\n\nThe session store persists the session state so that it may survive a page\nreload.\n\n**Authorizer**\n\nAuthorizers are responsible for using the data stored in a session to generate\nauthorization data that can be injected into outgoing requests.\n\n## Configuration\n\nTo configure the middleware, simply pass the `createAuthMiddleware` function the\nconfiguration needed for your application. You may find more documentation on\neach of these options below.\n\n```javascript\nconst authMiddleware = createAuthMiddleware({\n  authenticator: credentialsAuthenticator,\n  // or\n  authenticators: [facebookAuthenticator, githubAuthenticator],\n  authorize: jwtAuthorizer,\n  storage: localStorageStore,\n  refresh: refresher\n})\n```\n\n**Options:**\n\n* `authenticator` (_object_): An authenticator used to authenticate the session.\n  This option is typically used if you only need a single method of\n  authentication. This should not be used in conjunction with `authenticators`.\n\n* `authenticators` (_array_): An array of authenticators. If your application\n  offers more than one method of authentication (Facebook Login, Github login,\n  etc), you will pass the array of authenticators here. This option will be\n  ignored if you use the `authenticator` option.\n\n* `storage` (_object_): The storage mechanism used to persist the session.\n\n* `authorize` (_function_): An authorization function used to attach header\n  information to outgoing network requests.\n\n* `refresh` (_function_): A function used to refresh the session data after each\n  request.\n\n* `syncTabs` (_boolean_): Determines whether session state should be synced\n  across tabs or not.\n  * _Default_: `false`\n\n## Authenticators\n\nAuthenticators implement the business logic responsible for authenticating the\nsession. An application may have one or many authenticators such as\nauthenticating credentials with one's own server, Facebook login, Github login,\netc. The authentication strategy chosen is dependent on the action dispatched\nwith the authentication payload.\n\n```javascript\nstore.dispatch(authenticate('credentials', { email, password }))\n```\n\n### Built-in authenticators\n\nRedux Simple Auth ships with 2 authenticators. If you would like to build your\nown, refer to the [custom authenticators](#implementing-a-custom-authenticator)\ndocumentation.\n\n**Credentials**\n\nAn authenticator aimed to abstract away many of the common authentication\nscenarios used when authenticating via credentials. You may find more\ndocumentation on the options available below.\n\n```javascript\nimport { createCredentialsAuthenticator } from 'redux-simple-auth'\n\nconst credentialsAuthenticator = createCredentialsAuthenticator({\n  endpoint: '/api/authenticate'\n})\n```\n\nWhen authenticating via the `authenticate` action, simply give the credentials\npayload as the second argument.\n\n```javascript\nconst credentials = { email: 'test@example.com', password: 'F@keP@ssword!' }\n\nstore.dispatch(authenticate('credentials', credentials))\n```\n\n**Options**\n\n* `endpoint` (_string_): The endpoint that will be called with the credentials\n  during authentication.\n\n* `contentType` (_string_): Specifies the `Content-Type` header for the request.\n  * _Default_: `application/json`\n\n* `headers` (_object_): Allows you to define any additional headers for the\n  request\n  * _Default_: `{}`\n\n* `method` (_string_): Allows you to define the HTTP method used for the\n  request.\n  * _Default_: `POST`\n\n* `transformRequest`: (_function_): A function that accepts the credentials data\n  and transforms it for the request body. This is useful if you need to encode\n  the request body in a different way, such as an\n  `application/x-www-form-urlencoded` request.\n  * _Default_: `JSON.stringify`\n\n```javascript\nconst credentialsAuthenticator = createCredentialsAuthenticator({\n  endpoint: '/api/authenticate',\n  contentType: 'application/x-www-form-urlencoded',\n  transformRequest(credentials) {\n    return Object.keys(credentials)\n      .map(key =\u003e `${encodeURIComponent(key)}=${encodeURIComponent(credentials[key])}`)\n      .join('\u0026')\n  }\n})\n```\n\n* `transformResponse`: (_function_): A function that allows you to transform the\n  payload returned from the server that will be saved in the `session` state.\n  * _Default_: `(payload) =\u003e payload`\n\n```javascript\nconst credentialsAuthenticator = createCredentialsAuthenticator({\n  endpoint: '/api/authenticate',\n  transformResponse: data =\u003e ({\n    token: data.response.token\n  })\n})\n```\n\n* `restore`: (_function_): A restore function for the authenticator. The default\n  implementation will resolve if the data is non-empty. If you would like more\n  custom behavior, see the section on [custom\n  authenticators](#implementing-a-custom-authenticator) for usage information.\n\n* `invalidate`: (_function_): An invalidation function for the authenticator.\n  The default implementation will always resolve. If you would like more custom\n  behavior, see the section on [custom\n  authenticators](#implementing-a-custom-authenticator) for usage information.\n\n**OAuth2 Implicit Grant (alpha)**\n\nAn authenticator to handle OAuth2 implicit grant flow. This validates that the\ndata passed to `authenticate` has an `access_token` parameter.\n\n**NOTE:** This authenticator is currently in alpha. If you need\nmore robust authentication/restore behavior, consider building your own [custom\nauthenticator](#implementing-a-custom-authenticator).\n\n```javascript\nimport { createOauth2ImplicitGrantAuthenticator } from 'redux-simple-auth'\n\nconst oauth2ImplicitGrantAuthenticator = createOauth2ImplicitGrantAuthenticator()\n```\n\n**Options**\n\nThere are currently no options for this authenticator. As OAuth2 support is\nbuilt out, options will be added to better support extensibility.\n\n### Implementing a custom authenticator\n\nTo implement your own custom authenticator, you will need to import the\n`createAuthenticator` function from Redux Simple Auth. To create the\nauthenticator, simply call the function with a configuration object.\n\n```javascript\nimport { createAuthenticator } from 'redux-simple-auth'\n\nconst credentialsAuthenticator = createAuthenticator({\n  name: 'credentials',\n  authenticate(data) {\n    // ...\n  },\n  invalidate(data) {\n    // ...\n  },\n  restore(data) {\n    // ...\n  }\n})\n```\n\n**Options:**\n\n* `name` (_string_): The name of the authenticator. This is used by the\n  middleware to identify the authenticator used during the lifecycle of the\n  session.\n\n* `authenticate(data)` (_function_): A function responsible for implementing the\n  logic responsible for authentication. This function will be invoked when the\n  [`authenticate`](#authenticateauthenticator-payload) action is dispatched. It\n  accepts a single argument of data given to the `authenticate` action and must\n  return a promise. A resolved promise will indicate that the session is\n  successfully authenticated. Any data resolved with the promise will be stored\n  and accessible via the `session` state. A rejected promise will indicate\n  authentication failed and will result in an unauthenticated session. Note that\n  a default implementation of this function is defined if none is given and\n  always returns a rejected promise resulting in an unauthenticated session. It\n  is important that this function is defined when creating your authenticator.\n\n* `invalidate(data)` (_function_): A function responsible for doing any\n  additional cleanup of the authenticated data. This function will be invoked\n  when the [`invalidateSession`](#invalidatesession) action is dispatched. It\n  accepts a single argument with the data persisted to the session and must\n  return a promise. A resolved promise will clear the authenticated session data\n  and result in an unauthenticated session. A rejected promise will leave the\n  session authenticated. Note that a default implementation of this\n  function is defined if none is given and always returns a resolved promise.\n\n* `restore(data)` (_function_): A function used to restore the session,\n  typically after a page refresh. This function will be invoked when the\n  middleware is first created. It accepts an argument with the data persisted to\n  the session and must return a promise. A resolved promise indicates the\n  session restore was successful and will result in the session successfully\n  authenticated. A rejected promise indicates the session restore was\n  unsuccessful and will result in an unauthenticated session. Note that a\n  default implementation of this function is defined if none is given and always\n  returns a rejected promise resulting in an unauthenticated session. It is\n  important that you define this function when creating your authenticator.\n\n**Example:**\n\nLet's create a basic credentials authenticator that accepts an email and\npassword. The authenticator will use the credentials, authenticate with the\nserver, and return a token given by the server upon successful authentication.\n\n`configureStore.js`\n\n```javascript\nimport { createAuthMiddleware, createAuthenticator } from 'redux-simple-auth'\nimport { createStore, applyMiddleware } from 'redux'\n\nconst credentialsAuthenticator = createAuthenticator({\n  name: 'credentials',\n  authenticate(credentials) {\n    return fetch('/api/login', {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json'\n      },\n      body: JSON.stringify(credentials)\n    }).then(({ token }) =\u003e ({ token }))\n  },\n  restore(data) {\n    if (data.token) {\n      return Promise.resolve(data)\n    }\n\n    return Promise.reject()\n  },\n  invalidate(data) {\n    return fetch('/api/invalidate', { method: 'DELETE' })\n  }\n})\n\nconst authMiddleware = createAuthMiddleware({\n  authenticator: credentialsAuthenticator\n})\n\n// if combined with other authenticators\nconst authMiddleware = createAuthMiddleware({\n  authenticators: [...authenticators, credentialsAuthenticator]\n})\n```\n\n## Session Storage\n\nSession storage is responsible for persisting the session state so that it may\nsurvive a page refresh. Only one session store can be defined per application.\nRedux Simple Auth makes it easy to swap the session storage to meet your needs.\n\n```javascript\nimport {\n  createAuthMiddleware,\n  createLocalStorageStore\n} from 'redux-simple-auth'\n\nconst localStorageStore = createLocalStorageStore()\n\nconst authMiddleware = createAuthMiddleware({\n  storage: localStorageStore\n})\n```\n\n### Built-in session stores\n\nRedux Simple Auth ships with 4 session stores.\n\n**`localStorage` Store**\n\nThe local storage store stores its data in the browser's `localStorage`.\n\n**`sessionStorage` Store**\n\nThe session storage store stores its data in the browser's `sessionStorage`.\n\n**Cookie Store**\n\nThe cookie store stores its data in a cookie.\n\n**Adaptive Store**\n\nIf `localStorage` is available the adaptive store will use the local storage\nstore. If not, it will fallback to using the cookie store. This is the default\nstore.\n\n### Customizing a built-in store\n\nIt is easy to customize a store. To do so, just import its respective `create*`\nfunction to define it.\n\n**`localStorage` store**\n\n```javascript\nimport {\n  createAuthMiddleware,\n  createLocalStorageStore\n} from 'redux-simple-auth'\n\nconst localStorageStore = createLocalStorageStore({\n  key: 'my-custom-app-key'\n})\n\nconst authMiddleware = createAuthMiddleware({\n  storage: localStorageStore\n})\n```\n\n**Options:**\n\n* `key` (_string_): The `localStorage` key used to persist the session.\n  * _Default_: `'redux-simple-auth-session'`\n\n**`sessionStorage` store**\n\n```javascript\nimport {\n  createAuthMiddleware,\n  createSessionStorageStore\n} from 'redux-simple-auth'\n\nconst sessionStorageStore = createSessionStorageStore({\n  key: 'my-custom-app-key'\n})\n\nconst authMiddleware = createAuthMiddleware({\n  storage: sessionStorageStore\n})\n```\n\n**Options:**\n\n* `key` (_string_): The `sessionStorage` key used to persist the session.\n  * _Default_: `'redux-simple-auth-session'`\n\n**Cookie store**\n\n```javascript\nimport {\n  createAuthMiddleware,\n  createCookieStore\n} from 'redux-simple-auth'\n\nconst cookieStore = createCookieStore({\n  name: 'my-custom-app-cookie',\n  path: '/',\n  domain: 'example.com',\n  secure: true,\n  expires: 120\n})\n\nconst authMiddleware = createAuthMiddleware({\n  storage: cookieStore\n})\n```\n\n**Options:**\n\n* `name` (_string_): The name of the cookie used to persist the session\n  * _Default_: `'redux-simple-auth-session'`\n\n* `path` (_string_): A custom path used for the cookie (e.g. `'/something'`)\n  * _Default_: `'/'`\n\n* `domain` (_string_): The domain to use for the cookie (e.g. `'example.com'`,\n  `.example.com` to include all subdomains, or `'subdomain.example.com'`). If\n  not explicitly set, the cookie domain will default to the domain the session\n  was authenticated on.\n  * _Default_: `null`\n\n* `secure` (_boolean_): Determines how the cookie should set the secure flag.\n  * _Default_: `false`\n\n* `expires` (_number_): The expiration time for the cookie in seconds. A value\n  of `null` will make the cookie expire and get deleted when the browser is\n  closed.\n  * _Default_: `null`\n\n**Adaptive Store**\n\n```javascript\nimport {\n  createAuthMiddleware,\n  createAdaptiveStore\n} from 'redux-simple-auth'\n\nconst adaptiveStore = createAdaptiveStore({\n  localStorageKey: 'my-custom-app-key',\n  cookieName: 'my-custom-app-name',\n  cookiePath: '/',\n  cookieDomain: 'example.com',\n  cookieSecure: true,\n  cookieExpires: 120\n})\n\nconst authMiddleware = createAuthMiddleware({\n  storage: adaptiveStore\n})\n```\n\n**Options:**\n\nSee the options for each store to for usage and defaults. If local storage is\navailable, the local storage store will get created using the local storage\noptions. If not, the cookie options will be passed to the cookie store upon\ncreation.\n\n### Implementing a custom session store\n\nTo implement your own session store, simply define an object that handles the\nserialization and deserialization of data.\n\n```javascript\nconst mySessionStorage = {\n  persist(data) {\n    saveMyData(JSON.stringify(data))\n  },\n  restore() {\n    return JSON.parse(getMyDataBack()) || {}\n  }\n}\n\nconst authMiddleware = createAuthMiddleware({\n  storage: mySessionStorage\n})\n```\n\n**Options:**\n\n* `persist` (_function_): A serialization function that persists the session\n  data.\n\n* `restore` (_function_): A deserialization function that restores session data.\n\n\n## Authorizer\n\nAn authorizer is responsible for setting up any needed data for outgoing network\nrequests. This function is invoked by the middleware when a\n[`fetch`](#fetchurl-options) action is dispatched.\n\n### Built-in authorizers\n\nRedux Simple Auth currently ships with 1 authorizer. As this\nlibrary matures, there are plans to implement more built-in authorizers. Refer\nto the [custom authorizers](#implementing-a-custom-authorizer) section to build\nyour own.\n\n**OAuth2 Bearer**\n\nThis authorizer is responsible for setting the `Authorization` header using the\n`Bearer` scheme.\n\n```javascript\nimport { createAuthMiddleware, oauth2BearerAuthorizer } from 'redux-simple-auth'\n\nconst authMiddleware = createAuthMiddleware({\n  authorize: oauth2BearerAuthorizer\n})\n```\n\n### Implementing a custom authorizer\n\nTo implement a custom authorizer, simply define a function that accepts two\narguments: the session data, and a callback function.\n\n```javascript\n\nconst bearerAuthorizer = (data, block) =\u003e {\n  if (data.token) {\n    block('Authorization', `Bearer ${data.token}`)\n  }\n}\n\nconst authMiddleware = createAuthMiddleware({\n  authorize: bearerAuthorizer\n})\n```\n\n**Arguments:**\n\n* `data` (_object_): The session data\n\n* `block` (_function_): A callback function responsible for defining any headers\n  needed for authorization. It accepts a header name for its first argument and\n  that header's value as its second argument.\n\n### Store Enhancer\n\nThere may be cases where you may want the redux store initialized with the\nsesion data from the storage device. The store enhancer does just that. On store\ninitialization, it will ask the storage device for the session data.\n\n```javascript\nconst enhancer = getInitialAuthState({ storage })\n```\n\n**Options:**\n\n* `storage` (_object_): The storage mechanism used to store the session. **This\n  must** be the same storage device configured with the middleware.\n\n## Refreshing the session\n\nThere may be cases where you need to refresh the session data after each\nrequest. For example, you may implement sliding sessions where requests to your\nbackend give you an updated session token.\n\nTo use this feature, simply define a `refresh` function that accepts the raw\nresponse as an argument. Note, this will only get called for requests made\nthrough the dispatched [`fetch`](#fetchurl-options) action.\n\n```javascript\nconst refresh = response =\u003e ({\n  token: response.headers.get('x-access-token')\n})\n\nconst authMiddleware = createAuthMiddleware({\n  refresh\n})\n```\n\nThere may be cases where you want to conditionally update the session. To skip\nthe session update, simply return `null` from your `refresh` function.\n\n```javascript\nconst refresh = response =\u003e {\n  const contentType = response.headers.get('content-type')\n\n  if (contentType === 'text/html') {\n    return null\n  }\n\n  return { token: response.headers.get('x-access-token') }\n}\n```\n\n**Arguments:**\n\n* `response`\n  ([_Response_](https://developer.mozilla.org/en-US/docs/Web/API/Response)): The\n  raw response returned from `fetch`\n\n## Actions\n\nRedux Simple Auth ships with several actions to aide in authentication for your\napp. Simply import them and dispatch them as necessary.\n\n### `authenticate(authenticator, payload)`\n\nTo authenticate the session, use the authenticate action. The middleware will\nlook up the corresponding authenticator and invoke its `authenticate` function.\n\n```javascript\nimport { authenticate } from 'redux-simple-auth'\n\nstore.dispatch(\n  authenticate('credentials', {\n    email: 'user@example.com',\n    password: 'password'\n  })\n)\n```\n\n**Arguments:**\n\n* `authenticator` (_string_): The name of the authenticator used for\n  authentication. The middleware will invoke this authenticator's `authenticate`\n  function.\n\n* `payload` (_any_): The payload given to the authenticator when authenticating.\n  The middleware will pass this payload as an argument directly to the\n  `authenticate` function.\n\n### `fetch(url, [options])`\n\nFetch an endpoint that requires authentication. If an authorizer is configured\nwith the the middleware, the middleware will invoke the authorizer to attach any\nheaders needed for authentication.\n\nIt is important that you use this action and forego using `window.fetch` when\ninteracting with a server that requires authentication using data defined in the\nsession. This will invoke `window.fetch` under the hood after attaching any\nauthorization specific information from the authorizer. The API is the same API\nused for `window.fetch` so you may use it interchangeably.\n\n```javascript\nimport { fetch } from 'redux-simple-auth'\n\nstore.dispatch(\n  fetch('https://www.example.com/me', {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json'\n    },\n    body: JSON.stringify({ name: 'Bob' })\n  })\n).then(res =\u003e res.json())\n// etc\n```\n\n### `clearError()`\n\nClears the last error and resets failed auth state. Useful if a user has failed\nauthentication but has navigated away from the form.\n\n```javascript\nimport { clearError } from 'redux-simple-auth'\n\nstore.dispatch(clearError())\n```\n\n### `invalidateSession()`\n\nInvalidate the session. This will clear the authenticated session data and\nresult in an unauthenticated session.\n\n```javascript\nimport { invalidateSession } from 'redux-simple-auth'\n\nstore.dispatch(invalidateSession())\n```\n\n### `updateSession()`\n\nUpdate the session with new data. If you are using the `refresh` option for the\nmiddleware, this will automatically be dispatched for you. Use this only if you\nneed to manually update the session data outside of the request lifecycle.\n\n```javascript\nimport { updateSession } from 'redux-simple-auth'\n\nstore.dispatch(updateSession({ token: 'a-new-token' }))\n```\n\n## Selectors\n\nTo aid in selecting specific session state, redux simple auth ships with a few\nselectors for your convenience. All selectors take the store `state` as an\nargument. Note this is the entire store state, not just the session state.\n\n### `getSessionData(state)`\n\n(_object_) Returns the session data set when user was authenticated. If not yet\nauthenticated, this returns an empty object.\n\n```javascript\nimport { getSessionData } from 'redux-simple-auth'\n\nconst mapStateToProps = state =\u003e ({\n  session: getSessionData(state)\n})\n```\n\n### `getIsAuthenticated(state)`\n\n(_boolean_) Returns whether the user is authenticated.\n\n```javascript\nimport { getIsAuthenticated } from 'redux-simple-auth'\n\nconst mapStateToProps = state =\u003e ({\n  isAuthenticated: getIsAuthenticated(state)\n})\n```\n\n### `getAuthenticator(state)`\n\n(_string_) Returns the `authenticator` used when authenticating. If not yet\nauthenticated, this is set to `null`.\n\n```javascript\nimport { getAuthenticator } from 'redux-simple-auth'\n\nconst mapStateToProps = state =\u003e ({\n  authenticator: getAuthenticator(state)\n})\n```\n\n### `getIsRestored(state)`\n\n(_boolean_) Returns whether the session state has been restored. Useful if you\nneed to block rendering until the session state has been fully initialized.\n\n```javascript\nimport { getIsRestored } from 'redux-simple-auth'\n\nconst mapStateToProps = state =\u003e ({\n  isRestored: getIsRestored(state)\n})\n```\n\n### `getLastError(state)`\n\n(_any_) Returns the last authentication error received if authentication has\nfailed. This value is the same value passed to the rejected promise in the\nauthenticator's `authenticate` function.\n\n```javascript\nimport { getLastError } from 'redux-simple-auth'\n\nconst mapStateToProps = state =\u003e ({\n  lastError: getLastError(state)\n})\n```\n\n### `getHasFailedAuth(state)`\n\n(_boolean_) Returns whether the user has at least one failed authentication\nattempt. Will reset back to `false` once authentication has succeeded.\n\n```javascript\nimport { getHasFailedAuth } from 'redux-simple-auth'\n\nconst mapStateToProps = state =\u003e ({\n  hasFailedAuth: getHasFailedAuth(state)\n})\n```\n\n## Action Types\n\nIf you just plain need to hook into actions dispatched from `redux-simple-auth`,\nyou may import the action types themselves for use within your own reducers.\n\n```javascript\nimport { actionTypes } from 'redux-simple-auth'\n\nconst reducer = (state, action) =\u003e {\n  switch (action.type) {\n    case actionTypes.AUTHENTICATE_FAILED:\n      // do something\n  }\n}\n```\n\nThe following actions are available action types\n\n* `AUTHENTICATE`\n* `AUTHENTICATE_FAILED`\n* `AUTHENTICATE_SUCCEEDED`\n* `CLEAR_ERROR`\n* `FETCH`\n* `INVALIDATE_SESSION`\n* `INVALIDATE_SESSION_FAILED`\n* `RESTORE`\n* `RESTORE_FAILED`\n* `UPDATE_SESSION`\n\n## TODO\n\n- [ ] Built-in authenticators for common scenarios\n  - [x] Credentials\n  - [ ] Devise\n  - [ ] OAuth\n  - [ ] Facebook Login\n  - [ ] Github Login\n  - [ ] Google login\n- [ ] Built-in authorizers\n  - [ ] Devise\n  - [x] OAuth2 Bearer\n- [ ] Integration with React Router v3\n- [ ] Integration with React Router v4\n- [ ] Typescript/Flow support\n- [ ] Create example applications\n- [ ] Solutions for server-side rendering\n- [x] Sync state across tabs\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjerelmiller%2Fredux-simple-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjerelmiller%2Fredux-simple-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjerelmiller%2Fredux-simple-auth/lists"}