0.2.7 • Published 5 years ago

@contentchef/authentication-react v0.2.7

Weekly downloads
-
License
-
Repository
-
Last release
5 years ago

@contentchef/authentication-react

React components for authentication

Install

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

Configuring the AuthenticationProvider

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

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

Login

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

Logout

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

Unauthorized

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.

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.

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

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

AWSCognito

// 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.

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

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;
}