authosphere-react
v2.0.0
Published
Complete React authentication components for Authosphere
Downloads
3
Maintainers
Readme
⚛️ Authosphere React Components
Ready-to-use React authentication components with OAuth support.
✨ Features
- 🔑 Authentication Context - React Context for auth state management
- 📱 Ready-to-use Components - Login, register, profile components
- 🌐 OAuth Integration - Google, GitHub, Facebook buttons
- 🛡️ Protected Routes - Route protection wrapper
- 🎨 Customizable - Fully customizable styling and behavior
- 📱 Responsive - Mobile-friendly design
- 🎯 TypeScript Ready - Full TypeScript support
🚀 Quick Start
Installation
npm install @authosphere/react-auth-componentBasic Usage
import React from 'react';
import {
AuthProvider,
ProtectedRoute,
useAuth
} from '@authosphere/react-auth-component';
function App() {
return (
<AuthProvider apiUrl="http://localhost:3000/auth">
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
</AuthProvider>
);
}
function Dashboard() {
const { user, logout } = useAuth();
return (
<div>
<h1>Welcome, {user?.firstName}!</h1>
<button onClick={logout}>Logout</button>
</div>
);
}
export default App;📦 Components
AuthProvider
Authentication context provider that manages auth state.
import { AuthProvider } from '@authosphere/react-auth-component';
function App() {
return (
<AuthProvider apiUrl="http://localhost:3000/auth">
{/* Your app components */}
</AuthProvider>
);
}Props:
apiUrl(string, required) - Backend API URLchildren(ReactNode, required) - App components
useAuth Hook
Hook to access authentication state and methods.
import { useAuth } from '@authosphere/react-auth-component';
function MyComponent() {
const {
user,
token,
loading,
isAuthenticated,
login,
register,
logout,
oauthLogin
} = useAuth();
return (
<div>
{isAuthenticated ? (
<p>Welcome, {user?.firstName}!</p>
) : (
<p>Please log in</p>
)}
</div>
);
}Returns:
user- User objecttoken- JWT tokenloading- Loading stateisAuthenticated- Authentication statuslogin(email, password)- Login functionregister(email, password, firstName?, lastName?)- Register functionlogout()- Logout functionoauthLogin(provider)- OAuth login function
ProtectedRoute
Wrapper component that protects routes from unauthenticated users.
import { ProtectedRoute } from '@authosphere/react-auth-component';
function App() {
return (
<ProtectedRoute>
<SecretPage />
</ProtectedRoute>
);
}Props:
children(ReactNode, required) - Protected componentsfallback(ReactNode, optional) - Custom fallback component
AuthForm
Complete authentication form with login/register functionality.
import { AuthForm } from '@authosphere/react-auth-component';
function LoginPage() {
return (
<div>
<AuthForm />
</div>
);
}Props:
mode('login' | 'register', optional) - Default form modeonSuccess(function, optional) - Success callbackonError(function, optional) - Error callbackstyle(object, optional) - Custom styles
OAuthButtons
OAuth provider buttons for social login.
import { OAuthButtons } from '@authosphere/react-auth-component';
function LoginPage() {
return (
<div>
<OAuthButtons providers={['google', 'github']} />
</div>
);
}Props:
providers(string[], required) - Available OAuth providersonProviderClick(function, optional) - Provider click callbackstyle(object, optional) - Custom styles
UserProfile
User profile display component.
import { UserProfile } from '@authosphere/react-auth-component';
function ProfilePage() {
return (
<div>
<UserProfile />
</div>
);
}Props:
showDeleteButton(boolean, optional) - Show delete account buttononDeleteAccount(function, optional) - Delete account callbackstyle(object, optional) - Custom styles
🎨 Customization
Custom Styling
All components accept custom styles:
<AuthForm
style={{
maxWidth: '400px',
margin: '0 auto',
padding: '20px',
border: '1px solid #ddd',
borderRadius: '8px'
}}
/>Custom Components
You can build custom components using the useAuth hook:
import { useAuth } from '@authosphere/react-auth-component';
function CustomLogin() {
const { login, loading } = useAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
const result = await login(email, password);
if (result.success) {
console.log('Login successful!');
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<button type="submit" disabled={loading}>
{loading ? 'Loading...' : 'Login'}
</button>
</form>
);
}Theme Customization
Use CSS variables for consistent theming:
:root {
--auth-primary-color: #007bff;
--auth-secondary-color: #6c757d;
--auth-success-color: #28a745;
--auth-danger-color: #dc3545;
--auth-border-radius: 4px;
--auth-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto;
}🔐 OAuth Integration
Supported Providers
- ✅ Google - Full support
- ✅ GitHub - Full support
- ✅ Facebook - Full support
- 🔄 Discord - Coming soon
- 🔄 Twitter - Coming soon
OAuth Setup
- Configure OAuth providers in backend
- Use OAuthButtons component:
<OAuthButtons
providers={['google', 'github']}
onProviderClick={(provider) => {
console.log(`Login with ${provider}`);
}}
/>Custom OAuth Flow
import { useAuth } from '@authosphere/react-auth-component';
function CustomOAuthButton({ provider }) {
const { oauthLogin } = useAuth();
return (
<button onClick={() => oauthLogin(provider)}>
Login with {provider}
</button>
);
}🛡️ Security
Token Management
- Automatic token storage in localStorage
- Token refresh on expiration
- Secure token validation
- Automatic logout on invalid token
CORS Configuration
Ensure your backend is configured for CORS:
// Backend configuration
const authosphere = createAuthosphere({
cors: {
origin: ['http://localhost:3000', 'https://yourdomain.com'],
credentials: true
}
});📱 Responsive Design
All components are mobile-friendly and responsive:
// Mobile-first design
<AuthForm
style={{
width: '100%',
maxWidth: '400px',
padding: '20px',
'@media (max-width: 768px)': {
padding: '10px'
}
}}
/>🧪 Testing
Unit Tests
npm testComponent Tests
npm run test:componentsTest Coverage
npm run test:coverage📦 Dependencies
- react - React library
- react-dom - React DOM
- axios - HTTP client (optional)
🚀 Production Deployment
Build Optimization
npm run buildEnvironment Configuration
REACT_APP_API_URL=https://your-api-domain.com/authSecurity Best Practices
- Use HTTPS in production
- Configure proper CORS origins
- Implement proper error handling
- Use environment variables for API URLs
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
📞 Support
- 📧 Email: [email protected]
- 🌐 Website: www.terekhindt.com
- 🐛 Issues: GitHub Issues
Made with ❤️ by Terekhin Digital Crew
