/** * Authentication and Authorization Service * * Provides secure user authentication, role-based access control, * and JWT token management for the admin dashboard and API. */ import { v4 as uuidv4 } from 'uuid'; import * as crypto from 'crypto'; import type { User, UserSession } from '@buzztrail/shared-database'; export interface LoginCredentials { email: string; password: string; } export interface AuthResult { token: string; user: { id: string; email: string; role: string; permissions: Permission[]; }; expires_at: string; } export interface Permission { resource: string; // 'conversations', 'customers', 'analytics', 'admin' actions: string[]; // 'read', 'write', 'delete', 'export' scope?: string; // 'own', 'customer', 'all' } export interface UserRole { id: string; name: string; permissions: Permission[]; } export interface JWTPayload { userId: string; email: string; role: string; customerId?: string; iat: number; exp: number; } export interface DatabaseManager { getUserByEmail(email: string): Promise; getUserById(id: string): Promise; createUserSession(session: Partial): Promise; updateUserSession(id: string, updates: Partial): Promise; getUserSession(id: string): Promise; deleteUserSession(id: string): Promise; updateUser(id: string, updates: Partial): Promise; getRolePermissions(role: string): Promise; hasCustomerAccess(userId: string, customerId: string): Promise; } /** * Authentication Service * * Handles user authentication, JWT tokens, and session management */ export class AuthenticationService { private db: DatabaseManager; private jwtSecret: string; private tokenExpiration: number = 24 * 60 * 60 * 1000; // 24 hours constructor(db: DatabaseManager, jwtSecret?: string) { this.db = db; this.jwtSecret = jwtSecret || process.env.JWT_SECRET || 'default-secret-change-in-production'; } /** * Authenticate user with email and password */ async authenticateUser(credentials: LoginCredentials): Promise { try { const user = await this.db.getUserByEmail(credentials.email); if (!user || !user.is_active) { throw new Error('Invalid credentials or account disabled'); } // Verify password const isValidPassword = await this.verifyPassword(credentials.password, user.password_hash); if (!isValidPassword) { throw new Error('Invalid credentials'); } // Generate JWT token const tokenPayload: JWTPayload = { userId: user.id, email: user.email, role: user.role, customerId: user.customer_id || undefined, iat: Math.floor(Date.now() / 1000), exp: Math.floor((Date.now() + this.tokenExpiration) / 1000) }; const token = this.generateJWT(tokenPayload); // Create session record await this.createUserSession(user.id, token); // Update last login time await this.db.updateUser(user.id, { last_login_at: new Date().toISOString() }); // Get user permissions const permissions = await this.getUserPermissions(user.role); return { token, user: { id: user.id, email: user.email, role: user.role, permissions }, expires_at: new Date(Date.now() + this.tokenExpiration).toISOString() }; } catch (error) { console.error('Authentication failed:', error); throw new Error(`Authentication failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Verify JWT token and return user info */ async verifyToken(token: string): Promise { try { const payload = this.verifyJWT(token); // Check if session is still active const session = await this.getUserSessionByToken(token); if (!session || !session.is_active) { return null; } // Update session last accessed time await this.db.updateUserSession(session.id, { last_accessed_at: new Date().toISOString() }); return payload; } catch (error) { console.error('Token verification failed:', error); return null; } } /** * Authorize action for user */ async authorizeAction( token: string, resource: string, action: string, targetCustomerId?: string ): Promise { try { const payload = await this.verifyToken(token); if (!payload) { return false; } const permissions = await this.getUserPermissions(payload.role); const permission = permissions.find(p => p.resource === resource || p.resource === '*'); if (!permission) { return false; } // Check if action is allowed if (!permission.actions.includes(action) && !permission.actions.includes('*')) { return false; } // Check scope-based access if (permission.scope === 'own' && targetCustomerId !== payload.customerId) { return false; } if (permission.scope === 'customer' && targetCustomerId) { const hasAccess = await this.db.hasCustomerAccess(payload.userId, targetCustomerId); if (!hasAccess) { return false; } } return true; } catch (error) { console.error('Authorization failed:', error); return false; } } /** * Logout user by invalidating session */ async logout(token: string): Promise { try { const session = await this.getUserSessionByToken(token); if (session) { await this.db.updateUserSession(session.id, { is_active: false }); } } catch (error) { console.error('Logout failed:', error); throw new Error('Failed to logout user'); } } /** * Refresh token for extended session */ async refreshToken(token: string): Promise { try { const payload = await this.verifyToken(token); if (!payload) { return null; } const user = await this.db.getUserById(payload.userId); if (!user || !user.is_active) { return null; } // Generate new token const newTokenPayload: JWTPayload = { ...payload, iat: Math.floor(Date.now() / 1000), exp: Math.floor((Date.now() + this.tokenExpiration) / 1000) }; const newToken = this.generateJWT(newTokenPayload); // Update session with new token const session = await this.getUserSessionByToken(token); if (session) { await this.db.updateUserSession(session.id, { token_hash: this.hashToken(newToken), expires_at: new Date(Date.now() + this.tokenExpiration).toISOString() }); } const permissions = await this.getUserPermissions(user.role); return { token: newToken, user: { id: user.id, email: user.email, role: user.role, permissions }, expires_at: new Date(Date.now() + this.tokenExpiration).toISOString() }; } catch (error) { console.error('Token refresh failed:', error); return null; } } /** * Get user permissions based on role */ private async getUserPermissions(role: string): Promise { try { return await this.db.getRolePermissions(role); } catch (error) { console.error('Failed to get user permissions:', error); // Return default permissions based on role return this.getDefaultPermissions(role); } } /** * Get default permissions for role */ private getDefaultPermissions(role: string): Permission[] { switch (role) { case 'admin': return [ { resource: '*', actions: ['*'], scope: 'all' } ]; case 'customer': return [ { resource: 'conversations', actions: ['read', 'write'], scope: 'own' }, { resource: 'analytics', actions: ['read'], scope: 'own' } ]; case 'viewer': return [ { resource: 'conversations', actions: ['read'], scope: 'customer' }, { resource: 'analytics', actions: ['read'], scope: 'customer' } ]; default: return []; } } /** * Hash password for storage */ async hashPassword(password: string): Promise { return new Promise((resolve, reject) => { const salt = crypto.randomBytes(16).toString('hex'); crypto.pbkdf2(password, salt, 10000, 64, 'sha512', (err, derivedKey) => { if (err) reject(err); resolve(salt + ':' + derivedKey.toString('hex')); }); }); } /** * Verify password against hash */ private async verifyPassword(password: string, hash: string): Promise { return new Promise((resolve, reject) => { const parts = hash.split(':'); const salt = parts[0]; const key = parts[1]; if (!salt || !key) { reject(new Error('Invalid password hash format')); return; } crypto.pbkdf2(password, salt, 10000, 64, 'sha512', (err, derivedKey) => { if (err) reject(err); resolve(key === derivedKey.toString('hex')); }); }); } /** * Generate JWT token */ private generateJWT(payload: JWTPayload): string { // Simple JWT implementation - in production use proper JWT library const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url'); const payloadStr = Buffer.from(JSON.stringify(payload)).toString('base64url'); const signature = crypto .createHmac('sha256', this.jwtSecret) .update(`${header}.${payloadStr}`) .digest('base64url'); return `${header}.${payloadStr}.${signature}`; } /** * Verify JWT token */ private verifyJWT(token: string): JWTPayload { const parts = token.split('.'); const header = parts[0]; const payload = parts[1]; const signature = parts[2]; if (!header || !payload || !signature) { throw new Error('Invalid token format'); } // Verify signature const expectedSignature = crypto .createHmac('sha256', this.jwtSecret) .update(`${header}.${payload}`) .digest('base64url'); if (signature !== expectedSignature) { throw new Error('Invalid token signature'); } // Decode payload const decodedPayload = JSON.parse(Buffer.from(payload, 'base64url').toString()); // Check expiration if (decodedPayload.exp < Math.floor(Date.now() / 1000)) { throw new Error('Token expired'); } return decodedPayload; } /** * Create user session */ private async createUserSession(userId: string, token: string): Promise { return await this.db.createUserSession({ id: uuidv4(), user_id: userId, token_hash: this.hashToken(token), created_at: new Date().toISOString(), expires_at: new Date(Date.now() + this.tokenExpiration).toISOString(), last_accessed_at: new Date().toISOString(), is_active: true }); } /** * Get user session by token */ private async getUserSessionByToken(_token: string): Promise { // This would typically query by token hash // For now, return null as placeholder return null; } /** * Hash token for session storage */ private hashToken(token: string): string { return crypto.createHash('sha256').update(token).digest('hex'); } } /** * Authorization Middleware Factory * * Creates middleware functions for protecting routes */ export class AuthorizationMiddleware { private authService: AuthenticationService; constructor(authService: AuthenticationService) { this.authService = authService; } /** * Require authentication middleware */ requireAuth() { return async (req: { headers?: { authorization?: string } }, res: { status: (code: number) => { json: (data: Record) => void } }, next: () => void) => { try { const token = this.extractToken(req); if (!token) { return res.status(401).json({ error: 'authentication_required', message: 'Valid authentication token is required' }); } const payload = await this.authService.verifyToken(token); if (!payload) { return res.status(401).json({ error: 'invalid_token', message: 'Invalid or expired authentication token' }); } // Add user info to request // eslint-disable-next-line require-atomic-updates req.user = payload; // eslint-disable-next-line require-atomic-updates req.authToken = token; next(); } catch (_error) { res.status(401).json({ error: 'authentication_failed', message: 'Authentication verification failed' }); } }; } /** * Require specific permission middleware */ requirePermission(resource: string, action: string) { return async (req: { authToken?: string; params?: Record; body?: Record; query?: Record }, res: { status: (code: number) => { json: (data: Record) => void } }, next: () => void) => { try { const token = req.authToken; if (!token) { return res.status(401).json({ error: 'authentication_required', message: 'Authentication required for this action' }); } const targetCustomerId = req.params.customerId || req.body.customer_id || req.query.customer_id; const authorized = await this.authService.authorizeAction(token, resource, action, targetCustomerId); if (!authorized) { return res.status(403).json({ error: 'insufficient_permissions', message: `Insufficient permissions for ${action} on ${resource}` }); } next(); } catch (_error) { res.status(403).json({ error: 'authorization_failed', message: 'Authorization check failed' }); } }; } /** * Require admin role middleware */ requireAdmin() { return async (req: { user?: { role?: string } }, res: { status: (code: number) => { json: (data: Record) => void } }, next: () => void) => { try { if (req.user?.role !== 'admin') { return res.status(403).json({ error: 'admin_required', message: 'Admin privileges required' }); } next(); } catch (_error) { res.status(403).json({ error: 'admin_check_failed', message: 'Admin privilege check failed' }); } }; } /** * Extract token from request */ private extractToken(req: { headers?: { authorization?: string; 'x-auth-token'?: string } }): string | null { // Check Authorization header const authHeader = req.headers.authorization; if (authHeader && authHeader.startsWith('Bearer ')) { return authHeader.substring(7); } // Check X-Auth-Token header const tokenHeader = req.headers['x-auth-token']; if (tokenHeader) { return tokenHeader; } return null; } } export default AuthenticationService;