auth-node-test
v1.0.7
Published
DAuth SDK - OAuth 2.0 with PKCE and Wallet Authentication
Maintainers
Readme
DAuth SDK
A modern JavaScript SDK for DAuth OAuth 2.0 with PKCE and Wallet Authentication, similar to Auth0 and Google Auth SDKs.
Installation
npm install dauth
# or
yarn add dauthQuick Start
Basic Usage (Vanilla JavaScript)
import { DAuth } from 'dauth';
// Initialize the SDK
const dauth = new DAuth({
clientId: 'your_client_id',
redirectUri: 'http://localhost:3000/callback',
});
// Login
await dauth.login();
// Handle callback (in your callback route)
const tokens = await dauth.handleCallback();
// Check authentication
if (dauth.isAuthenticated()) {
const tokens = dauth.getTokens();
const user = await dauth.getUserInfo();
}
// Logout
dauth.logout({ returnTo: '/' });React Usage with Hooks
import { useDAuth } from 'dauth';
function App() {
const {
isAuthenticated,
isLoading,
user,
login,
logout
} = useDAuth({
clientId: 'your_client_id',
redirectUri: 'http://localhost:3000/callback',
});
if (isLoading) {
return <div>Loading...</div>;
}
return (
<div>
{isAuthenticated ? (
<div>
<p>Welcome, {user?.name}!</p>
<button onClick={() => logout()}>Logout</button>
</div>
) : (
<button onClick={() => login()}>Login</button>
)}
</div>
);
}Protected Routes
import { useDAuth, useRequireAuth } from 'dauth';
function Dashboard() {
const { isAuthenticated } = useDAuth({
clientId: 'your_client_id',
redirectUri: 'http://localhost:3000/callback'
});
// Redirect to login if not authenticated
useRequireAuth({
isAuthenticated,
redirectTo: '/login'
});
return <div>Protected Dashboard</div>;
}Callback Handler
import { useDAuth } from 'dauth';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
function Callback() {
const { handleCallback, isLoading } = useDAuth({
clientId: 'your_client_id',
redirectUri: 'http://localhost:3000/callback'
});
const navigate = useNavigate();
useEffect(() => {
const processCallback = async () => {
try {
await handleCallback();
navigate('/dashboard');
} catch (error) {
console.error('Callback error:', error);
navigate('/login');
}
};
processCallback();
}, [handleCallback, navigate]);
return <div>Completing sign-in...</div>;
}API Reference
DAuth Class
Constructor Options
interface DAuthConfig {
clientId: string; // Required: Your client ID
clientSecret?: string; // Optional: Client secret (for confidential clients)
redirectUri: string; // Required: Callback URL
apiUrl?: string; // Optional: API base URL
authUrl?: string; // Optional: Authorization server URL
scope?: string; // Optional: OAuth scope (default: 'openid profile email')
responseType?: string; // Optional: Response type (default: 'code')
tokenStorageKey?: string; // Optional: localStorage key for tokens (default: 'dauth_tokens')
pkceStorageKey?: string; // Optional: localStorage key for PKCE verifier
stateStorageKey?: string; // Optional: localStorage key for state
}Methods
login(options?: { state?: string, loginUrl?: string }): Promise<void>
Initiates the login flow by redirecting to the authorization server.
await dauth.login();handleCallback(options?: { code?: string, state?: string }): Promise<Object>
Handles the OAuth callback and exchanges the authorization code for tokens.
const tokens = await dauth.handleCallback();logout(options?: { returnTo?: string }): void
Clears stored tokens and optionally redirects.
dauth.logout({ returnTo: '/' });isAuthenticated(): boolean
Checks if the user is currently authenticated.
if (dauth.isAuthenticated()) {
// User is logged in
}getTokens(): Object | null
Retrieves stored tokens.
const tokens = dauth.getTokens();
// { access_token, id_token, token_type, expires_in, expires_at }getAuthHeader(): Object
Returns authorization header for API requests.
const headers = dauth.getAuthHeader();
// { Authorization: 'Bearer <token>' }getUserInfo(): Promise<Object>
Fetches user information using the access token.
const user = await dauth.getUserInfo();refreshToken(): Promise<Object>
Refreshes the access token using the refresh token.
const newTokens = await dauth.refreshToken();clearTokens(): void
Clears all stored tokens and PKCE data.
dauth.clearTokens();Wallet Methods
getWallet(): Promise<Object | null>
Gets the connected wallet account.
const wallet = await dauth.getWallet();getSignature(message: string): Promise<string | null>
Requests signature from wallet.
const signature = await dauth.getSignature('Sign this message');getUserAccounts(walletAddress: string): Promise<Array>
Gets user accounts associated with a wallet address.
const accounts = await dauth.getUserAccounts(walletAddress);React Hooks
useDAuth(config: DAuthConfig)
Returns authentication state and methods.
interface UseDAuthReturn {
dauth: DAuth; // DAuth instance
isAuthenticated: boolean; // Authentication status
isLoading: boolean; // Loading state
user: Object | null; // User information
error: Error | null; // Error state
login: (options?) => Promise<void>;
logout: (options?) => void;
handleCallback: (options?) => Promise<Object>;
getUserInfo: () => Promise<Object>;
getTokens: () => Object | null;
refreshToken: () => Promise<Object>;
}useRequireAuth(options: { isAuthenticated: boolean, redirectTo?: string })
Hook to protect routes by redirecting unauthenticated users.
useRequireAuth({
isAuthenticated,
redirectTo: '/login'
});Advanced Usage
Custom Token Storage
class CustomStorage {
getItem(key) { /* ... */ }
setItem(key, value) { /* ... */ }
removeItem(key) { /* ... */ }
}
// You can override token storage by modifying the DAuth class
// or use the tokenStorageKey option to use a different localStorage keyError Handling
try {
await dauth.login();
} catch (error) {
if (error.message === 'Failed to initiate login') {
// Handle login error
}
}
try {
await dauth.handleCallback();
} catch (error) {
if (error.message === 'Authorization code not found') {
// Handle callback error
}
}Making Authenticated API Requests
import axios from 'axios';
const dauth = new DAuth({ /* config */ });
async function fetchProtectedData() {
const headers = dauth.getAuthHeader();
try {
const response = await axios.get('https://api.example.com/data', {
headers
});
return response.data;
} catch (error) {
if (error.response?.status === 401) {
// Token expired, try refresh
await dauth.refreshToken();
// Retry request
const newHeaders = dauth.getAuthHeader();
const retryResponse = await axios.get('https://api.example.com/data', {
headers: newHeaders
});
return retryResponse.data;
}
throw error;
}
}Configuration
Environment Variables
You can use environment variables for configuration:
const dauth = new DAuth({
clientId: import.meta.env.VITE_DAUTH_CLIENT_ID,
redirectUri: import.meta.env.VITE_DAUTH_REDIRECT_URI,
apiUrl: import.meta.env.VITE_DAUTH_API_URL
});Browser Support
- Modern browsers with ES6+ support
- Requires Web Crypto API for PKCE
- Wallet functionality requires NCOG provider
License
MIT
