Code Monkey home page Code Monkey logo

allauth-axios's Introduction

Django AllauthClient Module

This project provides an axios-based client library and higher-level react context for the excellent Django Allauth library.

The AllauthClient module provides a client-side library for interacting with the authentication and account management endpoints of the django-allauth openapi spec. It supports both browser-based and app-based authentication flows.

Installation

Install the AllauthClient module using your preferred package manager. For example, using npm:

npx jsr add @knowsuchagency/allauth-axios

Usage

Importing the AllauthClient

import { AllauthClient } from "@knowsuchagency/allauth-axios";

Creating an AllauthClient Instance

Create an instance of the AllauthClient by providing the client type ('app' or 'browser') and the base URL of the API:

const allauthClient = new AllauthClient("browser", "https://api.example.com");

Authentication Methods

Login

const response = await allauthClient.login({
  username: "john",
  password: "secret",
});

Signup

const response = await allauthClient.signup({
  email: "[email protected]",
  password: "secret",
});

Logout

await allauthClient.logout(sessionToken);

Get Authentication Status

const response = await allauthClient.getAuthenticationStatus(sessionToken);

Email Verification

Get Email Verification Info

const response = await allauthClient.getEmailVerificationInfo(key);

Verify Email

const response = await allauthClient.verifyEmail({ key }, sessionToken);

Password Management

Request Password Reset

await allauthClient.requestPassword({ email: "[email protected]" });

Get Password Reset Info

const response = await allauthClient.getPasswordResetInfo(key);

Reset Password

const response = await allauthClient.resetPassword({
  key,
  password: "newPassword",
});

Change Password

await allauthClient.changePassword(
  { current_password: "oldPassword", new_password: "newPassword" },
  sessionToken
);

Social Account Management

Get Provider Accounts

const providerAccounts = await allauthClient.getProviderAccounts(sessionToken);

Disconnect Provider Account

const providerAccounts = await allauthClient.disconnectProviderAccount(
  { provider: "google", account: "[email protected]" },
  sessionToken
);

Email Address Management

Get Email Addresses

const emailAddresses = await allauthClient.getEmailAddresses(sessionToken);

Add Email Address

const emailAddresses = await allauthClient.addEmailAddress(
  { email: "[email protected]" },
  sessionToken
);

Change Primary Email Address

const emailAddresses = await allauthClient.changePrimaryEmailAddress(
  { email: "[email protected]", primary: true },
  sessionToken
);

Remove Email Address

const emailAddresses = await allauthClient.removeEmailAddress(
  { email: "[email protected]" },
  sessionToken
);

Multi-Factor Authentication (MFA)

Get Authenticators

const authenticators = await allauthClient.getAuthenticators(sessionToken);

Get TOTP Authenticator

const totpAuthenticator = await allauthClient.getTOTPAuthenticator(
  sessionToken
);

Activate TOTP

const totpAuthenticator = await allauthClient.activateTOTP(
  { code: "123456" },
  sessionToken
);

Deactivate TOTP

await allauthClient.deactivateTOTP(sessionToken);

Get Recovery Codes

const recoveryCodes = await allauthClient.getRecoveryCodes(sessionToken);

Regenerate Recovery Codes

await allauthClient.regenerateRecoveryCodes(sessionToken);

Session Management

Get Sessions

const sessions = await allauthClient.getSessions();

Delete Session

const sessions = await allauthClient.deleteSession();

Error Handling

The AllauthClient methods throw errors if there are any issues during the API requests. Make sure to handle these errors appropriately in your code.

Configuration

The AllauthClient constructor accepts the following parameters:

  • client: The client type, either 'app' or 'browser'.
  • apiBaseUrl: The base URL of the API.

Make sure to provide the correct values based on your API setup.

Conclusion

The AllauthClient module provides a convenient way to interact with an Allauth-compliant authentication and account management API from the client-side. It supports a wide range of authentication and account-related functionalities, making it easier to integrate authentication into your application.

