42 lines
1.5 KiB
JavaScript
42 lines
1.5 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.CreateApiKeyCommand = void 0;
|
|
const Result_1 = require("../../../../shared/domain/Result");
|
|
const ApiKey_1 = require("../../domain/entities/ApiKey");
|
|
const crypto_1 = require("crypto");
|
|
class CreateApiKeyCommand {
|
|
constructor(apiKeyRepository, userRepository) {
|
|
this.apiKeyRepository = apiKeyRepository;
|
|
this.userRepository = userRepository;
|
|
}
|
|
async execute(request) {
|
|
const user = await this.userRepository.findById(request.userId);
|
|
if (!user) {
|
|
return (0, Result_1.Err)('User not found');
|
|
}
|
|
if (!request.name.trim()) {
|
|
return (0, Result_1.Err)('API key name is required');
|
|
}
|
|
const rawKey = `abe_${(0, crypto_1.randomBytes)(32).toString('hex')}`;
|
|
const keyHash = (0, crypto_1.createHash)('sha256').update(rawKey).digest('hex');
|
|
const keyPrefix = rawKey.substring(0, 12);
|
|
const apiKey = ApiKey_1.ApiKey.create({
|
|
userId: request.userId,
|
|
orgId: request.orgId,
|
|
name: request.name.trim(),
|
|
keyHash,
|
|
keyPrefix,
|
|
permissions: request.permissions ?? ['member'],
|
|
expiresAt: request.expiresAt,
|
|
});
|
|
await this.apiKeyRepository.save(apiKey);
|
|
return (0, Result_1.Ok)({
|
|
id: apiKey.id.toString(),
|
|
key: rawKey,
|
|
keyPrefix,
|
|
name: apiKey.name,
|
|
});
|
|
}
|
|
}
|
|
exports.CreateApiKeyCommand = CreateApiKeyCommand;
|