Skip to content

Repository files navigation

React Native Auth0

A wrapper on auth0's react native library with common case features already implemented.

Installation

  1. Run on your terminal the following command:
$ npm i @cobuildlab/react-native-auth0

Usage

Auth0 Client Setup:

Create a new client instance using Auth0Native:

import{Auth0Native}from'@cobuildlab/react-native-auth0';importjwtDecodefrom'jwt-decode';// AUTH0 optionsconstAUTH0_OPTIONS={clientId: AUTH_CLIENT_ID,domain: AUTH_CLIENT_DOMAIN,};// You can handle the credentials obtained in auth0// and store them in the async store or another store of your choiceconstCREDENTIALS_HANDLER={save: async(credentials): Promise<void>=>{constvalue=JSON.stringify(credentials);awaitAsyncStorage.setItem('credentials_store',value);},get: async()=>{constvalue=awaitAsyncStorage.getItem('credentials_store');returnvalue!=null ? JSON.parse(value) : null;},clear: async()=>{awaitAsyncStorage.removeItem('credentials_store');apolloClient.resetStore();},// You can specify a what token the library will validatetokenToValidate: 'accessToken',// or pass a function that validate itvalidateToken: (credentials)=>{const{ exp }=jwtDecode(credentials.idToken)as{exp: number};// Current time unix (in seconds)constcurrentTime=Math.floor(newDate().getTime()/1000);returnexp>currentTime;},};exportconstclient=newAuth0Native(AUTH0_OPTIONS,CREDENTIALS_HANDLER);

Then import the client and pass through props to the provider:

import{AuthProvider}from'@cobuildlab/react-native-auth0';import{client}from'./config';constAUTH0_SCOPE='offline_access email openid profile';exportconstApp=()=>(<AuthProviderclient={auth0NativeClient}scope={client}><App/></AuthProvider>);

Hook usage:

Login View:

import{View,Button}from 'react-native;
import{useAuth}from'@cobuildlab/react-native-auth0';exportconstLoginView=()=>{const{ authorize }=useAuth();return(<View><ButtononPress={authorize}title="Sign in"></View>
)
}

Logout View:

import{View,Button}from 'react-native;
import{useAuth}from'@cobuildlab/react-native-auth0';exportconstLogOutView=()=>{const{ clearSession }=useAuth();return(<View><ButtononPress={clearSession}title="Sign in"></View>
)
}

App Component:

import{useAuth}from'@cobuildlab/react-native-auth0';import{LoginView}from'./LoginView';import{LogOutView}from'./LogOutView';import{MainView,Loading}from'./others';exportfunctionApp(){const{ isLoading, isAuthenticated, clearSession }=useAuth();if(isLoading){return<Loading/>;}if(!isAuthenticated){return<LoginView/>;}return<MainView/>;}

TODO

  • Documentation
  • Test Code
  • Hanlde error cases
  • hook for subscribe to error cases

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages