@linhnv1902/appcore-auth
v1.0.35
Published
Reusable authentication library for AppCore projects
Maintainers
Readme
@linhnv1902/appcore-auth
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
npm install @linhnv1902/appcore-authQuick Start
Backend (Node.js + Koa)
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)
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.
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.
interface ShopifyAuthOptions extends AuthConfig {
validateShop?: () => Middleware;
validateNonce?: () => Middleware;
validateHmac?: (options: AuthConfig) => Middleware;
}handleInstall(params, shopRepository, accessTokenKey?)
Handles new app installation.
interface InstallParams {
shop: string;
code: string;
apiKey: string;
secret: string;
}handleLogin(params, accessTokenKey?)
Handles existing shop login.
interface LoginParams {
shop: ShopData;
}Frontend APIs
initializeFirebase(config)
Initializes Firebase app and returns auth and database instances.
interface FirebaseConfig {
appId: string;
apiKey: string;
authDomain: string;
measurementId?: string;
projectId: string;
storageBucket: string;
}createApiClient(options)
Creates authenticated API client function.
interface ApiClientOptions {
auth: Auth;
baseURL?: string;
timeout?: number;
isEmbeddedApp?: () => boolean;
authenticatedFetch?: (url: string, options: any) => Promise<Response>;
}createAuthStateHandler(options)
Creates authentication state change handler.
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:
import type {
AuthConfig,
UserContext,
ShopData,
AuthResult
} from '@linhnv1902/appcore-auth';Examples
Complete Shopify App Setup
// 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
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Repository
- GitHub: https://github.com/nguyenvanlinh1902/appCore.git
- NPM: https://www.npmjs.com/package/@linhnv1902/appcore-auth
Support
If you have any questions or need help, please open an issue on GitHub.
