unleash-server
Version:
Unleash is an enterprise ready feature flag service. It provides different strategies for handling feature flags.
83 lines • 3.25 kB
JavaScript
import crypto from 'node:crypto';
import { SYSTEM_USER_AUDIT, } from '../types/index.js';
import { RoleName } from '../types/model.js';
import { PublicSignupTokenCreatedEvent, PublicSignupTokenUpdatedEvent, PublicSignupTokenUserAddedEvent, } from '../types/index.js';
import { URL } from 'url';
import { add } from 'date-fns';
import { NotFoundError } from '../error/index.js';
export class PublicSignupTokenService {
constructor({ publicSignupTokenStore, roleStore, }, config, userService, eventService) {
this.store = publicSignupTokenStore;
this.userService = userService;
this.eventService = eventService;
this.roleStore = roleStore;
this.unleashBase = config.server.unleashUrl;
}
getUrl(secret) {
return new URL(`${this.unleashBase}/new-user?invite=${secret}`).toString();
}
async get(secret) {
const token = await this.store.get(secret);
if (token === undefined) {
throw new NotFoundError('Could not find token with that secret');
}
return token;
}
async getAllTokens() {
return this.store.getAll();
}
async validate(secret) {
return this.store.isValid(secret);
}
async update(secret, { expiresAt, enabled }, auditUser) {
const result = await this.store.update(secret, { expiresAt, enabled });
await this.eventService.storeEvent(new PublicSignupTokenUpdatedEvent({
auditUser,
data: { secret, enabled, expiresAt },
}));
return result;
}
async addTokenUser(secret, createUser, auditUser) {
const token = await this.get(secret);
if (token === undefined) {
throw new NotFoundError('Could not find token with that secret');
}
const user = await this.userService.createUser({
...createUser,
rootRole: token.role.id,
}, auditUser);
await this.store.addTokenUser(secret, user.id);
await this.eventService.storeEvent(new PublicSignupTokenUserAddedEvent({
auditUser: SYSTEM_USER_AUDIT,
data: { secret, userId: user.id },
}));
return user;
}
async createNewPublicSignupToken(tokenCreate, auditUser) {
const viewerRole = await this.roleStore.getRoleByName(RoleName.VIEWER);
const secret = this.generateSecretKey();
const url = this.getUrl(secret);
const cappedDate = this.getMinimumDate(new Date(tokenCreate.expiresAt), add(new Date(), { months: 1 }));
const newToken = {
name: tokenCreate.name,
expiresAt: cappedDate,
secret: secret,
roleId: viewerRole ? viewerRole.id : -1,
createdBy: auditUser.username,
url: url,
};
const token = await this.store.insert(newToken);
await this.eventService.storeEvent(new PublicSignupTokenCreatedEvent({
auditUser,
data: token,
}));
return token;
}
generateSecretKey() {
return crypto.randomBytes(16).toString('hex');
}
getMinimumDate(date1, date2) {
return date1 < date2 ? date1 : date2;
}
}
//# sourceMappingURL=public-signup-token-service.js.map