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

@svene/basic-oauth2

v2.1.0

Published

A simple custom hook for handling OAuth2 authentication

Downloads

6

Readme

@svene/basic-oauth2

License: MIT

I created this for my personal use for my side project, but feel free to use it if it fits your needs. It is a simple hook for handling OAuth2 authentication with the default .NET Identity EntityFrameworkCoree endpoints. It provides a simple interface to interact with automatically generated API endpoints for authentication and user management.

Not really that good, but it works for me.

Table of Contents

Installation

To install the package, run:

npm install @svene/basic-oauth2

Quick Start

  1. Set up the API base URL:
import { setApiBaseUrl } from '@svene/basic-oauth2';

setApiBaseUrl('https://{base-url}.com');
  1. Use the useAuth hook in your components:
import { useAuth } from '@svene/basic-oauth2';

function LoginComponent() {
  const { login, accessToken } = useAuth();

  const handleLogin = async () => {
    try {
      await login({ email: '[email protected]', password: 'password123' });
      console.log('Logged in successfully');
    } catch (error) {
      console.error('Login failed', error);
    }
  };

  return (
    <div>
      {accessToken ? 'Logged in' : 'Not logged in'}
      <button onClick={handleLogin}>Login</button>
    </div>
  );
}

API Reference

The useAuth hook returns an object with the following methods and properties:

| Method/Property | Type | Description | |-----------------|------|-------------| | register | (data: RegisterRequest) => Promise<void> | Registers a new user | | login | (data: LoginRequest) => Promise<void> | Logs in a user | | refresh | (data: RefreshRequest) => Promise<void> | Refreshes the access token | | resendConfirmationEmail | (data: ResendConfirmationEmailRequest) => Promise<void> | Resends the confirmation email | | forgotPassword | (data: ForgotPasswordRequest) => Promise<void> | Initiates the password reset process | | resetPassword | (data: ResetPasswordRequest) => Promise<void> | Resets the user's password | | manageTwoFactor | (data: TwoFactorRequest) => Promise<any> | Manages two-factor authentication settings | | getInfo | () => Promise<InfoResponse> | Retrieves the user's information | | updateInfo | (data: InfoRequest) => Promise<InfoResponse> | Updates the user's information | | accessToken | string \| null | The current access token | | refreshToken | string \| null | The current refresh token | | setApiBaseUrl | (url: string) => void | Sets the base URL for API requests |

Usage

Registration

To register a new user:

const { register } = useAuth();

try {
  await register({ email: '[email protected]', password: 'securePassword123' });
  console.log('Registration successful');
} catch (error) {
  console.error('Registration failed', error);
}

Login

To log in a user:

const { login } = useAuth();

try {
  await login({ email: '[email protected]', password: 'password123' });
  console.log('Login successful');
} catch (error) {
  console.error('Login failed', error);
}

Two-Factor Authentication

To manage two-factor authentication:

const { manageTwoFactor } = useAuth();

try {
  const result = await manageTwoFactor({ 
    enable: true, 
    twoFactorCode: '123456' 
  });
  console.log('Two-factor authentication updated', result);
} catch (error) {
  console.error('Failed to update two-factor authentication', error);
}

TypeScript Interfaces

The package exports several TypeScript interfaces for type-safe usage:

  • RegisterRequest
  • LoginRequest
  • RefreshRequest
  • ResendConfirmationEmailRequest
  • ForgotPasswordRequest
  • ResetPasswordRequest
  • TwoFactorRequest
  • InfoRequest
  • AccessTokenResponse
  • InfoResponse

Import these as needed for type checking:

import { LoginRequest, AccessTokenResponse } from '@svene/basic-oauth2';

Error Handling

This doesn't handle errors internally. Wrap API calls in try-catch blocks and handle errors appropriately in your application:

try {
  await login({ email: '[email protected]', password: 'password123' });
} catch (error) {
  if (axios.isAxiosError(error)) {
    if (error.response?.status === 401) {
      console.error('Invalid credentials');
    } else {
      console.error('An error occurred:', error.message);
    }
  } else {
    console.error('An unexpected error occurred');
  }
}

Caveats and Limitations

  • API Structure. It is designed with a specific API structure in mind based on the default .NET Identity EntityFrameworkCore setup. You may need to customize it for other API structures.

  • Error handling. It is quite minimal, so there is a need to implement more robust error handling.

  • State management. It relies on React's useState. In more complex applications, you might want to integrate a state management library like Redux to handle state more effectively.

  • Token Management. It doesn't handle token expiration or automatic refresh robustly. You'll need to implement this logic yourself.

License

This project is licensed under the MIT License.

That's all.