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.
Install the AllauthClient
module using your preferred package manager. For example, using npm:
npx jsr add @knowsuchagency/allauth-axios
import { AllauthClient } from "@knowsuchagency/allauth-axios";
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");
const response = await allauthClient.login({
username: "john",
password: "secret",
});
const response = await allauthClient.signup({
email: "[email protected]",
password: "secret",
});
await allauthClient.logout(sessionToken);
const response = await allauthClient.getAuthenticationStatus(sessionToken);
const response = await allauthClient.getEmailVerificationInfo(key);
const response = await allauthClient.verifyEmail({ key }, sessionToken);
await allauthClient.requestPassword({ email: "[email protected]" });
const response = await allauthClient.getPasswordResetInfo(key);
const response = await allauthClient.resetPassword({
key,
password: "newPassword",
});
await allauthClient.changePassword(
{ current_password: "oldPassword", new_password: "newPassword" },
sessionToken
);
const providerAccounts = await allauthClient.getProviderAccounts(sessionToken);
const providerAccounts = await allauthClient.disconnectProviderAccount(
{ provider: "google", account: "[email protected]" },
sessionToken
);
const emailAddresses = await allauthClient.getEmailAddresses(sessionToken);
const emailAddresses = await allauthClient.addEmailAddress(
{ email: "[email protected]" },
sessionToken
);
const emailAddresses = await allauthClient.changePrimaryEmailAddress(
{ email: "[email protected]", primary: true },
sessionToken
);
const emailAddresses = await allauthClient.removeEmailAddress(
{ email: "[email protected]" },
sessionToken
);
const authenticators = await allauthClient.getAuthenticators(sessionToken);
const totpAuthenticator = await allauthClient.getTOTPAuthenticator(
sessionToken
);
const totpAuthenticator = await allauthClient.activateTOTP(
{ code: "123456" },
sessionToken
);
await allauthClient.deactivateTOTP(sessionToken);
const recoveryCodes = await allauthClient.getRecoveryCodes(sessionToken);
await allauthClient.regenerateRecoveryCodes(sessionToken);
const sessions = await allauthClient.getSessions();
const sessions = await allauthClient.deleteSession();
The AllauthClient
methods throw errors if there are any issues during the API requests. Make sure to handle these errors appropriately in your code.
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.
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.
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.
npx jsr add @knowsuchagency/allauth-axios
-
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;
-
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;
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'
.
The useAuth
hook allows you to access the authentication state and functions within your components.
Returns:
user
: The currently authenticated user object, ornull
if not authenticated.isAuthenticated
: A boolean indicating whether the user is authenticated.login
: A function to initiate the login process. It accepts an object withusername
(optional),email
(optional), andpassword
(required) properties.signup
: A function to initiate the signup process. It accepts an object withemail
(optional),username
(optional), andpassword
(required) properties.logout
: A function to log out the currently authenticated user.
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.
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.