UNPKG

bb-inspired

Version:

Core library for BB-inspired NestJS backend

136 lines 5.98 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var ExternalAuthService_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.ExternalAuthService = void 0; const common_1 = require("@nestjs/common"); const axios_1 = require("axios"); const cache_service_1 = require("../../cache/cache.service"); const logger_1 = require("../../../utils/logger"); let ExternalAuthService = ExternalAuthService_1 = class ExternalAuthService { constructor(options, cacheService) { var _a, _b; this.options = options; this.cacheService = cacheService; this.logger = new logger_1.AppLogger(ExternalAuthService_1.name); this.httpClient = axios_1.default.create({ baseURL: options.baseUrl, timeout: options.timeout || 5000, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', ...(options.apiKey ? { 'X-API-Key': options.apiKey } : {}), }, }); this.cacheEnabled = ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.enabled) || false; this.cacheTtl = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.ttl) || 300; this.logger.log(`External auth service initialized with URL: ${options.baseUrl}`); } async authenticate(credentials) { try { const response = await this.httpClient.post(this.options.endpoints.validate, credentials); return response.data; } catch (error) { this.handleRequestError(error, 'Authentication failed'); } } async validateToken(token) { var _a; const cacheKey = `auth:token:${token}`; if (this.cacheEnabled) { const cached = await this.cacheService.get(cacheKey); if (cached) { return cached; } } try { const response = await this.httpClient.post(this.options.endpoints.verify, { token }, { headers: { Authorization: `Bearer ${token}`, }, }); const result = response.data; if (this.cacheEnabled && result.isValid) { await this.cacheService.set(cacheKey, result, { ttl: this.cacheTtl }); } return result; } catch (error) { if (error.response && error.response.status === 401) { return { isValid: false, error: ((_a = error.response.data) === null || _a === void 0 ? void 0 : _a.message) || 'Token validation failed', }; } this.handleRequestError(error, 'Token validation failed'); return { isValid: false, error: 'Error connecting to authentication service', }; } } async refreshToken(refreshToken) { try { const response = await this.httpClient.post(this.options.endpoints.refresh, { refreshToken }); if (this.cacheEnabled) { await this.cacheService.invalidateByTag('auth:tokens'); } return response.data; } catch (error) { this.handleRequestError(error, 'Token refresh failed'); } } async logout(token, userId) { if (!this.options.endpoints.logout) { return true; } try { const response = await this.httpClient.post(this.options.endpoints.logout, { userId }, { headers: { Authorization: `Bearer ${token}`, }, }); if (this.cacheEnabled) { const cacheKey = `auth:token:${token}`; await this.cacheService.delete(cacheKey); } return response.status === 200; } catch (error) { this.logger.error(`Logout failed: ${error.message}`, error.stack); return false; } } handleRequestError(error, defaultMessage) { var _a, _b, _c; const status = ((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) || 500; const message = ((_c = (_b = error.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.message) || error.message || defaultMessage; this.logger.error(`External auth service error (${status}): ${message}`, error.stack); throw new common_1.HttpException({ statusCode: status, message, error: 'Authentication Error', }, status); } }; exports.ExternalAuthService = ExternalAuthService; exports.ExternalAuthService = ExternalAuthService = ExternalAuthService_1 = __decorate([ (0, common_1.Injectable)(), __param(0, (0, common_1.Inject)('EXTERNAL_AUTH_OPTIONS')), __param(1, (0, common_1.Inject)('CACHE_SERVICE')), __metadata("design:paramtypes", [Object, cache_service_1.CacheService]) ], ExternalAuthService); //# sourceMappingURL=external-auth.service.js.map