# @contentchef/authentication-react

> Contentchef authentication component library

Latest version **0.2.7** (published 2019-06-25) · 0 weekly downloads

## Install

```sh
npm install @contentchef/authentication-react
pnpm add @contentchef/authentication-react
yarn add @contentchef/authentication-react
bun add @contentchef/authentication-react
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.2.7 |
| Published | 2019-06-25 |
| First published | 2019-03-07 |
| Weekly downloads | 0 |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 6 |
| Unpacked size | 62.3 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| Author | Byte-Code |
| Maintainers | apalumbo, bcoders, octod |

## Links

- npm: https://www.npmjs.com/package/@contentchef/authentication-react
- npm.io page: https://npm.io/package/@contentchef/authentication-react

## Dependencies (6)

- [react](https://npm.io/package/react.md) ^16.7.0
- [auth0-js](https://npm.io/package/auth0-js.md) ^9.10.0
- [react-dom](https://npm.io/package/react-dom.md) ^16.7.0
- [@types/auth0-js](https://npm.io/package/@types/auth0-js.md) ^8.11.11
- [amazon-cognito-auth-js](https://npm.io/package/amazon-cognito-auth-js.md) ^1.3.2
- [@types/amazon-cognito-auth-js](https://npm.io/package/@types/amazon-cognito-auth-js.md) ^1.2.1

## Recent versions

- 0.2.7 (latest) — 2019-06-25
- 0.2.6 — 2019-06-20
- 0.2.5 — 2019-06-20
- 0.2.4 — 2019-06-18
- 0.2.3 — 2019-04-01
- 0.2.2 — 2019-03-25
- 0.2.1 — 2019-03-21
- 0.2.0 — 2019-03-18
- 0.1.0 — 2019-03-07

## README

@contentchef/authentication-react
=================================

React components for authentication

- [@contentchef/authentication-react](#contentchefauthentication-react)
  - [Install](#install)
  - [Configuring the AuthenticationProvider](#configuring-the-authenticationprovider)
  - [Components](#components)
      - [Authorized](#authorized)
      - [Login](#login)
      - [Logout](#logout)
      - [Unauthorized](#unauthorized)
  - [HOCs](#hocs)
      - [withStrategy](#withstrategy)
      - [withUser](#withuser)
  - [Known strategies](#known-strategies)
      - [Auth0](#auth0)
      - [AWSCognito](#awscognito)
  - [Creating a new authentication strategy](#creating-a-new-authentication-strategy)

## Install

```bash
npm i --save @contentchef/authentication-react
# or
yarn add @contentchef/authentication-react
```

## Configuring the AuthenticationProvider

```tsx
import Authentication, { AuthenticationStrategyRegistry } from '@contentchef/authentication-react';
import React from 'react';
import Auth0Configuration from './Auth0Configuration';
import CognitoConfiguration from './CognitoConfiguration';
import MyAuthenticationStrategy from './MyAuthenticationStrategy';

const { AuthenticationStrategy } = process.env;

AuthenticationStrategyRegistry.addStrategy(Authentication.KnownStrategies.Auth0);
AuthenticationStrategyRegistry.addStrategy(Authentication.KnownStrategies.AWSCognito);
AuthenticationStrategyRegistry.addStrategy(MyAuthenticationStrategy);

/*
 * This will get the correct configuration
 */
const getConfiguration = () => {
  switch(AuthenticationStrategy) {
    case Authentication.KnownStrategies.Auth0.name:
      return Auth0Configuration;
    case Authentication.KnownStrategies.AWSCognito.name:
      return CognitoConfiguration;
  }
}

export default function App() {
  return (
    <Authentication.AuthenticationProvider configuration={getConfiguration()} strategyName={AuthenticationStrategy}>
      {
        /* your app here 🦄 */
      }
    </Authentication.AuthenticationProvider>
  )
}
```

## Components

#### Authorized

```tsx
const MyComponent = () => (
  <Authorized>You will read this only if authorized</Authorized>
);
```

#### Login

```tsx
const MyComponent = () => (
  <Login>Click here to login</Login>
);
```

#### Logout

```tsx
const MyComponent = () => (
  <Logout>Click here to logout</Logout>
);
```

#### Unauthorized

```tsx
const MyComponent = () => (
  <Unauthorized>You will read this only if unauthorized</Unauthorized>
);
```

## HOCs

#### withStrategy

This HOC will pass the prop `strategy` which is the current selected strategy.

```tsx
class MyComponent extends React.Component<{ strategy: AuthenticationStrategyBase }> {
  public componentDidMount() {
    if (!this.props.strategy.isAuthorized()) {
      this.props.strategy.authorize();
    }
  }
  
  public render() {
    /**/
  }
}
```
#### withUser

This HOC will pass the prop `user` which is the current authenticated user.

```tsx
const MyEmail = withUser()(({ user }) => <span>{ user.email }</span>);
```

## Known strategies

At this moment there are two known strategies, `Auth0` and `AWSCognito`.

Each strategy has it's own configuration

#### Auth0

```typescript
// Auth0 configuration
interface IConfiguration {
  audience: string;
  clientID: string;
  domain: string;
  redirectUri: string;
  logoutRedirectURI: string;
  responseType: string;
  scope: string;
}
```

#### AWSCognito

```typescript
// AWSCognito configuration
interface IConfiguration {
  AppWebDomain: string;
  ClientId: string;
  RedirectUriSignIn: string;
  RedirectUriSignOut: string;
  RestApiId: string;
  UserPoolId: string;
  TokenScopesArray: string[];
}
```

## Creating a new authentication strategy

In order to create a new authentication strategy, you have to extend then `AuthenticationStrategyBase` class.

```typescript
import { 
  AuthenticationStrategyBase, 
  IAuthenticationStrategyBaseConfig, 
  IUserInfo,
} from '@contentchef/authentication-react';

export interface IMyAuthenticationStrategyConfiguration extends IAuthenticationStrategyBaseConfig {

}

export default class MyAuthenticationStrategy extends AuthenticationStrategyBase {
  // begins the authorization flow
  public async authorize<T = unknown>(): Promise<T> { }
  // is invoked automatically from the Callback component. Should handle the login return url
  public async callback<T = unknown>(arg?: T): Promise<void> { }
  // should return if a user is authorized
  public isAuthorized(): boolean { }
  // is used to renew the session and to check if a user is authenticated
  public async renewSession<T = unknown>(): Promise<T> { }
  // logs out current user
  public async logout(): Promise<void> { }
  // should returns the strategy name. This name is the one to choose from the `strategyName` provider prop
  public strategyName(): string { }
  // this method is used to retrieve user's normalized data
  public userInfo(): Readonly<IUserInfo> { }
}
```

You can use also hooks methods inside your strategy, in order to notify the strategy consumer 

```typescript
export interface IAuthenticationStrategyHooks {
  // you should invoke this inside the `callback` method
  onAfterCallback?(): void;
  // use this when an authentication error occurs
  onAuthenticationError?(error: Error): void;
  // use this when the authorize flow has finished successfully
  onAuthenticationSuccess?(): void;
  // you can use this before the authorization flow starts
  onBeforeAuthenticate?(): void;
  // you can use this before the callback flow starts
  onBeforeCallback?(): void;
  // this will be invoked right after the strategy is instantiated
  onInit?(): void;
  // use this after you have received the accessToken inside the authorization flow
  onRenewSession?(token: string): void;
}
```

---
_Source: https://npm.io/package/@contentchef/authentication-react · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
