0.1.7 • Published 4 years ago

@reshuffle/react-auth v0.1.7

Weekly downloads
14
License
MIT
Repository
-
Last release
4 years ago

@reshuffle/react-auth

React context for adding "out-of-the-box" auth to your app using @reshuffle/passport.

See a fully working demo here.

Installation

$ npm install @reshuffle/react-auth

Prerequisites

  • Install @reshuffle/passport
  • Configure backend/_handler.js to use @reshuffle/passport, see instructions

Usage

Wrap your root component with AuthProvider.

src/App.js

import React from 'react';
import { AuthProvider } from '@reshuffle/react-auth';
import Main from './components/Main';

export default function App() {
  return (
    <AuthProvider>
      <Main />
    </AuthProvider>
  );
}

Use with react hooks.

src/components/Main

import React from 'react';
import { useAuth } from '@reshuffle/react-auth';

export default function Main() {
  const {
    loading,
    error,
    authenticated,
    profile,
    getLoginURL,
    getLogoutURL,
  } = useAuth();

  if (loading) {
    return <div><h2>Loading...</h2></div>;
  }
  if (error) {
    return <div className='error'><h1>{error.toString()}</h1></div>;
  }
  if (!authenticated) {
    return <a href={getLoginURL()}>Login</a>;
  }
  return (
    <>
      <img src={profile.picture} />
      <span>{profile.displayName}</span>
      <a href={getLogoutURL()}>Logout</a>
    </>
  );
}

Use with react class components.

src/components/Main

import React from 'react';
import { AuthContext } from '@reshuffle/react-auth';

export default class Main extends React.Component {
  static contextType = AuthContext;

  render() {
    const {
      loading,
      error,
      authenticated,
      profile,
      getLoginURL,
      getLogoutURL,
    } = this.context;

    if (loading) {
      return <div><h2>Loading...</h2></div>;
    }
    if (error) {
      return <div className='error'><h1>{error.toString()}</h1></div>;
    }
    if (!authenticated) {
      return <a href={getLoginURL()}>Login</a>;
    }
    return (
      <>
        <img src={profile.picture} />
        <span>{profile.displayName}</span>
        <a href={getLogoutURL()}>Logout</a>
      </>
    );
  }
}
0.1.7

4 years ago

0.1.6

4 years ago

0.1.5

4 years ago

0.1.4

4 years ago

0.1.3

4 years ago

0.1.2

4 years ago

0.1.1

4 years ago