smackza-auth-core
v1.2.0
Published
Shared authentication utilities for Smackza services
Downloads
8
Maintainers
Readme
@smackza/auth-core
Shared authentication utilities for Smackza services, providing multi-tenant Firebase authentication, role-based access control, and header processing utilities.
Features
- 🔥 Multi-tenant Firebase: Support for both admin and tenant-specific Firebase configurations
- 🛡️ Role-based Access Control: Comprehensive RBAC with predefined roles and permissions
- 🔧 Header Processing: Utilities for extracting and building authentication headers
- ⚡ Fastify Integration: Ready-to-use middleware for Fastify applications
- 📝 TypeScript: Full TypeScript support with comprehensive type definitions
- 🧪 Validated: Zod schemas for request validation
Installation
npm install @smackza/auth-coreQuick Start
Basic Fastify Integration
import { createFirebaseAuth, extractAuthHeaders, UserRole } from '@smackza/auth-core';
// Create Firebase auth decorator
const firebaseAuth = createFirebaseAuth({
enableLogging: true,
getRestaurantFirebaseConfig: async (restaurantId) => {
// Your logic to get restaurant-specific Firebase config
return await getConfigFromDatabase(restaurantId);
}
});
// Use in route
app.register(async function (fastify) {
fastify.get('/protected', {
preHandler: firebaseAuth()
}, async (request, reply) => {
return { user: request.users };
});
});Header Processing
import { extractAuthHeaders, buildAdapterHeaders } from '@smackza/auth-core';
// Extract auth headers from request
const { authToken, loginSource } = extractAuthHeaders(req.headers);
// Build headers for API calls
const headers = buildAdapterHeaders(authToken, loginSource);Role-based Access Control
import { requireRole, UserRole } from '@smackza/auth-core';
// Protect route with role requirement
const handler = requireRole([UserRole.RestaurantOwner], async (req, reply) => {
return { message: 'Only restaurant owners can access this' };
});API Reference
Authentication
extractAuthHeaders(headers)
Extract authentication headers from request headers.
buildAdapterHeaders(authToken?, loginSource?)
Build headers for adapter service calls.
requireRole(allowedRoles, handler)
Create role-protected route handler.
Firebase
MultiTenantFirebase.initializeForRequest(config, getConfig?)
Initialize Firebase for a specific request context.
verifyFirebaseToken(admin, token, restaurantId?)
Verify Firebase ID token and extract user claims.
Types
import {
UserRole,
UserInfo,
AuthHeaders,
AuthContext,
RouteConfig
} from '@smackza/auth-core';User Roles
SuperAdmin: Full system accessRestaurantOwner: Restaurant ownership accessRestaurantManager: Restaurant management accessRestaurantUser: Restaurant staff accessRestaurantEmployee: Restaurant employee accessCustomer: Customer accessSameUser: Self-access authorization
Configuration
Multi-tenant Firebase
The package supports both admin and tenant-specific Firebase configurations:
const config = {
restaurantId: 'uuid-here',
loginSource: 'mobile', // or 'web'
isAdminContext: false
};
const admin = await MultiTenantFirebase.initializeForRequest(
config,
getRestaurantFirebaseConfig
);Public Routes
Define routes that bypass authentication:
const publicRoutes = [
{ type: 'exact', value: '/health', description: 'Health check' },
{ type: 'prefix', value: '/docs', description: 'Documentation' },
{ type: 'pattern', value: /^\/api\/v1\/auth/, description: 'Auth endpoints' }
];Error Handling
The package provides comprehensive error handling:
import { UnauthorizedError, ForbiddenError, getFirebaseErrorMessage } from '@smackza/auth-core';
try {
await verifyFirebaseToken(admin, token);
} catch (error) {
const message = getFirebaseErrorMessage(error);
reply.status(401).send({ error: message });
}Migration from Existing Code
From Yum
// Before
import { FirebaseAuth } from '@api/decorators/firebase-auth';
import { extractAuthHeaders } from '@api/utils/auth';
// After
import { createFirebaseAuth, extractAuthHeaders } from '@smackza/auth-core';From Yum-Clover-Adapter
// Before
import { verifyToken, UserRole } from '../auth/utils';
// After
import { verifyFirebaseToken, UserRole } from '@smackza/auth-core';License
MIT
