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

use-auth-hook

v1.0.1

Published

A reusable and configurable authentication hook for React applications.

Downloads

4

Readme

use-auth-hook

Overview

use-auth-hook is a powerful and flexible React hook designed to simplify authentication management in modern web applications. It provides a comprehensive solution for handling authentication states, managing secure token storage, and integrating with various authentication providers, including support for JWTs and OAuth. With use-auth-hook, developers can easily implement login, logout, and token refresh functionalities, while ensuring secure practices and scalability.

Feature

  • Customizable API Endpoints: Easily configure the base URL and specific authentication endpoints for seamless integration with any backend.
  • JWT Management: Securely store, decode, and manage JWT tokens using cookies with HttpOnly and Secure flags to enhance security.
  • OAuth Support: Integrated support for third-party authentication providers (Google, Facebook, etc.) via OAuth.
  • Multi-Factor Authentication (MFA): Optional support for MFA to add an extra layer of security.
  • Role-Based Access Control: Manage user roles and permissions to control access to different parts of the application.
  • Automatic Token Refresh: Automatically refresh tokens before they expire, ensuring a smooth user experience.
  • Error Handling and User Feedback: Comprehensive error handling mechanisms with clear user feedback for various authentication scenarios.

Installation

To install the package, use npm:

 npm install use-auth-hook

Basic usage

1.Set up AuthProvider: Wrap your application with the AuthProvider component and provide configuration for your authentication endpoints.

// App.js
import React from 'react';
import { AuthProvider } from 'use-auth-hook'; // Import the AuthProvider from the package
import Dashboard from './Dashboard';
import Login from './Login';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const authConfig = {
  baseURL: 'https://yourapi.com',
  endpoints: {
    login: '/auth/login',
    refreshToken: '/auth/refresh-token',
    logout: '/auth/logout',
    oauth: '/auth/oauth',
  },
};

function App() {
  return (
    <AuthProvider config={authConfig}>
      <Router>
        <Switch>
          <Route path="/login" component={Login} />
          <Route path="/dashboard" component={Dashboard} />
          {/* Add more routes as needed */}
        </Switch>
      </Router>
    </AuthProvider>
  );
}

export default App;

2.Implement Login Component: Use the useAuth hook to manage user authentication.

// Login.js
import React, { useState } from 'react';
import { useAuth } from 'use-auth-hook';

function Login() {
  const [credentials, setCredentials] = useState({ username: '', password: '' });
  const { login, error } = useAuth();

  const handleInputChange = (e) => {
    setCredentials({ ...credentials, [e.target.name]: e.target.value });
  };

  const handleLogin = async () => {
    try {
      await login(credentials);
      // Redirect to a protected route or show a success message
    } catch (err) {
      console.error('Login failed', err);
    }
  };

  return (
    <div>
      <h2>Login</h2>
      <input
        type="text"
        name="username"
        value={credentials.username}
        onChange={handleInputChange}
        placeholder="Username"
      />
      <input
        type="password"
        name="password"
        value={credentials.password}
        onChange={handleInputChange}
        placeholder="Password"
      />
      <button onClick={handleLogin}>Login</button>
      {error && <p>{error}</p>}
    </div>
  );
}

export default Login;

3.Protected Routes: Use the useAuth hook to protect routes based on authentication status.

// PrivateRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { useAuth } from 'use-auth-hook';

const PrivateRoute = ({ component: Component, ...rest }) => {
  const { isAuthenticated } = useAuth();

  return (
    <Route
      {...rest}
      render={(props) =>
        isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
      }
    />
  );
};

export default PrivateRoute;

Configuration

The use-auth-hook relies on a configuration object passed to the AuthProvider. This configuration includes:

  • baseURL: The base URL of your API server.
  • endpoints: An object containing the endpoints for various authentication actions.
const authConfig = {
  baseURL: 'https://yourapi.com',
  endpoints: {
    login: '/auth/login',
    refreshToken: '/auth/refresh-token',
    logout: '/auth/logout',
    oauth: '/auth/oauth',
  },
};

Advanced Features

Multi-Factor Authentication (MFA)

To integrate MFA, ensure your backend supports MFA and the frontend handles MFA challenges. If the requiresMFA flag is returned during login, you can trigger a secondary authentication step.

OAuth Integration

Use the startOAuthFlow function from the hook to initiate OAuth authentication flows. This function redirects users to the OAuth provider's authentication page.

const { startOAuthFlow } = useAuth();

// Trigger OAuth flow for a specific provider (e.g., Google)
const handleOAuthLogin = () => startOAuthFlow('google');

Token Management

Tokens are securely stored using HttpOnly and Secure cookies, preventing access through JavaScript and ensuring they are sent only over HTTPS.

Error Handling

The useAuth hook provides an error state to capture and display error messages to users. This helps in diagnosing issues during the authentication process.

Security Best Practices

Secure Storage: Use HttpOnly and Secure flags for cookies to store tokens safely. Token Expiry: Implement automatic token refresh and handle expired tokens gracefully. Role-Based Access Control: Use the checkPermission function to enforce user roles and permissions.

Authors

🔗 Links

portfolio linkedin twitter github