1.0.1 • Published 8 months ago

@aetosky/auth v1.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
8 months ago
# @aetosky/auth

A lightweight OAuth2 client library for JavaScript and TypeScript, designed for seamless integration with Aetosky’s authentication flow. It handles login redirection, token exchange, automatic token refresh, and secure API requests.

## Features

- **OAuth2 Flow:** Manages login, callback handling, and token exchange.
- **Token Management:** Stores access and refresh tokens, and refreshes tokens automatically before expiration.
- **Secure Requests:** Automatically attaches a valid access token to API requests.
- **Easy Logout:** Clears stored tokens and redirects users to the login page.
- **Singleton Pattern:** Ensures a single instance of the Auth class is used throughout your application.
- **TypeScript Ready:** Fully typed for TypeScript, with full JavaScript compatibility.
- **Custom Error Handling:** Uses a custom `AuthError` class to provide meaningful error messages.

## Installation

### Using npm

```bash
npm install @aetosky/auth

Using yarn

yarn add @aetosky/auth

Quick Start

In your application, simply initialize the Auth instance and check for an active session. If the user isn’t logged in, the library will attempt to exchange an OAuth2 code for tokens or redirect to the login page if needed.

Example

import Auth from '@aetosky/auth';
import config from './config';

(async () => {
  // Initialize the singleton Auth instance with your backend URL and redirect URI
  const auth = Auth.getInstance({
    baseURL: config.backendUrl,
    redirectUri: window.location.origin
  });

  // Check if the user is logged in. If not, attempt to handle the OAuth2 callback.
  let logged = await auth.isLogged();
  if (!logged) {
    logged = await auth.exchangeCodeForToken();
  }

  // If still not logged in, redirect to the login page.
  if (!logged) {
    await auth.redirectToLogin();
  }

  // Retrieve and use the authenticated user's information.
  const user = await auth.getUser();
  console.log('User:', user);
})();

Usage Details

Initialization

Create an instance of the Auth class by providing your backend URL and a redirect URI:

import Auth from '@aetosky/auth';

const auth = new Auth({
  baseURL: 'https://app.aetosky.com',      // Your API base URL
  redirectUri: window.location.origin       // URL to redirect after login
});

Alternatively, use the singleton accessor:

const auth = Auth.getInstance({
  baseURL: 'https://app.aetosky.com',
  redirectUri: window.location.origin
});

OAuth2 Callback Handling

After the user logs in, the authentication server redirects back with an authorization code. Use handleAuthCallback() (or exchangeCodeForToken()) to exchange the code for tokens and clean up the URL:

await auth.handleAuthCallback();
// or
await auth.exchangeCodeForToken();

Getting a Valid Access Token

Retrieve the current access token. The library will refresh the token automatically if it is expired or about to expire:

const token = await auth.getToken();
console.log('Access token:', token);

Get current user information

You can also get the current user information:

const user = await auth.getUser();
console.log('User data:', user);

Logging Out

Clear tokens and redirect to the login page using the logout() method:

await auth.logout();

API Overview

  • getToken(): Promise<string | null>
    Returns a valid access token (refreshing it if necessary).

  • request(endpoint: string, options?: RequestInit): Promise<any>
    Makes an authenticated API request, attaching the access token to the request header.

  • getUser(): Promise<any>
    Retrieves user information via the /api/auth/me endpoint.

  • logout(): Promise<void>
    Logs out the user, clearing stored tokens and redirecting to login.

  • redirectToLogin(): Promise<void>
    Redirects the user to the login page.

  • exchangeCodeForToken(): Promise<boolean>
    Exchanges an OAuth2 code from the URL for access and refresh tokens, then cleans the URL.

  • clearTokens(): void
    Removes all token-related data from localStorage.

Error Handling

The library throws an AuthError for any authentication-related issues. Use try-catch blocks to handle these errors gracefully:

try {
  const user = await auth.getUser();
} catch (error) {
  if (error instanceof AuthError) {
    console.error('Authentication error:', error.message);
  }
}

AuthError Class

class AuthError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.name = "AuthError";
    this.statusCode = statusCode;
  }
}

License

This project is licensed under the MIT License - see the LICENSE file for details.

1.0.1

8 months ago

1.0.0

8 months ago