npm package: @rxbenefits/login
Description: RxBenefits authentication and login components
Author: RxBenefits
Latest version: 1.0.0

# @rxbenefits/login

> RxBenefits authentication and login components for React applications

[![npm version](https://img.shields.io/npm/v/@rxbenefits/login.svg)](https://www.npmjs.com/package/@rxbenefits/login)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Table of Contents

- [Overview](#overview)
- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Components](#components)
  - [LoginModule](#loginmodule)
  - [LoginPage](#loginpage)
- [Usage Examples](#usage-examples)
- [API Reference](#api-reference)
- [TypeScript Support](#typescript-support)
- [Testing](#testing)
- [Migration from Monorepo](#migration-from-monorepo)
- [Contributing](#contributing)
- [License](#license)

## Overview

The `@rxbenefits/login` library provides authentication and login functionality for RxBenefits applications. It integrates seamlessly with Auth0 for secure authentication and uses React Router v6 for routing.

This library is part of the RxBenefits component ecosystem and is designed to work with other `@rxbenefits/*` packages.

## Features

- 🔐 **Auth0 Integration**: Secure authentication using Auth0
- 🚀 **React Router v6**: Modern routing with React Router v6
- 📦 **Lightweight**: Minimal bundle size with zero unnecessary dependencies
- 🎯 **TypeScript**: Full TypeScript support with comprehensive type definitions
- 🧪 **Well-Tested**: Comprehensive test suite with 90%+ coverage
- 📱 **Responsive**: Works seamlessly across all devices
- ♿ **Accessible**: Built with accessibility best practices

## Installation

```bash
# Using npm
npm install @rxbenefits/login

# Using yarn
yarn add @rxbenefits/login

# Using pnpm
pnpm add @rxbenefits/login
```

### Peer Dependencies

This package requires the following peer dependencies:

```json
{
  "@auth0/auth0-react": "^2.0.0",
  "react": "^18.0.0",
  "react-dom": "^18.0.0",
  "react-router-dom": "^6.0.0"
}
```

Install peer dependencies:

```bash
npm install @auth0/auth0-react react react-dom react-router-dom
```

## Quick Start

### Basic Setup

```tsx
import { Auth0Provider } from '@auth0/auth0-react';
import { BrowserRouter } from 'react-router-dom';
import { LoginModule } from '@rxbenefits/login';

function App() {
  return (
    <Auth0Provider
      domain="your-domain.auth0.com"
      clientId="your-client-id"
      redirectUri={window.location.origin}
    >
      <BrowserRouter>
        <LoginModule basePath="/" applicationName="optimize" />
      </BrowserRouter>
    </Auth0Provider>
  );
}
```

### With Custom Routes

```tsx
import { Routes, Route } from 'react-router-dom';
import { LoginPage } from '@rxbenefits/login';

function App() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route path="/dashboard" element={<Dashboard />} />
    </Routes>
  );
}
```

## Components

### LoginModule

The `LoginModule` component provides a complete authentication module with routing.

#### Props

| Prop              | Type     | Required | Default      | Description                |
| ----------------- | -------- | -------- | ------------ | -------------------------- |
| `basePath`        | `string` | Yes      | -            | Base path for login routes |
| `applicationName` | `string` | No       | `'optimize'` | Name of the application    |

#### Example

```tsx
import { LoginModule } from '@rxbenefits/login';

function App() {
  return <LoginModule basePath="/app/" applicationName="optimize" />;
}
```

#### Routes

The `LoginModule` creates the following routes:

- `{basePath}` - Root login route
- `{basePath}login` - Explicit login route

Both routes render the `LoginPage` component.

### LoginPage

The `LoginPage` component handles the authentication flow by redirecting unauthenticated users to Auth0.

#### Props

This component accepts no props.

#### Behavior

- Automatically redirects unauthenticated users to Auth0 login
- Returns `null` (no visible UI) as it only handles redirect logic
- Works with Auth0's `useAuth0` hook

#### Example

```tsx
import { LoginPage } from '@rxbenefits/login';
import { Route } from 'react-router-dom';

function App() {
  return <Route path="/login" element={<LoginPage />} />;
}
```

## Usage Examples

### Example 1: Simple Application

```tsx
import { Auth0Provider } from '@auth0/auth0-react';
import { BrowserRouter } from 'react-router-dom';
import { LoginModule } from '@rxbenefits/login';

function App() {
  return (
    <Auth0Provider
      domain={process.env.REACT_APP_AUTH0_DOMAIN}
      clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
      redirectUri={window.location.origin}
    >
      <BrowserRouter>
        <LoginModule basePath="/" applicationName="optimize" />
      </BrowserRouter>
    </Auth0Provider>
  );
}

export default App;
```

### Example 2: With Protected Routes

```tsx
import { Auth0Provider, withAuthenticationRequired } from '@auth0/auth0-react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { LoginPage } from '@rxbenefits/login';

const ProtectedDashboard = withAuthenticationRequired(Dashboard);

function App() {
  return (
    <Auth0Provider
      domain={process.env.REACT_APP_AUTH0_DOMAIN}
      clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
      redirectUri={window.location.origin}
    >
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<LoginPage />} />
          <Route path="/dashboard" element={<ProtectedDashboard />} />
        </Routes>
      </BrowserRouter>
    </Auth0Provider>
  );
}

export default App;
```

### Example 3: With Custom Base Path

```tsx
import { LoginModule } from '@rxbenefits/login';
import { BrowserRouter } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      {/* LoginModule handles routes under /app/auth/ */}
      <LoginModule basePath="/app/auth/" applicationName="keystone" />
    </BrowserRouter>
  );
}
```

### Example 4: Nested in Application Routes

```tsx
import { Routes, Route } from 'react-router-dom';
import { LoginModule } from '@rxbenefits/login';

function App() {
  return (
    <Routes>
      <Route path="/public/*" element={<PublicPages />} />
      <Route
        path="/auth/*"
        element={<LoginModule basePath="/auth/" applicationName="optimize" />}
      />
      <Route path="/app/*" element={<ProtectedApp />} />
    </Routes>
  );
}
```

## API Reference

### Types

```typescript
import { Application, ModuleDefinition } from '@rxbenefits/types';

interface LoginModuleProps extends ModuleDefinition, Application {
  basePath: string;
  applicationName?: string;
}
```

### Exports

```typescript
// Components
export { LoginModule } from './lib/LoginModule';
export { LoginPage } from './lib/Components/LoginPage';
```

## TypeScript Support

This library is written in TypeScript and provides comprehensive type definitions.

### Example with Types

```tsx
import { FC } from 'react';
import { LoginModule } from '@rxbenefits/login';
import { Application, ModuleDefinition } from '@rxbenefits/types';

interface AppProps {
  config: ModuleDefinition & Application;
}

const App: FC<AppProps> = ({ config }) => {
  return <LoginModule basePath={config.basePath} applicationName={config.applicationName} />;
};
```

### Type Imports

```typescript
import type { Application, ModuleDefinition } from '@rxbenefits/types';
```

## Testing

### Running Tests

```bash
# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage
```

### Test Coverage

The library maintains a minimum of 70% test coverage across all files.

```bash
# Generate coverage report
npm run test:coverage
```

### Example Test

```tsx
import { render, waitFor } from '@testing-library/react';
import { useAuth0 } from '@auth0/auth0-react';
import { LoginPage } from '@rxbenefits/login';

jest.mock('@auth0/auth0-react');

describe('LoginPage', () => {
  it('should redirect unauthenticated users', async () => {
    const mockLoginWithRedirect = jest.fn();
    (useAuth0 as jest.Mock).mockReturnValue({
      isAuthenticated: false,
      loginWithRedirect: mockLoginWithRedirect,
    });

    render(<LoginPage />);

    await waitFor(() => {
      expect(mockLoginWithRedirect).toHaveBeenCalled();
    });
  });
});
```

## Migration from Monorepo

This library was migrated from the RxBenefits Optimize.UI monorepo. If you're migrating from the monorepo version:

### Import Changes

**Before (Monorepo):**

```typescript
import { LoginModule } from '@optimize/login';
```

**After (Published Package):**

```typescript
import { LoginModule } from '@rxbenefits/login';
```

### Breaking Changes

1. **React Router v6**: Migrated from React Router v5 to v6
   - `Switch` → `Routes`
   - `<Route exact path="...">` → `<Route path="..." element={...}>`
2. **TypeScript Types**: Now imports from `@rxbenefits/types`
   ```typescript
   // Old: import { Application } from '@optimize/types';
   // New: import { Application } from '@rxbenefits/types';
   ```

### Migration Guide

1. Update imports from `@optimize/login` to `@rxbenefits/login`
2. Update React Router usage if you're using the components directly
3. Update type imports to use `@rxbenefits/types`
4. Install peer dependencies if not already present

## Development

### Building

```bash
# Build the library
npm run build

# Build in watch mode
npm run build:watch

# Clean build artifacts
npm run clean
```

### Code Quality

```bash
# Type checking
npm run typecheck

# Linting
npm run lint
npm run lint:fix

# Formatting
npm run format
npm run format:check

# Run all validations
npm run validate
```

### Project Structure

```
@rxbenefits/login/
├── src/
│   ├── index.ts              # Main entry point
│   └── lib/
│       ├── LoginModule.tsx   # Login module with routing
│       └── Components/
│           ├── index.ts
│           └── LoginPage.tsx # Login page component
├── __tests__/
│   ├── LoginPage.test.tsx
│   ├── LoginModule.test.tsx
│   └── index.test.ts
├── dist/                     # Build output (generated)
├── package.json
├── tsconfig.json
├── jest.config.js
└── README.md
```

## Browser Support

This library supports all modern browsers:

- Chrome (last 2 versions)
- Firefox (last 2 versions)
- Safari (last 2 versions)
- Edge (last 2 versions)

## Performance

- **Bundle Size**: ~2 KB (minified + gzipped)
- **Dependencies**: Minimal external dependencies
- **Tree-Shakeable**: Full ES module support for optimal tree-shaking

## Security

For security concerns, please see our [SECURITY.md](./SECURITY.md) file.

## Contributing

We welcome contributions! Please see our contributing guidelines for more details.

### Development Setup

1. Clone the repository
2. Install dependencies: `npm install`
3. Run tests: `npm test`
4. Build: `npm run build`

## Related Packages

- [`@rxbenefits/types`](https://github.com/rxbenefits/types) - TypeScript type definitions
- [`@rxbenefits/ui`](https://github.com/rxbenefits/ui) - UI component library
- [`@rxbenefits/components`](https://github.com/rxbenefits/components) - Shared React components

## Changelog

See [CHANGELOG.md](./CHANGELOG.md) for a detailed list of changes.

## License

MIT © RxBenefits

---

**Made with ❤️ by the RxBenefits Team**