{"id":19578654,"url":"https://github.com/pierrecabriere/react-authmanager","last_synced_at":"2025-04-27T06:34:18.246Z","repository":{"id":121724216,"uuid":"126469674","full_name":"pierrecabriere/react-authmanager","owner":"pierrecabriere","description":"Integrate an authentication system based on JWT in your react app, in a simple way!","archived":false,"fork":false,"pushed_at":"2020-09-04T15:56:14.000Z","size":119,"stargazers_count":13,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-18T22:14:08.850Z","etag":null,"topics":["authentication","authmanager","guard","guards","hoc","jwt","localstorage","react","redux","user"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"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/pierrecabriere.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-03-23T10:26:36.000Z","updated_at":"2020-10-19T13:41:28.000Z","dependencies_parsed_at":"2023-06-07T21:45:27.644Z","dependency_job_id":null,"html_url":"https://github.com/pierrecabriere/react-authmanager","commit_stats":{"total_commits":14,"total_committers":2,"mean_commits":7.0,"dds":0.2142857142857143,"last_synced_commit":"6b2fd5c7af0d039d7cebee9b2d0a26b74ae79fd0"},"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pierrecabriere%2Freact-authmanager","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pierrecabriere%2Freact-authmanager/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pierrecabriere%2Freact-authmanager/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pierrecabriere%2Freact-authmanager/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pierrecabriere","download_url":"https://codeload.github.com/pierrecabriere/react-authmanager/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251099416,"owners_count":21536148,"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","authmanager","guard","guards","hoc","jwt","localstorage","react","redux","user"],"created_at":"2024-11-11T07:12:31.914Z","updated_at":"2025-04-27T06:34:17.974Z","avatar_url":"https://github.com/pierrecabriere.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# React authentication manager 🔑\n\n[![NPM version](https://img.shields.io/npm/v/react-authmanager.svg)](https://www.npmjs.com/package/react-authmanager)\n\n**react-authmanager is a highly-configurable manager for react. It manages users authentication with JWT in your app and provides guards HOCs to secure components in a flexible and simple way.**\n\n---\n\n- [Getting started](#1---getting-started)\n- [Authenticate users](#2---authenticate-users)\n- [Access user informations](#3---access-user-informations)\n- [Secure components](#4---secure-components)\n- [Authmanager](#5---authmanager)\n    - [Authmanager.config](#51---authmanagerconfig)\n    - [Authmanager.utils](#52---authmanager-utils)\n\n## 1 - Getting started\n`npm install --save react-authmanager`, then you have to configure the package.\u003cbr/\u003e\nTo manage configuration, you need to import the default Authmanager.\u003cbr/\u003e\nYou need to configure the manager before starting to use, so your highest component file is the best place (by example, it's the `App.js` file with a [create-react-app](https://github.com/facebook/create-react-app) instance !)\n\nYou can also create a new manager instance.\n```js\nimport Authmanager from 'react-authmanager';\n\nconst customManager = Authmanager.create(\"customName\", { ...config });\n```\n\n**react-authmanager** needs:\n- to know how to login the user from the server and get a token back ([`fetchToken`](#configfetchtokencredentials-async))\n- to know how to get the current logged user informations from the server ([`fetchUser`](#configfetchuser-async))\n\n**you** will need:\n- to include the current token in your requests headers authorization ([`getToken`](#gettoken))\n\n### Minimal configuration for the manager\n```js\nimport Authmanager from 'react-authmanager';\n\n// how to login the user from the server and get a token back\nAuthmanager.config.fetchToken = async credentials =\u003e {\n  ... // login user with an ajax call to the server and return the given token\n  return token;\n}\n\n// how to get the current logged user informations from the server\nAuthmanager.config.fetchUser = async () =\u003e {\n  ... // get current logged user informations from the server with an ajax call and return any data you will need\n  return user;\n}\n```\n\n### Authorize your requests\n```js\n// include the current token in your requests headers authorization\nfetch(..., {\n  headers: new Headers({\n    'Authorization': 'Bearer ' + Authmanager.getToken() // returns null if no token is stored\n  }),\n  ...\n});\n```\n\n*For more configurations, please read the [Authmanager](#5---authmanager) section below.*\n\n## 2 - Authenticate users\n**withAuth** HOC injects in your component helpers to manage authentication: **login**, **logout** and **auth**.\u003cbr/\u003e\n**login** and **logout** are functions to log users. **auth** is an object that contains a state of operations.\n\n| prop       | default | description                                                   |\n|:-----------|:--------|:--------------------------------------------------------------|\n| login      |         | `function` send credentials to the server to get a token back |\n| logout     |         | `function` remove the stored token                            |\n| auth:      |         | `object` informations about the current state of operations   |\n| -- loading | false   | `bool` is authentication (login or logout) currently loading  |\n\n```js\nimport Authmanager from 'react-authmanager';\n\nclass LoginComponent extends React.Component {\n  handleSubmit() {\n    const credentials = {\n      email: 'hello@example.com',\n      password: 'ThisIsASecret'\n    }; // or whatever data you want to send to the server (see the getToken configuration in the Minimal configuration section above)\n    \n    this.props.login(credentials)\n      .then(function() { alert('Hello !') })\n  }\n  \n  render() {\n    if (this.props.auth.loading)\n      return (\u003cMyLoadingComponent /\u003e);\n    \n    return ( ... );\n  }\n  \n  ...\n}\n\nexport default Authmanager.withAuth(LoginComponent); // or customManager.withAuth(LoginComponent);\n\n...\n\nclass LogoutComponent extends React.Component {\n  handleClick() {\n    this.props.logout()\n      .then(function() { alert('Good bye !') })\n  }\n  \n  ...\n}\n\nexport default Authmanager.withAuth(LogoutComponent); // or customManager.withAuth(LogoutComponent);\n```\n\nYou can also call the login and logout methods anywhere on the manager with `Authmanager.login()` and `Authmanager.logout()`\n\n## 3 - Access user informations\n**withUser** HOC will automatically injects an user object in your component props.\u003cbr/\u003e\nThis object contains informations about the current user:\n\n| prop       | default | description                                                                                             |\n|:-----------|:--------|:--------------------------------------------------------------------------------------------------------|\n| user:      |         | `object` containing current user informations                                                           |\n| -- loading | false   | `bool` is user currently loaded from the server                                                         |\n| -- logged  | false   | `bool` is the current user logged in (setted by [`isUserLogged`](#configisuserloggeduser-async)) |\n| -- ...     | null    | `any` informations about the user sent by the server (setted by [`getUser`](#configgetuser-async))    |\n\n```js\nimport Authmanager from 'react-authmanager';\n\nclass MyComponent extends React.Component {\n  handleClick() {\n    if (this.props.user.logged)\n      alert('Hello ' + this.props.user.name);\n    else\n      alert('Hello John, please login !');\n  }\n  \n  ...\n}\n\nexport default Authmanager.withUser(MyComponent);\n```\n\n## 4 - Secure components\n**withGuard** HOC helps you protect your components in a flexible way. By example, you can render a login form instead of a component if no user is logged in.\u003cbr/\u003e\nIt needs a guard as parameter. A guard is just a function that returns a component, so you can easily create your own guards.\u003cbr/\u003e\nA guard function has parameters:\n\n| prop  | description                                              |\n|:------|:---------------------------------------------------------|\n| user  | `object` the current user object                         |\n| next  | `function` a function that returns the current Component |\n| props | `object` the current component props                     |\n\n```js\nimport Authmanager from 'react-authmanager';\n\nconst loggedGuard = function(user, props, next) {\n  if (user.loading)\n    return (\u003cMyLoadingComponent /\u003e); // render a loading component if user is currently fetched from the server\n  \n  if (user.logged)\n    return next(); // render the component if user is not loading and is logged\n  \n  return (\u003cMyLoginComponent /\u003e); // render a login component by default (if user is fetched from the server but not logged)\n}\n\nclass MyComponent extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003eThis message is visible only for logged users !\u003c/div\u003e\n    )\n  }\n  \n  ...\n}\n\nexport default Authmanager.withGuard(loggedGuard)(MyComponent);\n```\n\nYou can inject data in your rendered component props through the next function\n```js\nconst guardThatInjects = function(user, props, next) {\n    return next({ myNewProp: true });\n}\n\nclass MyComponent extends React.Component {\n  render() {\n    console.log(this.props.myNewProp); // true\n    return (\n      \u003cdiv\u003eThis message is visible only for logged users !\u003c/div\u003e\n    )\n  }\n\n  ...\n}\n\nexport default Authmanager.withGuard(loggedGuard)(MyComponent);\n```\n\nYou can also configure you guards from outside the component file with the [`addGuard`](#addguard) Authmanager function :\n\n```js\nAuthmanager.addGuard('loggedGuard', function(user, props, next) {\n  if (user.loading)\n    return (\u003cMyLoadingComponent /\u003e); // render a loading component if user is currently fetched from the server\n    \n  if (user.logged)\n    return next(); // render the component if user is not loading and is logged\n    \n  return (\u003cMyLoginComponent /\u003e); // render a login component by default (if user is fetched from the server but not logged)\n});\n\n...\n\nclass MyComponent extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003eThis message is visible only for logged users !\u003c/div\u003e\n    )\n  }\n  \n  ...\n}\n\nexport default Authmanager.withGuard('loggedGuard')(MyComponent);\n```\n\n## 5 - Authmanager\n\n### 5.1 - `Authmanager.config`\nTo edit the configuration of **react-authmanager**your manager, you have to override the config object:\n```js\nimport Authmanager from 'react-authmanager';\n\n// will change the way how the manager will login the user and get a token back, see below\nAuthmanager.fetchToken = function(credentials) {}\n```\n\n```typescript\ninterface IReactAuthConfig {\n  fetchToken?: Function,\n  fetchUser?: Function,\n  isUserLogged?: Function\n}\n```\n\n#### `fetchToken([credentials]) [async]`\nGet an authentication token when an user tries to login. `fetchToken` is called when the auth login function is executed to store the token in *localStorage*.\n\n**Parameters**\n- [`credentials`] *(`Object`)* Argument given by the login function. (when you call `Authmanager.login(credentials)`)\n\n**Return *(`String`)***\n```\nNeed to return a token that will be stored\n```\n\n**default**\n```js\nfetchToken = null;\n```\n\n**example with axios**\n```js\nAuthmanager.config.fetchToken = async credentials =\u003e {\n  const { data } = await axios.post('https://example.com/login', credentials);\n  return data.token;\n}\n```\n\n#### `fetchUser() [async]`\nGet the current authenticated user. `fetchUser` is called when the manager initialize its store and after an user login.\n\n**Return *(`Object`)***\n```\nNeed to return informations about the current logged user\n```\n\n**default**\n```js\nfetchUser = null;\n```\n\n**example with axios**\n```js\nAuthmanager.config.fetchUser = async () =\u003e {\n const { data } = await axios.get('https://example.com/current-user');\n return data;\n}\n```\n\n#### `isUserLogged([user]) [async]`\nDefine if the current user (returned by `getUser`) is logged. `isUserLogged` is called after each user state change. The result is set in `user.logged`.\n\n**Parameters**\n- [`user`] *(`Object`)* Object returned by the `getUser` function.\n\n**Return *(`Boolean`)***\n```\nNeed to return a boolean that tell if the current user (returned by `getUser`) is logged.\n```\n\n**default**\n```js\nisUserLogged = userData =\u003e !!userData \u0026\u0026 Object.keys(userData).length \u003e 0;\n```\n*By default, `isUserLogged` returns true if `fetchUser` returns a non-empty object*\n\n### 5.2 - `Authmanager` utils\n**react-authmanager** also provides some utilities to manage the manager from your app:\n```js\nimport Authmanager from 'react-authmanager';\n\n// will return the current stored token, or null, see below\nconst token = Authmanager.getToken()\n```\n\n#### `getToken()`\nReturns the current stored token (in *localStorage*). You should use `getToken` to authorize your requests to the server\n\n**Return *(`String`)***\n```\nReturns the token stored after the `fetchToken` call\n```\n\n**example with axios**\n```js\naxios.defaults.transformRequest.push((data, headers) =\u003e {\n  const token = Authmanager.getToken();\n  if (token) headers.common['Authorization'] = 'Bearer ' + token;\n\n  return data;\n});\n```\n\n#### `setToken([token])`\nManually set a token. You can call the `setToken` if you want to implements your own login function.\n\n**Parameters**\n- [`token`] *(`String`)* String token that will be returned by the `fetchToken` function.\n\n**Return *utils (`Object`)***\n```\nNeed to return a boolean that tell if the current user (returned by `getUser`) is logged.\n```\n\n**example**\n```js\nAuthmanager.setToken('aValidToken');\nAuthmanager.getUser();\n```\n\n#### `addGuard([guard])`\nCreate a guard at the manager level, you will be able to reuse the guard just by giving its name\n\n**Parameters**\n- [`guard`] *(`Function`)* A function that returns a component or call the next function to render the default component.\n\n**Return *Component | next()***\n```\nNeed to return a valid React component or call the next function given in parameters.\n```\n\n**example**\n```js\nAuthmanager.addGuard('loggedGuard', (user, next) =\u003e {\n  if (user.loading)\n    return \u003cdiv\u003eloading\u003c/div\u003e;\n    \n  if (user.logged)\n    return next();\n    \n  return \u003cdiv\u003elogin\u003c/div\u003e;\n});\n```\n\n#### `getUser()`\nCall the `fetchUser` function and update the redux store. You can use this function to refresh the current logged user from the server\n\n**Return *utils (`Object`)***\n```\nReturns a promise that resolves the new user data\n```\n\n---\n\n🚀\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpierrecabriere%2Freact-authmanager","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpierrecabriere%2Freact-authmanager","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpierrecabriere%2Freact-authmanager/lists"}