npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@bithero/simple-react-auth

v1.0.1

Published

A set of react components for authorization

Downloads

12

Readme

simple-react-auth

Npm package version Npm package license Npm package types

A set of react components for authorization

License

This project is licensed under AGPL-3.0-or-later. See the LICENSE file for more informations.

Usage

For a detailed example, see the example folder.

AuthProvider

To use this library, you first need to wrap your app with an custom auth provider:

import { AuthProvider } from '@bithero/simple-react-auth';

const MyAuthProvider = ({ children }) => {
    return (
        <AuthProvider client={...} onRedirect={...}>
            {children}
        </AuthProvider>
    );
};

// As you see, with this lib you even can wrap the browserrouter with the auth provider!
root.render(
    <MyAuthProvider>
        <BrowserRouter>
            <App/>
        </BrowserRouter>
    </MyAuthProvider>
);

Next, you have to implement & supply a instance of IAuthClient<TUser>. This is a type that will be called to do the actual login/logout actions, check the user's session (i.e. localstorage and similar technologies) and get the user data. The generic argument (TUser) is used to specify the type the userdata a client produces has.

Here's an example:

import { IAuthClient } from '@bithero/simple-react-auth';
type MockUser = { name: string; };
class MockClient implements IAuthClient<MockUser> {
    private user: MockUser | null = null;
    async login(params: any): Promise<void> {
        // Handles the login.
        // The parameters are the one provided by your application.
        // This method should fill in the user field above
        // and throw if any issue arieses.
    }
    async logout(): Promise<void> {
        // Handles the logout.
        // You should cleanup all cached data from a login here.
    }
    async checkSession(): Promise<void> {
        // Called on app startup to determine if already logged in.
        // In other words: it checks a users "session". Effectivly
        // the client should after this be the same state as after
        // a call to '.login()'.
    }
    async getUser(): Promise<MockUser | null> {
        // Simple accessor to the user object.
        // Can be as complex or simple as you need it.
        return this.user;
    }
}

Next we also need to supply a redirect callback which is called when the library needs to take the user to the login page.

It can either be a normal lambda such as

const onRedirect = () => {
    window.location = "/login";
};

but to use things as navigate() from react-router, you need to use a bit more complicated syntax:

import { useNavigate } from 'react-router-dom';
import { createHookAware } from '@bithero/react-helpers';
const onRedirect = createHookAware(
    // This is a object which maps a name to the hook it should call;
    // Here it makes 'navigate' an alias to the result of `useNavigate`.
    { 'navigate': useNavigate, },

    // This NEEDS to be a function; a arrow function will NOT work!
    // It gets `this` set to a object where all keys / members are
    // the names declared in the object above, with the result of the
    // specified hooks as value.
    function() {
        // 2 second timeout before redirecting to the login.
        setTimeout(() => {
            this.navigate('/login');
        }, 2000);
    }
);

For more informations, see the @bithero/react-helpers package.

useAuth

With this, you can finish configuring <AuthProvider>. Now in it's children you can use useAuth to get the auth object:

import { useAuth } from '@bithero/simple-react-auth';
function HomePage() {
    const auth = useAuth();
    // Auth gives access to all functions of the library:
    //  auth.login(...) starts a login
    //  auth.logout() starts a logout
    //  auth.refreshUser() refreshes the user object
    //      (by calling client.getUser one time) and notifying
    //      all consumers.
    //  auth.error contains the last error
    //  auth.isAuthenticated is a flag that, when true,
    //      expresses that a user is authenticated.
    //  auth.user is the user object as returned by client.getUser
};

withAuth

A simple higher order component, which wraps the provided component in a consumer for the auth context, and additionally providing the current auth to it as parameter (same return type as if you'd use useAuth).

import { withAuth } from '@bithero/simple-react-auth';
const HomePage = withAuth(({ auth }) => {
    const { user } = auth;
    return <pre>{JSON.stringify(user)}</pre>;
});

withAuthRequired

A higher order component, which requires a authenticated user to render the provided component. If there is no authenticated user, it will call the optionally supplied IAuthRequiredOpts.onRedirect to render a alternative text and runs the onRedirect hook provided to the <AuthProvider> to redirect the user to the login page.

import { withAuthRequired } from '@bithero/simple-react-auth';

const authRequiredOpts: IAuthRequiredOpts = {
    onRedirect() {
        return <div>Youre being redirected to the login now.</div>;
    }
};

const Protected = withAuthRequired(() => {
    return <>...</>;
}, authRequiredOpts);

function AppRoutes() {
    return <Routes>
        <Route path="/plugin"/>
        <Route path="/protected" element={<Protected/>}/>
    </Routes>;
}