1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-11-01 19:07:38 +01:00
unleash.unleash/src/lib/services/public-signup-token-service.ts

152 lines
4.7 KiB
TypeScript
Raw Normal View History

PublicSignupTokens (#2053) * PublicSignupTokens * bug fix * bug fixes and test * bug fixes and test * bug fixes and test * Add feature flag * tests * tests * Update 20220908093515-add-public-signup-tokens.js Bug Fix * task: use swc instead of ts-jest (#2042) * Add a counter for total number of environments (#1964) * add groupId to gradual rollout template (#2045) * add groupId to gradual rollout template * FMT * Improve tabs UI on smaller devices (#2014) * Improve tabs UI on smaller devices * Improve tabs UI on smaller devices * bug fix * add proper scrollable tabs * removed centered from Tabs (conflicts with scrollable) * PR comments * 4.15.0-beta.10 * Fix broken doc links (#2046) ## What This PR fixes some broken links that have been hanging around in the docs for what seems like a very long time. ## Why As discovered by the link check in #1912, there are a fair few broken links in the docs. Everyone hates broken links because it makes it harder to understand what they were supposed to be pointing at. ## How There are 3 types of links that have been fixed: - Links that should have been internal but were absolute. E.g. `https://docs.getunleash.io/path/article` that should have been `./article.md` - External links that have changed, such as Slack's API description - GitHub links to files that either no longer exist or that have been moved. These links generally pointed to `master`/`main`, meaning they are subject to change. They have been replaced with permalinks pointing to specific commits. ----- * docs: fix slack api doc link * docs: update links in migration guide * docs: fix broken link to ancient feature schema validation * docs: update links to v3 auth hooks * docs: update broken link in the go sdk article * Fix: use permalink for GitHub link * docs: fix wrong google auth link * 4.15.0 * 4.15.1 * docs: update link for symfony sdk (#2048) The doc link appears to have pointed at an address that is no longer reachable. Instead, let's point to the equivalent GitHub link Relates to and closes #2047 * docs: test broken links in website (#1912) The action triggers manually as a first step to test this functionality. In the near future, we might schedule it * Schedule link checker action (#2050) Runs at 12:30 UTC on Mon, Tue, Wed, Thu and Fri * fix: add env and project labels to feature updated metrics. (#2043) * Revert workflow (#2051) * update snapshot * PR comments * Added Events and tests * Throw error if token not found Co-authored-by: Christopher Kolstad <chriswk@getunleash.ai> Co-authored-by: Thomas Heartman <thomas@getunleash.ai> Co-authored-by: Gastón Fournier <gaston@getunleash.ai> Co-authored-by: Ivar Conradi Østhus <ivarconr@gmail.com> Co-authored-by: sjaanus <sellinjaanus@gmail.com>
2022-09-14 14:29:12 +02:00
import crypto from 'crypto';
import { Logger } from '../logger';
import { IUnleashConfig, IUnleashStores } from '../types';
import { minutesToMilliseconds } from 'date-fns';
import { IPublicSignupTokenStore } from '../types/stores/public-signup-token-store';
import { PublicSignupTokenSchema } from '../openapi/spec/public-signup-token-schema';
import { IRoleStore } from '../types/stores/role-store';
import { IPublicSignupTokenCreate } from '../types/models/public-signup-token';
import { PublicSignupTokenCreateSchema } from '../openapi/spec/public-signup-token-create-schema';
import { RoleName } from '../types/model';
import { IEventStore } from '../types/stores/event-store';
import {
PublicSignupTokenCreatedEvent,
PublicSignupTokenManuallyExpiredEvent,
PublicSignupTokenUserAddedEvent,
} from '../types/events';
import UserService, { ICreateUser } from './user-service';
import { IUser } from '../types/user';
export class PublicSignupTokenService {
private store: IPublicSignupTokenStore;
private roleStore: IRoleStore;
private eventStore: IEventStore;
private userService: UserService;
private logger: Logger;
private timer: NodeJS.Timeout;
private activeTokens: PublicSignupTokenSchema[] = [];
constructor(
{
publicSignupTokenStore,
roleStore,
eventStore,
}: Pick<
IUnleashStores,
'publicSignupTokenStore' | 'roleStore' | 'eventStore'
>,
config: Pick<IUnleashConfig, 'getLogger' | 'authentication'>,
userService: UserService,
) {
this.store = publicSignupTokenStore;
this.userService = userService;
this.roleStore = roleStore;
this.eventStore = eventStore;
this.logger = config.getLogger(
'/services/public-signup-token-service.ts',
);
this.fetchActiveTokens();
this.timer = setInterval(
() => this.fetchActiveTokens(),
minutesToMilliseconds(1),
).unref();
}
async fetchActiveTokens(): Promise<void> {
this.activeTokens = await this.getAllActiveTokens();
}
public async get(secret: string): Promise<PublicSignupTokenSchema> {
return this.store.get(secret);
}
public async getAllTokens(): Promise<PublicSignupTokenSchema[]> {
return this.store.getAll();
}
public async getAllActiveTokens(): Promise<PublicSignupTokenSchema[]> {
return this.store.getAllActive();
}
public async validate(secret: string): Promise<boolean> {
return this.store.isValid(secret);
}
public async setExpiry(
secret: string,
expireAt: Date,
): Promise<PublicSignupTokenSchema> {
return this.store.setExpiry(secret, expireAt);
}
public async addTokenUser(
secret: string,
createUser: ICreateUser,
): Promise<IUser> {
const user = await this.userService.createUser(createUser);
await this.store.addTokenUser(secret, user.id);
await this.eventStore.store(
new PublicSignupTokenUserAddedEvent({
createdBy: 'userId',
data: { secret, userId: user.id },
}),
);
return user;
}
public async delete(secret: string, expiredBy: string): Promise<void> {
await this.expireToken(secret);
await this.eventStore.store(
new PublicSignupTokenManuallyExpiredEvent({
createdBy: expiredBy,
data: { secret },
}),
);
}
private async expireToken(
secret: string,
): Promise<PublicSignupTokenSchema> {
return this.store.setExpiry(secret, new Date());
}
public async createNewPublicSignupToken(
tokenCreate: PublicSignupTokenCreateSchema,
createdBy: string,
): Promise<PublicSignupTokenSchema> {
const viewerRole = await this.roleStore.getRoleByName(RoleName.VIEWER);
const newToken: IPublicSignupTokenCreate = {
name: tokenCreate.name,
expiresAt: new Date(tokenCreate.expiresAt),
secret: this.generateSecretKey(),
roleId: viewerRole ? viewerRole.id : -1,
createdBy: createdBy,
};
const token = await this.store.insert(newToken);
this.activeTokens.push(token);
await this.eventStore.store(
new PublicSignupTokenCreatedEvent({
createdBy: createdBy,
data: newToken,
}),
);
return token;
}
private generateSecretKey(): string {
return crypto.randomBytes(32).toString('hex');
}
destroy(): void {
clearInterval(this.timer);
this.timer = null;
}
}