npm package: @hayyantariqacme/user-management
Description: Reusable login & signup UI components for React Native & Expo
Author: Hayyan Tariq
Latest version: 5.2.0

# @hayyantariqacme/user-management

> Complete authentication solution for React Native & Expo with Google Sign-In support

[![npm version](https://badge.fury.io/js/%40hayyantariqacme%2Fuser-management.svg)](https://badge.fury.io/js/%40hayyantariqacme%2Fuser-management)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

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

```bash
npm install @hayyantariqacme/user-management
```

### Dependencies

This package requires the following peer dependencies:

```bash
npm install react react-native @expo/vector-icons @react-native-async-storage/async-storage
```

For Google Sign-In functionality:
```bash
npm install @react-native-google-signin/google-signin expo-auth-session expo-web-browser
```

## 🚀 Quick Start

### 1. Basic Setup

```tsx
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

```tsx
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.

```tsx
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.

```tsx
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.

```tsx
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.

```tsx
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.

```tsx
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('user@example.com', '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

```tsx
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:

```env
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:**
```json
{
  "email": "user@example.com",
  "password": "password123"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Login successful",
  "user": {
    "id": "user_id",
    "name": "John Doe",
    "email": "user@example.com",
    "createdAt": "2024-01-01T00:00:00Z"
  },
  "accessToken": "jwt_access_token",
  "refreshToken": "jwt_refresh_token",
  "expiresAt": "2024-01-01T01:00:00Z"
}
```

#### POST /auth/signup
**Request:**
```json
{
  "name": "John Doe",
  "email": "user@example.com",
  "password": "password123"
}
```

#### POST /auth/google
**Request:**
```json
{
  "idToken": "google_id_token"
}
```

#### POST /auth/refresh
**Request:**
```json
{
  "refreshToken": "refresh_token"
}
```

#### GET /auth/user
**Headers:**
```
Authorization: Bearer access_token
```

#### POST /auth/logout
**Headers:**
```
Authorization: Bearer access_token
```

#### DELETE /auth/delete
**Headers:**
```
Authorization: Bearer access_token
```

### ASP.NET Core Example

```csharp
[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`:

```json
{
  "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`:
```xml
<string name="google_android_client_id">YOUR_ANDROID_CLIENT_ID</string>
```

### iOS Setup

Add to `ios/YourApp/Info.plist`:
```xml
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>YOUR_IOS_CLIENT_ID</string>
    </array>
  </dict>
</array>
```

## 🎨 Customization

### Custom Colors

```tsx
<AuthSystem
  backgroundColor="#F0F9FF"
  primaryColor="#0EA5E9"
  titleColor="#0F172A"
  cardShadowColor="#64748B"
/>
```

### Custom Styling

```tsx
<GoogleAuthButton
  style={{
    backgroundColor: '#4285F4',
    borderRadius: 8,
    paddingVertical: 12,
  }}
  buttonText="Sign in with Google"
/>
```

## 🔍 Advanced Usage

### Direct Service Usage

```tsx
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

```tsx
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

```tsx
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

1. **Always use HTTPS** for your backend API
2. **Validate Google ID tokens** on your backend
3. **Use environment variables** for sensitive data
4. **Implement proper token expiration** and refresh logic
5. **Store tokens securely** using secure storage
6. **Implement rate limiting** on your auth endpoints

## 📋 TypeScript Support

This package is written in TypeScript and provides full type definitions:

```tsx
import type { User, AuthConfig, AuthContextType } from '@hayyantariqacme/user-management';

const user: User = {
  id: 'user_id',
  name: 'John Doe',
  email: 'user@example.com',
  createdAt: '2024-01-01T00:00:00Z'
};
```

## 🐛 Common Issues

### Google Sign-In Issues

1. **DEVELOPER_ERROR**: Check SHA-1 fingerprint in Google Console
2. **SIGN_IN_CANCELLED**: User cancelled the sign-in process
3. **NETWORK_ERROR**: Check internet connection
4. **INVALID_ACCOUNT**: Account doesn't exist or is disabled

### Backend Issues

1. **401 Unauthorized**: Check API endpoint and token validation
2. **CORS Error**: Configure CORS on your backend
3. **Token Expired**: Implement token refresh logic

## 📚 API Reference

### Components
- `AuthSystem` - Complete auth system
- `LoginPage` - Login screen
- `SignupPage` - Signup screen  
- `GoogleAuthButton` - Google Sign-In button

### Hooks
- `useAuth` - Main authentication hook

### Services
- `AuthApiClient` - API client for backend communication
- `GoogleAuthService` - Google Sign-In service
- `TokenManager` - Token management utilities

### Types
- `User` - User object interface
- `AuthConfig` - Configuration interface
- `AuthContextType` - Auth context interface
- `GoogleAuthConfig` - 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](LICENSE) file for details.

## 👨‍💻 Author

**Hayyan Tariq**

- Email: [hayyantariq2004@gmail.com](mailto:hayyantariq2004@gmail.com)
- GitHub: [@HayyanTariq](https://github.com/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](https://github.com/HayyanTariq)**

For more examples and detailed documentation, visit our [GitHub repository](https://github.com/HayyanTariq/user-management-module).