npm package: @linhnv1902/appcore-auth
Description: Reusable authentication library for AppCore projects
Author: AppCore Team
Latest version: 1.0.35

# @linhnv1902/appcore-auth

[![npm version](https://badge.fury.io/js/%40linhnv1902%2Fappcore-auth.svg)](https://badge.fury.io/js/%40linhnv1902%2Fappcore-auth)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Reusable TypeScript authentication library for AppCore projects supporting Firebase and Shopify OAuth.

## Features

- 🔐 **Firebase Authentication** - Custom tokens and JWT verification
- 🛍️ **Shopify OAuth** - Complete OAuth flow for Shopify apps
- 🎯 **Koa.js Middleware** - Ready-to-use middleware for Node.js
- 📱 **Frontend Helpers** - React/JS authentication utilities
- 🔄 **TypeScript Support** - Full type safety and IntelliSense
- 🚀 **Reusable** - Works across multiple projects

## Installation

```bash
npm install @linhnv1902/appcore-auth
```

## Quick Start

### Backend (Node.js + Koa)

```typescript
import { firebaseAuth, shopifyAuth } from '@linhnv1902/appcore-auth';

// Firebase authentication middleware
app.use(firebaseAuth({
  onAuthSuccess: (ctx, user) => {
    console.log('User authenticated:', user.shopID);
  }
}));

// Shopify OAuth router
const authRouter = shopifyAuth({
  apiKey: 'your-shopify-api-key',
  secret: 'your-shopify-secret',
  scopes: ['read_products', 'write_products'],
  hostName: 'https://your-app.com',
  firebaseApiKey: 'your-firebase-api-key',
  isEmbeddedApp: true
}, shopRepository);

app.use(authRouter.routes());
```

### Frontend (React/JS)

```typescript
import { initializeFirebase, createApiClient, createAuthStateHandler } from '@linhnv1902/appcore-auth';

// Initialize Firebase
const { auth, db } = initializeFirebase({
  appId: 'your-app-id',
  apiKey: 'your-api-key',
  authDomain: 'your-domain',
  projectId: 'your-project-id',
  storageBucket: 'your-bucket'
});

// Create API client
const api = createApiClient({
  auth,
  baseURL: '/api',
  isEmbeddedApp: () => window.location.pathname.includes('/embed')
});

// Handle authentication state
const handleAuthState = createAuthStateHandler({
  auth,
  api,
  onAuthSuccess: (user, activeShop) => {
    console.log('User logged in:', user.uid);
    console.log('Active shop:', activeShop);
  },
  onAuthError: (error) => {
    console.error('Auth error:', error);
  }
});

auth.onAuthStateChanged(handleAuthState);
```

## API Reference

### Backend APIs

#### `firebaseAuth(options?)`

Firebase authentication middleware for Koa.js.

```typescript
interface FirebaseAuthOptions {
  tokenHeader?: string;                    // Token header name (default: 'x-auth-token')
  onAuthSuccess?: (ctx: Context, user: UserContext) => void;
  onAuthError?: (ctx: Context, error: Error) => void;
}
```

#### `shopifyAuth(options, shopRepository)`

Creates Shopify OAuth router for Koa.js.

```typescript
interface ShopifyAuthOptions extends AuthConfig {
  validateShop?: () => Middleware;
  validateNonce?: () => Middleware;
  validateHmac?: (options: AuthConfig) => Middleware;
}
```

#### `handleInstall(params, shopRepository, accessTokenKey?)`

Handles new app installation.

```typescript
interface InstallParams {
  shop: string;
  code: string;
  apiKey: string;
  secret: string;
}
```

#### `handleLogin(params, accessTokenKey?)`

Handles existing shop login.

```typescript
interface LoginParams {
  shop: ShopData;
}
```

### Frontend APIs

#### `initializeFirebase(config)`

Initializes Firebase app and returns auth and database instances.

```typescript
interface FirebaseConfig {
  appId: string;
  apiKey: string;
  authDomain: string;
  measurementId?: string;
  projectId: string;
  storageBucket: string;
}
```

#### `createApiClient(options)`

Creates authenticated API client function.

```typescript
interface ApiClientOptions {
  auth: Auth;
  baseURL?: string;
  timeout?: number;
  isEmbeddedApp?: () => boolean;
  authenticatedFetch?: (url: string, options: any) => Promise<Response>;
}
```

#### `createAuthStateHandler(options)`

Creates authentication state change handler.

```typescript
interface AuthStateHandlerOptions {
  auth: Auth;
  api: (uri: string, options?: any) => Promise<any>;
  onAuthStateChange?: (user: any) => Promise<void> | void;
  onAuthSuccess?: (user: any, activeShop: any) => Promise<void> | void;
  onAuthError?: (error: Error) => void;
}
```

## TypeScript Support

This library is written in TypeScript and provides full type definitions:

```typescript
import type { 
  AuthConfig, 
  UserContext, 
  ShopData, 
  AuthResult 
} from '@linhnv1902/appcore-auth';
```

## Examples

### Complete Shopify App Setup

```typescript
// Backend setup
import { shopifyAuth } from '@linhnv1902/appcore-auth';

const authRouter = shopifyAuth({
  apiKey: process.env.SHOPIFY_API_KEY!,
  secret: process.env.SHOPIFY_API_SECRET!,
  scopes: ['read_products', 'write_products'],
  hostName: process.env.APP_URL!,
  firebaseApiKey: process.env.FIREBASE_API_KEY!,
  isEmbeddedApp: true,
  successRedirect: '/dashboard',
  failureRedirect: '/auth/error'
}, shopRepository);

app.use(authRouter.routes());

// Frontend setup
import { initializeFirebase, createAuthStateHandler } from '@linhnv1902/appcore-auth';

const { auth } = initializeFirebase({
  appId: process.env.VITE_FIREBASE_APP_ID!,
  apiKey: process.env.VITE_FIREBASE_API_KEY!,
  authDomain: process.env.VITE_FIREBASE_AUTH_DOMAIN!,
  projectId: process.env.VITE_FIREBASE_PROJECT_ID!,
  storageBucket: process.env.VITE_FIREBASE_STORAGE_BUCKET!
});

const handleAuthState = createAuthStateHandler({
  auth,
  api: createApiClient({ auth, baseURL: '/api' }),
  onAuthSuccess: (user, activeShop) => {
    // Initialize app with user data
    initializeApp(user, activeShop);
  },
  onAuthError: (error) => {
    // Handle authentication errors
    showErrorNotification(error.message);
  }
});

auth.onAuthStateChanged(handleAuthState);
```

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Repository

- **GitHub**: [https://github.com/nguyenvanlinh1902/appCore.git](https://github.com/nguyenvanlinh1902/appCore.git)
- **NPM**: [https://www.npmjs.com/package/@linhnv1902/appcore-auth](https://www.npmjs.com/package/@linhnv1902/appcore-auth)

## Support

If you have any questions or need help, please open an issue on GitHub.