Files
maps-saas/apps/api/dist/auth/auth.service.js
T

180 lines
8.5 KiB
JavaScript

"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 AuthService_1;
var _a, _b;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const crypto_1 = require("crypto");
const api_key_entity_1 = require("./entities/api-key.entity");
const tenant_entity_1 = require("./entities/tenant.entity");
const redis_service_1 = require("../common/redis.service");
let AuthService = AuthService_1 = class AuthService {
apiKeyRepository;
tenantRepository;
redisService;
logger = new common_1.Logger(AuthService_1.name);
constructor(apiKeyRepository, tenantRepository, redisService) {
this.apiKeyRepository = apiKeyRepository;
this.tenantRepository = tenantRepository;
this.redisService = redisService;
}
async validateApiKey(key, origin, referer) {
const cacheKey = `auth:apikey:${key}`;
const cachedData = await this.redisService.get(cacheKey);
if (cachedData) {
this.validateRestrictions(cachedData.apiKey, origin, referer);
return cachedData;
}
const apiKey = await this.apiKeyRepository.findOne({
where: { key, isActive: true },
relations: ['tenant'],
});
if (!apiKey || !apiKey.tenant || !apiKey.tenant.isActive) {
throw new common_1.UnauthorizedException('Invalid or inactive API Key');
}
this.validateRestrictions(apiKey, origin, referer);
const result = {
tenant: apiKey.tenant,
apiKey: apiKey,
rateLimit: apiKey.rateLimit || tenant_entity_1.RATE_LIMITS[apiKey.tenant.plan] || 100,
};
await this.redisService.set(cacheKey, result, 3600);
this.apiKeyRepository.update(apiKey.id, { lastUsedAt: new Date() }).catch(err => this.logger.error(`Failed to update lastUsedAt for API key ${apiKey.id}: ${err.message}`));
return result;
}
validateRestrictions(apiKey, origin, referer) {
if (apiKey.allowedOrigins && apiKey.allowedOrigins.length > 0) {
if (!origin || !this.isDomainAllowed(origin, apiKey.allowedOrigins)) {
this.logger.warn(`Origin mismatch for API key ${apiKey.id}. Received: ${origin}`);
throw new common_1.UnauthorizedException('Request Origin not allowed for this API Key');
}
}
if (apiKey.allowedReferrers && apiKey.allowedReferrers.length > 0) {
if (!referer || !this.isDomainAllowed(referer, apiKey.allowedReferrers)) {
this.logger.warn(`Referer mismatch for API key ${apiKey.id}. Received: ${referer}`);
throw new common_1.UnauthorizedException('Request Referer not allowed for this API Key');
}
}
}
isDomainAllowed(domain, allowedList) {
const cleanDomain = domain.replace(/^https?:\/\//, '').split('/')[0];
return allowedList.some(allowed => {
if (allowed === '*')
return true;
const regex = new RegExp('^' + allowed.replace(/\*/g, '.*') + '$');
return regex.test(cleanDomain);
});
}
hashSecret(secret) {
return (0, crypto_1.createHash)('sha256').update(secret).digest('hex');
}
async seedDefaultKey(name, email, keyString) {
let tenant = await this.tenantRepository.findOne({ where: { email } });
if (!tenant) {
tenant = await this.tenantRepository.save({
name,
email,
isActive: true,
plan: tenant_entity_1.TenantPlan.ENTERPRISE,
});
}
const existingKey = await this.apiKeyRepository.findOne({ where: { key: keyString } });
if (!existingKey) {
await this.apiKeyRepository.save({
key: keyString,
secretHash: this.hashSecret(keyString),
name: 'Default Production Key',
isActive: true,
tenantId: tenant.id,
rateLimit: 1000
});
}
}
async getApiKeys(tenantId) {
return this.apiKeyRepository.find({
where: { tenantId },
order: { createdAt: 'DESC' }
});
}
async createApiKey(tenantId, name, rateLimit, allowedOrigins) {
const existingKeysCount = await this.apiKeyRepository.count({ where: { tenantId } });
if (existingKeysCount >= 1) {
throw new common_1.ConflictException('Limit reached: Only 1 API key allowed per developer currently.');
}
const key = `in_${(0, crypto_1.createHash)('md5').update(Math.random().toString()).digest('hex').substring(0, 24)}`;
const apiKey = this.apiKeyRepository.create({
key,
secretHash: this.hashSecret(key),
name,
tenantId,
rateLimit: rateLimit || 100,
allowedOrigins: allowedOrigins || [],
isActive: true
});
return this.apiKeyRepository.save(apiKey);
}
async getDefaultTenant() {
const tenant = await this.tenantRepository.findOne({ where: {} });
if (!tenant)
throw new common_1.NotFoundException('No tenants found in system');
return tenant;
}
async findOrCreateByFirebaseUid(uid, email, name, photoUrl) {
let tenant = await this.tenantRepository.findOne({ where: { firebaseUid: uid } });
if (!tenant) {
tenant = await this.tenantRepository.findOne({ where: { email } });
if (tenant) {
this.logger.log(`Linking existing tenant ${email} to Firebase UID: ${uid}`);
tenant.firebaseUid = uid;
if (photoUrl)
tenant.photoUrl = photoUrl;
tenant = await this.tenantRepository.save(tenant);
}
else {
this.logger.log(`Creating new tenant for Firebase user: ${email} (${uid})`);
const isAdmin = email === 'hamzaaleghwairyeen@gmail.com' || email === 'hamzadoctor@gmail.com' || email === 'hamzaayedpython@gmail.com';
tenant = await this.tenantRepository.save({
firebaseUid: uid,
email,
name,
photoUrl,
plan: isAdmin ? tenant_entity_1.TenantPlan.ENTERPRISE : tenant_entity_1.TenantPlan.FREE,
isActive: true,
});
}
}
else {
const isAdmin = email === 'hamzaaleghwairyeen@gmail.com' || email === 'hamzadoctor@gmail.com' || email === 'hamzaayedpython@gmail.com';
if (isAdmin && tenant.plan !== tenant_entity_1.TenantPlan.ENTERPRISE) {
tenant.plan = tenant_entity_1.TenantPlan.ENTERPRISE;
await this.tenantRepository.save(tenant);
}
if (tenant.photoUrl !== photoUrl || tenant.name !== name) {
await this.tenantRepository.update(tenant.id, { photoUrl, name });
}
}
return tenant;
}
};
exports.AuthService = AuthService;
exports.AuthService = AuthService = AuthService_1 = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, typeorm_1.InjectRepository)(api_key_entity_1.ApiKey)),
__param(1, (0, typeorm_1.InjectRepository)(tenant_entity_1.Tenant)),
__metadata("design:paramtypes", [typeof (_a = typeof typeorm_2.Repository !== "undefined" && typeorm_2.Repository) === "function" ? _a : Object, typeof (_b = typeof typeorm_2.Repository !== "undefined" && typeorm_2.Repository) === "function" ? _b : Object, redis_service_1.RedisService])
], AuthService);
//# sourceMappingURL=auth.service.js.map