@skylabs-digital/react-identity-access
Version:
A comprehensive React library for multi-tenancy, authentication, authorization, roles, session management, and settings management
442 lines (350 loc) โข 11.4 kB
Markdown
A powerful, modern authentication and authorization library for React applications. Built with TypeScript, featuring role-based access control, permission management, Magic Link authentication, and seamless integration with React applications.
- **๐ Secure Authentication** - JWT-based authentication with automatic token refresh
- **โจ Magic Link Authentication** - Passwordless authentication via email with automatic verification
- **๐ง Flexible Login** - Support for both email and phone number authentication
- **๐ฅ Role-Based Access Control** - Granular permission system with role hierarchy
- **๐ก๏ธ Protected Components** - Easy-to-use components for conditional rendering
- **๐ฑ Multi-Tenant Support** - Built-in support for multi-tenant applications
- **๐ฏ TypeScript First** - Full TypeScript support with comprehensive type definitions
- **โก Modern React** - Built with React hooks and context for optimal performance
- **๐ Session Management** - Automatic session handling and token refresh
- **๐จ Feature Flags** - Built-in feature flag management
- **๐ณ Subscription Management** - Integrated billing and subscription handling
```bash
npm install @skylabs-digital/react-identity-access
yarn add @skylabs-digital/react-identity-access
pnpm add @skylabs-digital/react-identity-access
```
Wrap your application with the required providers:
```tsx
import {
AppProvider,
TenantProvider,
AuthProvider
} from '@skylabs-digital/react-identity-access';
function App() {
return (
<AppProvider
config={{
baseUrl: 'https://your-api.com',
appId: 'your-app-id',
}}
>
<TenantProvider
config={{
tenantMode: 'selector', // 'subdomain', 'selector', or 'fixed'
selectorParam: 'tenant',
}}
>
<AuthProvider>
{/* Your app components */}
</AuthProvider>
</TenantProvider>
</AppProvider>
);
}
```
```tsx
import { useAuth } from '@skylabs-digital/react-identity-access';
function LoginComponent() {
const { login, logout, sessionManager } = useAuth();
const user = sessionManager.getUser();
const handleLogin = async () => {
try {
// Supports both email and phone number
await login('user@example.com', 'password'); // Email
// await login('+1234567890', 'password'); // Phone
} catch (error) {
console.error('Login failed:', error);
}
};
return (
<div>
{user ? (
<div>
<p>Welcome, {user.name}!</p>
<button onClick={logout}>Logout</button>
</div>
) : (
<button onClick={handleLogin}>Login</button>
)}
</div>
);
}
```
```tsx
import {
MagicLinkForm,
MagicLinkVerify,
useAuth
} from '@skylabs-digital/react-identity-access';
import { useNavigate } from 'react-router-dom';
// Send Magic Link
function MagicLinkLogin() {
const navigate = useNavigate();
const handleSuccess = (response) => {
console.log('Magic link sent successfully!');
};
return (
<MagicLinkForm
frontendUrl="https://yourapp.com"
onSuccess={handleSuccess}
onLoginClick={() => navigate('/login')}
onSignupClick={() => navigate('/signup')}
/>
);
}
// Verify Magic Link (at /magic-link/verify route)
function MagicLinkVerifyPage() {
const navigate = useNavigate();
const handleSuccess = (data) => {
console.log('Magic link verified!', data);
navigate('/dashboard');
};
const handleError = (error) => {
console.error('Verification failed:', error);
};
return (
<MagicLinkVerify
onSuccess={handleSuccess}
onError={handleError}
onBackToLogin={() => navigate('/login')}
autoRedirectDelay={3000}
/>
);
}
```
```tsx
import { Protected } from '@skylabs-digital/react-identity-access';
function AdminPanel() {
return (
<Protected
requiredPermissions={['admin:read', 'users:manage']}
fallback={<div>Access denied</div>}
>
<div>Admin content here</div>
</Protected>
);
}
```
The library includes ready-to-use form components with full customization support:
```tsx
import {
LoginForm,
SignupForm,
MagicLinkForm,
MagicLinkVerify,
PasswordRecoveryForm
} from '@skylabs-digital/react-identity-access';
// Login Form (supports email/phone + password)
<LoginForm
onSuccess={(user) => console.log('Logged in:', user)}
onForgotPasswordClick={() => navigate('/forgot-password')}
onSignupClick={() => navigate('/signup')}
onMagicLinkClick={() => navigate('/magic-link')}
showMagicLinkOption={true}
/>
// Signup Form
<SignupForm
onSuccess={(user) => console.log('Signed up:', user)}
onLoginClick={() => navigate('/login')}
onMagicLinkClick={() => navigate('/magic-link')}
showMagicLinkOption={true}
/>
// Magic Link Form
<MagicLinkForm
frontendUrl="https://yourapp.com"
onSuccess={() => console.log('Magic link sent!')}
onLoginClick={() => navigate('/login')}
onSignupClick={() => navigate('/signup')}
/>
// Magic Link Verification
<MagicLinkVerify
onSuccess={(data) => navigate('/dashboard')}
onError={(error) => console.error(error)}
onBackToLogin={() => navigate('/login')}
/>
// Password Recovery
<PasswordRecoveryForm
onSuccess={() => console.log('Recovery email sent!')}
onBackToLogin={() => navigate('/login')}
/>
```
All components support full customization of copy, styles, and icons:
```tsx
<LoginForm
copy={{
title: 'Welcome Back',
submitButton: 'Sign In',
usernameLabel: 'Email or Phone',
}}
styles={{
container: { backgroundColor: '#f8f9fa' },
button: { backgroundColor: '#007bff' },
}}
icons={{
showPassword: <CustomEyeIcon />,
hidePassword: <CustomEyeOffIcon />,
}}
/>
```
- **AppProvider** - Application configuration and context
- **TenantProvider** - Multi-tenant configuration and management
- **AuthProvider** - Authentication and session management
- **FeatureFlagProvider** - Feature flag management
- **SubscriptionProvider** - Billing and subscription handling
The library uses a resource-action permission format:
```
resource:action
```
Examples:
- `users:read` - Read user data
- `products:write` - Create/update products
- `admin:*` - All admin permissions
- `reports:read` - View reports
- [๐ Implementation Guide](./docs/implementation.md)
- [๐ง Advanced Usage](./docs/advanced-usage.md)
- [๐ค Contributing](./docs/contributing.md)
- [๐ API Reference](./docs/api-reference.md)
- [๐ฏ Examples](./docs/examples.md)
A complete demo application is included in the `example/` directory. To run it:
```bash
cd example
yarn install
yarn start
```
The demo showcases:
- **Traditional Authentication** - Email/phone + password login
- **Magic Link Authentication** - Passwordless login with automatic verification
- **User Registration** - Signup with email/phone support
- **Password Recovery** - Reset password functionality
- **Role-based Dashboard** - Different views based on user roles
- **Permission Testing** - Interactive permission system testing
- **Protected Routes** - Route-level access control
- **Feature Flag Usage** - Dynamic feature toggling
- **Multi-tenant Support** - Tenant switching and management
- Node.js 18+
- yarn (recommended) or npm
```bash
git clone https://github.com/skylabs-digital/react-identity-access.git
cd react-identity-access
yarn install
yarn build
yarn test
yarn ci
cd example && yarn start
```
```
react-identity-access/
โโโ src/
โ โโโ components/
โ โโโ providers/
โ โโโ services/
โ โโโ types/
โ โโโ index.ts
โโโ example/
โโโ docs/
โโโ dist/
โโโ package.json
```
```env
REACT_APP_BASE_URL=https://your-api.com
REACT_APP_ID=your-app-id
REACT_APP_TENANT_MODE=subdomain
```
```tsx
// AppProvider Config
interface AppConfig {
baseUrl: string; // API base URL
appId: string; // Application identifier
apiTimeout?: number; // Request timeout (default: 30000)
retryAttempts?: number; // Retry attempts (default: 3)
}
// TenantProvider Config
interface TenantConfig {
tenantMode: 'subdomain' | 'selector' | 'fixed';
selectorParam?: string; // For 'selector' mode
fixedTenantSlug?: string; // For 'fixed' mode
initialTenant?: string; // Initial tenant value
}
```
The library includes comprehensive tests:
```bash
yarn test
yarn test:watch
yarn test:coverage
```
- **Tree-shakable** - Only import what you need
- **Lazy loading** - Components load on demand
- **Optimized re-renders** - Minimal React re-renders
- **Caching** - Intelligent caching of API responses
- **JWT tokens** with automatic refresh
- **Secure storage** of sensitive data
- **CSRF protection** built-in
- **Permission validation** on both client and server
- **Audit logging** for security events
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
MIT License - see [LICENSE](./LICENSE) file for details.
We welcome contributions! Please see our [Contributing Guide](./docs/contributing.md) for details.
- ๐ง Email: support@skylabs.com
- ๐ฌ Discord: [Join our community](https://discord.gg/skylabs)
- ๐ Issues: [GitHub Issues](https://github.com/skylabs-digital/react-identity-access/issues)
- ๐ Docs: [Documentation](./docs/)
- [x] **Magic Link Authentication** - Passwordless authentication via email โ
- [x] **Email/Phone Login Support** - Flexible authentication methods โ
- [x] **Pre-built Form Components** - Ready-to-use authentication forms โ
- [x] **Multi-tenant Architecture** - Separate App and Tenant providers โ
- [ ] **OAuth 2.0 / OpenID Connect** - Social login integration
- [ ] **Multi-factor Authentication** - SMS/TOTP support
- [ ] **Advanced Audit Logging** - Comprehensive security tracking
- [ ] **GraphQL Integration** - GraphQL API support
- [ ] **React Native Support** - Mobile app integration
- [ ] **SSR/Next.js Optimization** - Server-side rendering support
- [ ] **Biometric Authentication** - WebAuthn/FIDO2 support
---
Made with โค๏ธ by [Skylabs Digital](https://skylabs.digital)