UNPKG

@optimizely-opal/opal-tools-sdk

Version:

SDK for creating Opal-compatible tools services

53 lines (44 loc) 1.45 kB
/** * Middleware to handle authentication requirements * @param req Express request * @param res Express response * @param next Express next function */ export function authMiddleware(req: any, res: any, next: any) { const authHeader = req.headers.authorization; if (!authHeader && req.authRequired) { return res.status(401).json({ error: 'Authentication required' }); } // The Tools Management Service will provide the appropriate token // in the Authorization header next(); } interface AuthOptions { provider: string; scopeBundle: string; required?: boolean; } /** * Decorator to indicate that a tool requires authentication * @param options Authentication options */ export function requiresAuth(options: AuthOptions) { return function(target: any, propertyKey?: string, descriptor?: PropertyDescriptor) { const isMethod = propertyKey && descriptor; if (isMethod && descriptor) { const originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { // Store auth requirements in function metadata const fn = originalMethod as any; fn.__authRequirements__ = { provider: options.provider, scopeBundle: options.scopeBundle, required: options.required ?? true }; return originalMethod.apply(this, args); }; return descriptor; } return target; }; }