npm package: @snssoftware/readin-auth-client
Description: React authentication client with JWT token management, context provider, and hooks
Author: SNS Software
Latest version: 1.0.1

# @snssoftware/readin-auth-client

⚡ React authentication client with JWT token management, context provider, and automatic token refresh.

## Features

- ✅ React Context API for global auth state
- ✅ Automatic JWT token refresh with axios interceptors
- ✅ TypeScript support
- ✅ localStorage token management
- ✅ Login, Register, Logout functionality
- ✅ Google OAuth support
- ✅ Error handling and loading states
- ✅ Email verification & password reset

## Installation

```bash
npm install @snssoftware/readin-auth-client
```

## Peer Dependencies

```bash
npm install react axios
```

## Quick Start

### 1. Wrap Your App with AuthProvider

```typescript
import { AuthProvider, initializeAuthClient } from '@snssoftware/readin-auth-client';

// Initialize with your API URL
initializeAuthClient('http://localhost:5003/api');

function App() {
  return (
    <AuthProvider>
      {/* Your app components */}
    </AuthProvider>
  );
}
```

### 2. Use the Auth Hook

```typescript
import { useAuth } from '@snssoftware/readin-auth-client';

function LoginPage() {
  const { login, user, loading, error } = useAuth();

  const handleLogin = async (email: string, password: string) => {
    try {
      await login(email, password);
      // Login successful, user is now authenticated
    } catch (err) {
      // Handle error
    }
  };

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      {error && <p>{error}</p>}
      {user ? <p>Welcome {user.firstName}!</p> : <LoginForm onSubmit={handleLogin} />}
    </div>
  );
}
```

### 3. Setup Automatic Token Refresh

```typescript
import { useAuthToken } from '@snssoftware/readin-auth-client';

function App() {
  useAuthToken(); // Sets up axios interceptors

  return (
    <div>
      {/* Your app */}
    </div>
  );
}
```

## API Reference

### `useAuth()` Hook

Provides access to authentication state and methods:

```typescript
const {
  user,              // Current user object or null
  token,             // JWT token or null
  loading,           // Loading state
  error,             // Error message or null
  isAuthenticated,   // Boolean - true if user is logged in
  login,             // (email, password) => Promise<void>
  register,          // (userData) => Promise<void>
  logout,            // () => Promise<void>
  googleLogin,       // () => void - Redirects to Google OAuth
  clearError         // () => void - Clears error state
} = useAuth();
```

### `AuthService`

Direct access to auth API methods:

```typescript
import { AuthService } from '@snssoftware/readin-auth-client';

// Login
const response = await AuthService.login(email, password);

// Register
const response = await AuthService.register({
  email,
  password,
  firstName,
  lastName,
  role: 'parent'
});

// Logout
await AuthService.logout();

// Get profile
const profile = await AuthService.getProfile();

// Refresh token
await AuthService.refreshToken();

// Verify email
await AuthService.verifyEmail(token);

// Request password reset
await AuthService.requestPasswordReset(email);

// Reset password
await AuthService.resetPassword(token, newPassword);

// Check if authenticated
const isAuth = AuthService.isAuthenticated();
```

### `useAuthToken()` Hook

Sets up axios interceptors for automatic token management:

```typescript
import { useAuthToken } from '@snssoftware/readin-auth-client';

function App() {
  useAuthToken();
  // Axios will now automatically:
  // - Add Authorization header to requests
  // - Refresh expired tokens
  // - Redirect to login on auth failure
  
  return <YourApp />;
}
```

## Types

```typescript
import type {
  User,
  AuthContextType,
  RegisterData,
  LoginResponse,
  RegisterResponse,
  ApiError
} from '@snssoftware/readin-auth-client';
```

## Complete Example

```typescript
// app.tsx
import { AuthProvider, useAuthToken, initializeAuthClient } from '@snssoftware/readin-auth-client';

initializeAuthClient(process.env.REACT_APP_API_URL!);

function App() {
  useAuthToken();
  
  return (
    <AuthProvider>
      <Router>
        <Routes>
          <Route path="/login" element={<LoginPage />} />
          <Route path="/register" element={<RegisterPage />} />
          <Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
        </Routes>
      </Router>
    </AuthProvider>
  );
}

// LoginPage.tsx
import { useAuth } from '@snssoftware/readin-auth-client';

function LoginPage() {
  const { login, loading, error } = useAuth();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await login(email, password);
      navigate('/dashboard');
    } catch (err) {
      console.error('Login failed:', err);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {error && <div className="error">{error}</div>}
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        disabled={loading}
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        disabled={loading}
      />
      <button type="submit" disabled={loading}>
        {loading ? 'Logging in...' : 'Login'}
      </button>
    </form>
  );
}

// ProtectedRoute.tsx
import { useAuth } from '@snssoftware/readin-auth-client';
import { Navigate } from 'react-router-dom';

function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated, loading } = useAuth();

  if (loading) return <div>Loading...</div>;
  
  return isAuthenticated ? <>{children}</> : <Navigate to="/login" />;
}
```

## Environment Variables

```env
REACT_APP_API_URL=http://localhost:5003/api
# or for Next.js
NEXT_PUBLIC_API_URL=http://localhost:5003/api
```

## License

MIT © SNS Software