Remember to handle errors appropriately and refer to the API documentation for specific endpoint details and requirements.

React Authentication Context Module

This module provides a React context for handling user authentication using the AllauthClient class. It allows you to easily manage authentication state and perform authentication actions within your React components.

Installation

npx jsr add @knowsuchagency/allauth-axios

Usage

  1. Wrap your application or the components that require authentication with the AuthProvider component. Pass the necessary props:

    • apiBaseUrl: The base URL of your authentication API.
    • client: The client type, either 'app' or 'browser'.

    Example:

    import React from "react";
    import { AuthProvider } from "@knowsuchagency/allauth-axios/react";
    
    const App = () => {
      return (
        <AuthProvider apiBaseUrl="https://api.example.com" client="browser">
          {/* Your application components */}
        </AuthProvider>
      );
    };
    
    export default App;
  2. Use the useAuth hook in your components to access the authentication state and functions.

    Example:

    import React from "react";
    import { useAuth } from "@knowsuchagency/allauth-axios/react";
    
    const LoginForm = () => {
      const { login, isAuthenticated, user } = useAuth();
    
      const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        const email = "[email protected]";
        const password = "password123";
        await login({ email, password });
      };
    
      if (isAuthenticated) {
        return <div>Welcome, {user?.display}!</div>;
      }
    
      return (
        <form onSubmit={handleLogin}>
          {/* Login form fields */}
          <button type="submit">Login</button>
        </form>
      );
    };
    
    export default LoginForm;

API

AuthProvider

The AuthProvider component is responsible for managing the authentication state and providing the authentication context to its children components.

Props:

  • children (required): The child components that will have access to the authentication context.
  • apiBaseUrl (required): The base URL of your authentication API.
  • client (required): The client type, either 'app' or 'browser'.

useAuth

The useAuth hook allows you to access the authentication state and functions within your components.

Returns:

  • user: The currently authenticated user object, or null if not authenticated.
  • isAuthenticated: A boolean indicating whether the user is authenticated.
  • login: A function to initiate the login process. It accepts an object with username (optional), email (optional), and password (required) properties.
  • signup: A function to initiate the signup process. It accepts an object with email (optional), username (optional), and password (required) properties.
  • logout: A function to log out the currently authenticated user.

Error Handling

The module logs errors to the console if there are any issues during the authentication process. You can customize the error handling logic by modifying the catch blocks in the login, signup, and logout functions.

Example

Here's a complete example of how to use the authentication context module in a React application:

// App.tsx
import React from 'react';
import { AuthProvider } from "@knowsuchagency/allauth-axios/react";
import LoginForm from './LoginForm';

const App = () => {
  return (
    <AuthProvider apiBaseUrl="https://api.example.com" client="browser">
      <div>
        <h1>My App</h1>
        <LoginForm />
      </div>
    </AuthProvider>
  );
};

export default App;

// LoginForm.tsx
import React from 'react';
import { useAuth } from "@knowsuchagency/allauth-axios/react";

const LoginForm = () => {
  const { login, isAuthenticated, user, logout } = useAuth();

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    const email = '[email protected]';
    const password = 'password123';
    await login({ email, password });
  };

  const handleLogout = async () => {
    await logout();
  };

  if (isAuthenticated) {
    return (
      <div>
        <p>Welcome, {user?.display}!</p>
        <button onClick={handleLogout}>Logout</button>
      </div>
    );
  }

  return (
    <form onSubmit={handleLogin}>
      {/* Login form fields */}
      <button type="submit">Login</button>
    </form>
  );
};

export default LoginForm;

In this example, the App component wraps the application with the AuthProvider, passing the necessary props. The LoginForm component uses the useAuth hook to access the authentication state and functions. It renders a login form if the user is not authenticated, and a welcome message with a logout button if the user is authenticated.

allauth-axios's People

Contributors

knowsuchagency avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.