@hayyantariqacme/user-management
v5.2.0
Published
Reusable login & signup UI components for React Native & Expo
Maintainers
Readme
@hayyantariqacme/user-management
Complete authentication solution for React Native & Expo with Google Sign-In support
A comprehensive, plug-and-play authentication package for React Native and Expo applications. Features beautiful UI components, complete authentication flow, Google Sign-In integration, and seamless backend API integration.
✨ Features
- 🎨 Beautiful UI Components - Pre-built Login & Signup screens with modern design
- 🔐 Complete Auth Flow - Login, Signup, Logout, Account deletion
- 🔑 Google Sign-In - One-tap Google authentication
- 🛡️ Secure Token Management - Automatic token handling and refresh
- 🔌 Backend Agnostic - Works with any backend (ASP.NET, Node.js, etc.)
- 📱 Cross Platform - Works on iOS, Android, and Web
- 🎭 Customizable - Fully customizable colors, logos, and styles
- 🪝 React Hooks - Easy-to-use hooks for authentication state
- 💾 Persistent Storage - Automatic user session persistence
- 🔄 Auto Token Refresh - Seamless token refresh mechanism
📦 Installation
npm install @hayyantariqacme/user-managementDependencies
This package requires the following peer dependencies:
npm install react react-native @expo/vector-icons @react-native-async-storage/async-storageFor Google Sign-In functionality:
npm install @react-native-google-signin/google-signin expo-auth-session expo-web-browser🚀 Quick Start
1. Basic Setup
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { AuthProvider, AuthSystem } from '@hayyantariqacme/user-management';
const authConfig = {
baseURL: 'https://your-api-domain.com',
endpoints: {
login: '/auth/login',
signup: '/auth/signup',
logout: '/auth/logout',
refresh: '/auth/refresh',
user: '/auth/user',
googleSignIn: '/auth/google',
delete: '/auth/delete'
}
};
function App() {
return (
<AuthProvider config={authConfig}>
<NavigationContainer>
<AuthSystem
logo={require('./assets/logo.png')}
onNavigateToHome={() => {
// Navigate to your main app screen
console.log('User authenticated, navigate to home');
}}
/>
</NavigationContainer>
</AuthProvider>
);
}
export default App;2. With Google Sign-In
import { AuthProvider } from '@hayyantariqacme/user-management';
const authConfig = {
baseURL: 'https://your-api-domain.com',
endpoints: {
login: '/auth/login',
signup: '/auth/signup',
logout: '/auth/logout',
refresh: '/auth/refresh',
user: '/auth/user',
googleSignIn: '/auth/google',
delete: '/auth/delete'
},
google: {
webClientId: 'your-web-client-id.googleusercontent.com',
iosClientId: 'your-ios-client-id.googleusercontent.com',
androidClientId: 'your-android-client-id.googleusercontent.com',
}
};
function App() {
return (
<AuthProvider config={authConfig}>
{/* Your app components */}
</AuthProvider>
);
}🎨 Components
AuthSystem
Complete authentication system with login and signup screens.
import { AuthSystem } from '@hayyantariqacme/user-management';
<AuthSystem
logo={require('./assets/logo.png')}
title="Sign in to your account"
backgroundColor="#FFFFFF"
primaryColor="#22C55E"
titleColor="#111827"
cardShadowColor="#000"
onNavigateToHome={() => navigation.navigate('Home')}
/>LoginPage
Standalone login component.
import { LoginPage } from '@hayyantariqacme/user-management';
<LoginPage
logo={require('./assets/logo.png')}
title="Welcome Back"
primaryColor="#3B82F6"
onGoToSignup={() => setScreen('signup')}
onNavigateToHome={() => navigation.navigate('Home')}
/>SignupPage
Standalone signup component.
import { SignupPage } from '@hayyantariqacme/user-management';
<SignupPage
logo={require('./assets/logo.png')}
backgroundColor="#F8FAFC"
primaryColor="#10B981"
onGoToLogin={() => setScreen('login')}
onNavigateToHome={() => navigation.navigate('Home')}
/>GoogleAuthButton
Standalone Google Sign-In button.
import { GoogleAuthButton } from '@hayyantariqacme/user-management';
<GoogleAuthButton
onSuccess={() => console.log('Google Sign-In successful')}
onError={(error) => console.error('Google Sign-In error:', error)}
buttonText="Continue with Google"
/>🪝 Hooks
useAuth
Main authentication hook providing all auth methods and state.
import { useAuth } from '@hayyantariqacme/user-management';
function MyComponent() {
const {
user,
isLoading,
isAuthenticated,
signIn,
signUp,
signOut,
signInWithGoogle,
deleteAccount
} = useAuth();
const handleLogin = async () => {
const result = await signIn('[email protected]', 'password');
if (result.success) {
console.log('Login successful');
} else {
console.log('Login failed:', result.message);
}
};
const handleGoogleSignIn = async () => {
try {
const result = await GoogleAuthService.signIn();
const authResult = await signInWithGoogle(result.idToken);
if (authResult.success) {
console.log('Google Sign-In successful');
}
} catch (error) {
console.error('Google Sign-In error:', error);
}
};
return (
<View>
{isAuthenticated ? (
<Text>Welcome, {user?.name}!</Text>
) : (
<Button title="Login" onPress={handleLogin} />
)}
</View>
);
}🔧 Configuration
AuthConfig
interface AuthConfig {
baseURL: string;
endpoints: {
login: string;
signup: string;
logout: string;
refresh: string;
user: string;
googleSignIn?: string;
delete: string;
};
tokenStorageKey?: string;
refreshTokenStorageKey?: string;
onAuthStateChange?: (user: User | null) => void;
onTokenExpired?: () => void;
google?: {
webClientId: string;
iosClientId?: string;
androidClientId?: string;
hostedDomain?: string;
offlineAccess?: boolean;
forceCodeForRefreshToken?: boolean;
};
}Environment Variables
Create a .env file in your project root:
EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID=your-web-client-id.googleusercontent.com
EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID=your-ios-client-id.googleusercontent.com
EXPO_PUBLIC_GOOGLE_ANDROID_CLIENT_ID=your-android-client-id.googleusercontent.com🛡️ Backend Integration
Expected API Endpoints
Your backend should implement these endpoints:
POST /auth/login
Request:
{
"email": "[email protected]",
"password": "password123"
}Response:
{
"success": true,
"message": "Login successful",
"user": {
"id": "user_id",
"name": "John Doe",
"email": "[email protected]",
"createdAt": "2024-01-01T00:00:00Z"
},
"accessToken": "jwt_access_token",
"refreshToken": "jwt_refresh_token",
"expiresAt": "2024-01-01T01:00:00Z"
}POST /auth/signup
Request:
{
"name": "John Doe",
"email": "[email protected]",
"password": "password123"
}POST /auth/google
Request:
{
"idToken": "google_id_token"
}POST /auth/refresh
Request:
{
"refreshToken": "refresh_token"
}GET /auth/user
Headers:
Authorization: Bearer access_tokenPOST /auth/logout
Headers:
Authorization: Bearer access_tokenDELETE /auth/delete
Headers:
Authorization: Bearer access_tokenASP.NET Core Example
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
[HttpPost("google")]
public async Task<IActionResult> GoogleSignIn([FromBody] GoogleSignInRequest request)
{
var payload = await GoogleJsonWebSignature.ValidateAsync(request.IdToken);
var user = await GetOrCreateUser(payload.Email, payload.Name);
var tokens = GenerateTokens(user);
return Ok(new AuthResponse
{
Success = true,
Message = "Google Sign-In successful",
User = user,
AccessToken = tokens.AccessToken,
RefreshToken = tokens.RefreshToken,
ExpiresAt = tokens.ExpiresAt
});
}
}📱 Platform Setup
Expo Configuration
Add to your app.json or app.config.js:
{
"expo": {
"plugins": [
[
"@react-native-google-signin/google-signin",
{
"iosUrlScheme": "YOUR_IOS_CLIENT_ID"
}
]
]
}
}Android Setup
Add to android/app/src/main/res/values/strings.xml:
<string name="google_android_client_id">YOUR_ANDROID_CLIENT_ID</string>iOS Setup
Add to ios/YourApp/Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>YOUR_IOS_CLIENT_ID</string>
</array>
</dict>
</array>🎨 Customization
Custom Colors
<AuthSystem
backgroundColor="#F0F9FF"
primaryColor="#0EA5E9"
titleColor="#0F172A"
cardShadowColor="#64748B"
/>Custom Styling
<GoogleAuthButton
style={{
backgroundColor: '#4285F4',
borderRadius: 8,
paddingVertical: 12,
}}
buttonText="Sign in with Google"
/>🔍 Advanced Usage
Direct Service Usage
import { GoogleAuthService, AuthApiClient } from '@hayyantariqacme/user-management';
// Configure Google Auth
GoogleAuthService.configure({
webClientId: 'your-web-client-id.googleusercontent.com'
});
// Use API client directly
const apiClient = new AuthApiClient(authConfig);
const user = await apiClient.getCurrentUser();Custom Token Management
import { TokenManager } from '@hayyantariqacme/user-management';
// Check if user has valid token
const hasToken = await TokenManager.hasValidToken();
// Get stored user
const user = await TokenManager.getUser();
// Clear tokens
await TokenManager.clearTokens();🚨 Error Handling
const { signIn } = useAuth();
try {
const result = await signIn(email, password);
if (!result.success) {
// Handle authentication error
Alert.alert('Login Failed', result.message);
}
} catch (error) {
// Handle network or other errors
Alert.alert('Error', 'An unexpected error occurred');
}🔒 Security Best Practices
- Always use HTTPS for your backend API
- Validate Google ID tokens on your backend
- Use environment variables for sensitive data
- Implement proper token expiration and refresh logic
- Store tokens securely using secure storage
- Implement rate limiting on your auth endpoints
📋 TypeScript Support
This package is written in TypeScript and provides full type definitions:
import type { User, AuthConfig, AuthContextType } from '@hayyantariqacme/user-management';
const user: User = {
id: 'user_id',
name: 'John Doe',
email: '[email protected]',
createdAt: '2024-01-01T00:00:00Z'
};🐛 Common Issues
Google Sign-In Issues
- DEVELOPER_ERROR: Check SHA-1 fingerprint in Google Console
- SIGN_IN_CANCELLED: User cancelled the sign-in process
- NETWORK_ERROR: Check internet connection
- INVALID_ACCOUNT: Account doesn't exist or is disabled
Backend Issues
- 401 Unauthorized: Check API endpoint and token validation
- CORS Error: Configure CORS on your backend
- Token Expired: Implement token refresh logic
📚 API Reference
Components
AuthSystem- Complete auth systemLoginPage- Login screenSignupPage- Signup screenGoogleAuthButton- Google Sign-In button
Hooks
useAuth- Main authentication hook
Services
AuthApiClient- API client for backend communicationGoogleAuthService- Google Sign-In serviceTokenManager- Token management utilities
Types
User- User object interfaceAuthConfig- Configuration interfaceAuthContextType- Auth context interfaceGoogleAuthConfig- Google configuration interface
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
👨💻 Author
Hayyan Tariq
- Email: [email protected]
- GitHub: @HayyanTariq
🙏 Acknowledgments
- React Native team for the amazing framework
- Expo team for simplifying React Native development
- Google for providing authentication services
📊 Package Stats
- ✅ Zero dependencies (only peer dependencies)
- 🚀 Lightweight - Minimal bundle size
- 📱 Cross-platform - Works on iOS, Android, and Web
- 🔧 Flexible - Works with any backend
- 🎨 Customizable - Fully customizable UI
Made with ❤️ by Hayyan Tariq
For more examples and detailed documentation, visit our GitHub repository.
