@metadiv-studio/user-auth-context
v0.3.16
Published
A comprehensive React authentication context package that provides user authentication, workspace management, and token handling for multi-tenant applications. Built with TypeScript and designed to work seamlessly with the Metadiv Studio ecosystem.
Readme
@metadiv-studio/user-auth-context
A comprehensive React authentication context package that provides user authentication, workspace management, and token handling for multi-tenant applications. Built with TypeScript and designed to work seamlessly with the Metadiv Studio ecosystem.
📦 Installation
npm i @metadiv-studio/user-auth-context🎯 What This Package Provides
This package offers a complete authentication solution including:
- User Authentication: Login, logout, and token management
- Workspace Management: Multi-tenant workspace support with role-based access
- Token Handling: Automatic token refresh and storage management
- Context Provider: React Context-based state management
- TypeScript Support: Full type definitions for all components and APIs
🚀 Quick Start
1. Wrap Your App with the Provider
import { UserAuthProvider } from '@metadiv-studio/user-auth-context';
function App() {
return (
<UserAuthProvider>
<YourAppComponents />
</UserAuthProvider>
);
}2. Use the Authentication Context
import { useUserAuthContext } from '@metadiv-studio/user-auth-context';
function LoginComponent() {
const { login, user, workspaceMember } = useUserAuthContext();
const handleLogin = async () => {
try {
await login('[email protected]', 'password123');
console.log('Login successful!');
} catch (error) {
console.error('Login failed:', error);
}
};
return (
<div>
{user ? (
<p>Welcome, {user.display_name}!</p>
) : (
<button onClick={handleLogin}>Login</button>
)}
</div>
);
}🔧 API Reference
UserAuthProvider
The main context provider that wraps your application and provides authentication state.
<UserAuthProvider>
{children}
</UserAuthProvider>useUserAuthContext Hook
Returns the authentication context with the following properties and methods:
State Properties
user: SystemUserDTO | null- Current authenticated userworkspaceMember: WorkspaceMemberDTO | null- Current workspace memberselfWorkspaces: WorkspaceMemberDTO[]- List of user's workspaces
Methods
login(usernameOrEmail: string, password: string): Promise<void>- Authenticate userrefreshToken(): Promise<boolean>- Refresh authentication tokenlistWorkspaces(): Promise<void>- Fetch user's workspacesgetWorkspace(): WorkspaceMemberDTO | null- Get current workspace
📖 Usage Examples
Basic Authentication Flow
import { useUserAuthContext } from '@metadiv-studio/user-auth-context';
function AuthExample() {
const {
user,
login,
logout,
workspaceMember,
listWorkspaces
} = useUserAuthContext();
useEffect(() => {
if (user) {
// Load user's workspaces when authenticated
listWorkspaces();
}
}, [user]);
if (!user) {
return (
<div>
<h2>Please Login</h2>
<button onClick={() => login('[email protected]', 'password')}>
Login
</button>
</div>
);
}
return (
<div>
<h2>Welcome, {user.display_name}!</h2>
<p>Email: {user.email}</p>
<p>Username: {user.username}</p>
{workspaceMember && (
<div>
<h3>Current Workspace</h3>
<p>Name: {workspaceMember.workspace?.name}</p>
<p>Role: {workspaceMember.role}</p>
</div>
)}
</div>
);
}Workspace Management
import { useUserAuthContext } from '@metadiv-studio/user-auth-context';
function WorkspaceSelector() {
const { selfWorkspaces, getWorkspace, refreshToken } = useUserAuthContext();
const currentWorkspace = getWorkspace();
const handleWorkspaceChange = async (workspaceId: number) => {
// Refresh token for the new workspace
const success = await refreshToken();
if (success) {
console.log('Workspace changed successfully');
}
};
return (
<div>
<h3>Select Workspace</h3>
<select
value={currentWorkspace?.id || ''}
onChange={(e) => handleWorkspaceChange(Number(e.target.value))}
>
{selfWorkspaces.map(workspace => (
<option key={workspace.id} value={workspace.id}>
{workspace.workspace?.name} ({workspace.role})
</option>
))}
</select>
</div>
);
}Protected Routes
import { useUserAuthContext } from '@metadiv-studio/user-auth-context';
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { user, workspaceMember } = useUserAuthContext();
if (!user) {
return <div>Please log in to access this page.</div>;
}
if (!workspaceMember) {
return <div>Please select a workspace to continue.</div>;
}
return <>{children}</>;
}
// Usage
function App() {
return (
<UserAuthProvider>
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
</UserAuthProvider>
);
}🏗️ Data Models
SystemUserDTO
interface SystemUserDTO {
id: number;
created_at: number;
updated_at: number;
uuid: string;
avatar: string;
username: string;
email: string;
display_name: string;
language: string;
active: boolean;
invited: boolean;
invited_at: number;
}WorkspaceMemberDTO
interface WorkspaceMemberDTO {
id: number;
created_at: number;
updated_at: number;
workspace?: WorkspaceDTO;
user?: SystemUserDTO;
role: string;
active: boolean;
invited: boolean;
}WorkspaceDTO
interface WorkspaceDTO {
id: number;
created_at: number;
updated_at: number;
uuid: string;
avatar: string;
name: string;
time_zone: string;
active: boolean;
}🔐 Authentication Flow
- Login: User provides credentials → API call → Store token and user data
- Token Refresh: Automatic token refresh when needed
- Workspace Selection: User selects workspace → Refresh token for workspace context
- State Persistence: User and workspace data stored in localStorage
- Automatic Cleanup: Invalid tokens and expired sessions handled automatically
🛠️ Dependencies
This package requires the following peer dependencies:
react^18react-dom^18
And includes these internal dependencies:
@metadiv-studio/axios-configurator- HTTP client configuration@metadiv-studio/button- UI button component@metadiv-studio/context- Context creation utilities
🎨 Styling
The package includes a Badge component that can be styled with Tailwind CSS classes:
import { Badge } from '@metadiv-studio/user-auth-context';
function UserBadge() {
return (
<Badge className="bg-blue-500 text-white">
Premium User
</Badge>
);
}🔧 Configuration
The package automatically handles:
- Local Storage Keys: Access tokens, user data, and workspace information
- API Endpoints: Authentication and workspace management endpoints
- Error Handling: Graceful fallbacks for failed requests
- Token Management: Automatic refresh and cleanup
🚨 Error Handling
All authentication methods include proper error handling:
const { login } = useUserAuthContext();
try {
await login('[email protected]', 'password');
} catch (error) {
// Handle login errors
console.error('Authentication failed:', error);
}📱 Browser Support
- Modern browsers with ES6+ support
- React 18+ applications
- TypeScript 5+ projects
🤝 Contributing
This package is part of the Metadiv Studio ecosystem. For issues, feature requests, or contributions, please refer to the main Metadiv Studio repository.
📄 License
UNLICENSED - See package.json for details.
Built with ❤️ by the Metadiv Studio Team
