@metadiv-studio/admin-auth-context
v0.2.0
Published
A React context package for managing system administrator authentication state, providing login functionality, token refresh, and admin user management for React applications.
Readme
@metadiv-studio/admin-auth-context
A React context package for managing system administrator authentication state, providing login functionality, token refresh, and admin user management for React applications.
🚀 Quick Start
Install the package:
npm install @metadiv-studio/admin-auth-contextWrap your app with the
AdminAuthProvider:import { AdminAuthProvider } from '@metadiv-studio/admin-auth-context'; function App() { return ( <AdminAuthProvider> {/* Your app components */} </AdminAuthProvider> ); }Use the authentication context in your components:
import { useAdminAuthContext } from '@metadiv-studio/admin-auth-context'; function LoginForm() { const { login, admin } = useAdminAuthContext(); const handleSubmit = async (e) => { e.preventDefault(); await login('[email protected]', 'password'); }; return ( <form onSubmit={handleSubmit}> {/* Your login form */} </form> ); }
📦 Package Description
This package provides a complete authentication solution for system administrators with the following features:
- Authentication Context: React context for managing admin authentication state
- Login Management: Secure login with username/email and password
- Token Management: Automatic token storage and refresh functionality
- User State: Access to current admin user information and role
- Local Storage: Persistent authentication state across browser sessions
- TypeScript Support: Full type definitions for all interfaces and functions
🛠️ Usage Examples
Basic Authentication Setup
import React from 'react';
import { AdminAuthProvider, useAdminAuthContext } from '@metadiv-studio/admin-auth-context';
// Wrap your app with the provider
function App() {
return (
<AdminAuthProvider>
<AdminDashboard />
</AdminAuthProvider>
);
}
// Use authentication in your components
function AdminDashboard() {
const { admin, login, refreshToken } = useAdminAuthContext();
if (!admin) {
return <LoginForm />;
}
return (
<div>
<h1>Welcome, {admin.display_name}!</h1>
<p>Role: {admin.admin ? 'Administrator' : 'Member'}</p>
<button onClick={refreshToken}>Refresh Token</button>
</div>
);
}Login Form Component
import { useAdminAuthContext } from '@metadiv-studio/admin-auth-context';
import { useState } from 'react';
function LoginForm() {
const { login } = useAdminAuthContext();
const [credentials, setCredentials] = useState({ username: '', password: '' });
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
try {
await login(credentials.username, credentials.password);
// Login successful - user will be redirected or state will update
} catch (error) {
console.error('Login failed:', error);
} finally {
setLoading(false);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Username or Email"
value={credentials.username}
onChange={(e) => setCredentials(prev => ({ ...prev, username: e.target.value }))}
required
/>
<input
type="password"
placeholder="Password"
value={credentials.password}
onChange={(e) => setCredentials(prev => ({ ...prev, password: e.target.value }))}
required
/>
<button type="submit" disabled={loading}>
{loading ? 'Logging in...' : 'Login'}
</button>
</form>
);
}Protected Route Component
import { useAdminAuthContext } from '@metadiv-studio/admin-auth-context';
function ProtectedRoute({ children, requiredRole = 'member' }) {
const { admin, refreshToken } = useAdminAuthContext();
// Check if user is authenticated
if (!admin) {
return <div>Please log in to access this page.</div>;
}
// Check if user has required role
if (requiredRole === 'admin' && !admin.admin) {
return <div>Access denied. Administrator privileges required.</div>;
}
return <>{children}</>;
}
// Usage
function AdminOnlyPage() {
return (
<ProtectedRoute requiredRole="admin">
<div>This content is only visible to administrators.</div>
</ProtectedRoute>
);
}User Profile Display
import { useAdminAuthContext } from '@metadiv-studio/admin-auth-context';
function UserProfile() {
const { admin } = useAdminAuthContext();
if (!admin) return null;
return (
<div className="user-profile">
<img src={admin.avatar} alt={admin.display_name} />
<h2>{admin.display_name}</h2>
<p>Username: {admin.username}</p>
<p>Email: {admin.email}</p>
<p>Language: {admin.language}</p>
<p>Role: {admin.admin ? 'Administrator' : 'Member'}</p>
<p>Status: {admin.active ? 'Active' : 'Inactive'}</p>
</div>
);
}🔧 API Reference
AdminAuthProvider
React context provider that wraps your application to provide authentication state.
Props:
children: React.ReactNode- Your application components
useAdminAuthContext()
Hook that provides access to the authentication context.
Returns:
{
admin: SystemAdminDTO | null; // Current admin user data
login: (usernameOrEmail: string, password: string) => Promise<void>; // Login function
refreshToken: () => Promise<boolean>; // Token refresh function
}SystemAdminDTO
Interface for admin user data:
interface SystemAdminDTO {
id: number;
created_at: number;
updated_at: number;
uuid: string;
avatar: string;
display_name: string;
username: string;
email: string;
language: string;
admin: boolean; // true for administrators, false for members
active: boolean; // account status
}🔒 Security Features
- Token Storage: Access tokens are securely stored in localStorage
- Automatic Refresh: Built-in token refresh functionality
- Role-based Access: Support for different admin roles (admin/member)
- Session Persistence: Authentication state persists across browser sessions
📋 Dependencies
This package requires the following peer dependencies:
react^18react-dom^18
And includes these internal dependencies:
@metadiv-studio/axios-configurator- For API calls@metadiv-studio/context- For React context creation
🚀 Getting Started
Install the package:
npm install @metadiv-studio/admin-auth-contextSet up your API endpoints - Ensure your backend provides the required authentication endpoints
Wrap your app with the
AdminAuthProviderUse the context in your components with
useAdminAuthContext()
🤝 Contributing
This package is part of the Metadiv Studio ecosystem. For issues, feature requests, or contributions, please refer to the main repository.
📄 License
UNLICENSED - See package.json for details.
