unleash-server
Version:
Unleash is an enterprise ready feature flag service. It provides different strategies for handling feature flags.
54 lines • 2.25 kB
JavaScript
import { PatCreatedEvent, PatDeletedEvent, } from '../types/index.js';
import crypto from 'crypto';
import BadDataError from '../error/bad-data-error.js';
import NameExistsError from '../error/name-exists-error.js';
import { OperationDeniedError } from '../error/operation-denied-error.js';
import { PAT_LIMIT } from '../util/constants.js';
export default class PatService {
constructor({ patStore }, config, eventService) {
this.config = config;
this.logger = config.getLogger('services/pat-service.ts');
this.patStore = patStore;
this.eventService = eventService;
}
async createPat(pat, forUserId, auditUser) {
await this.validatePat(pat, forUserId);
const secret = this.generateSecretKey();
const newPat = await this.patStore.create(pat, secret, forUserId);
await this.eventService.storeEvent(new PatCreatedEvent({
data: { ...pat, secret: '***' },
auditUser,
}));
return { ...newPat, secret };
}
async getAll(userId) {
return this.patStore.getAllByUser(userId);
}
async deletePat(id, forUserId, auditUser) {
const pat = await this.patStore.get(id);
await this.eventService.storeEvent(new PatDeletedEvent({
data: { ...pat, secret: '***' },
auditUser,
}));
return this.patStore.deleteForUser(id, forUserId);
}
async validatePat({ description, expiresAt }, userId) {
if (!description) {
throw new BadDataError('PAT description cannot be empty.');
}
if (new Date(expiresAt) < new Date()) {
throw new BadDataError('The expiry date should be in future.');
}
if ((await this.patStore.countByUser(userId)) >= PAT_LIMIT) {
throw new OperationDeniedError(`Too many PATs (${PAT_LIMIT}) already exist for this user.`);
}
if (await this.patStore.existsWithDescriptionByUser(description, userId)) {
throw new NameExistsError('PAT description already exists.');
}
}
generateSecretKey() {
const randomStr = crypto.randomBytes(28).toString('hex');
return `user:${randomStr}`;
}
}
//# sourceMappingURL=pat-service.js.map