Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
♻️ Update approved subnet, session, webhook modules
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Jan 9, 2021
1 parent a96f824 commit 0d02e65
Show file tree
Hide file tree
Showing 6 changed files with 90 additions and 52 deletions.
7 changes: 5 additions & 2 deletions src/modules/approved-subnets/approved-subnets.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { ApprovedSubnetsService } from './approved-subnets.service';
export class ApprovedSubnetController {
constructor(private approvedSubnetsService: ApprovedSubnetsService) {}

/** Get approved subnets for a user */
@Get()
@Scopes('user-{userId}:read-approved-subnet-*')
async getAll(
Expand All @@ -38,21 +39,23 @@ export class ApprovedSubnetController {
});
}

/** Get an approved subnet for a user */
@Get(':id')
@Scopes('user-{userId}:read-approved-subnet-{id}')
async get(
@Param('userId', ParseIntPipe) userId: number,
@Param('id', ParseIntPipe) id: number,
): Promise<Expose<ApprovedSubnet>> {
return this.approvedSubnetsService.getApprovedSubnet(userId, Number(id));
return this.approvedSubnetsService.getApprovedSubnet(userId, id);
}

/** Delete an approved subnet for a user */
@Delete(':id')
@Scopes('user-{userId}:delete-approved-subnet-{id}')
async remove(
@Param('userId', ParseIntPipe) userId: number,
@Param('id', ParseIntPipe) id: number,
): Promise<Expose<ApprovedSubnet>> {
return this.approvedSubnetsService.deleteApprovedSubnet(userId, Number(id));
return this.approvedSubnetsService.deleteApprovedSubnet(userId, id);
}
}
29 changes: 15 additions & 14 deletions src/modules/approved-subnets/approved-subnets.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import type { Prisma } from '@prisma/client';
import { ApprovedSubnet } from '@prisma/client';
import { compare, hash } from 'bcrypt';
import anonymize from 'ip-anonymize';
import { Configuration } from '../../config/configuration.interface';
import {
APPROVED_SUBNET_NOT_FOUND,
UNAUTHORIZED_RESOURCE,
Expand Down Expand Up @@ -36,16 +35,20 @@ export class ApprovedSubnetsService {
},
): Promise<Expose<ApprovedSubnet>[]> {
const { skip, take, cursor, where, orderBy } = params;
const ApprovedSubnet = await this.prisma.approvedSubnet.findMany({
skip,
take,
cursor,
where: { ...where, user: { id: userId } },
orderBy,
});
return ApprovedSubnet.map((user) =>
this.prisma.expose<ApprovedSubnet>(user),
);
try {
const ApprovedSubnet = await this.prisma.approvedSubnet.findMany({
skip,
take,
cursor,
where: { ...where, user: { id: userId } },
orderBy,
});
return ApprovedSubnet.map((user) =>
this.prisma.expose<ApprovedSubnet>(user),
);
} catch (error) {
return [];
}
}

async getApprovedSubnet(
Expand Down Expand Up @@ -82,9 +85,7 @@ export class ApprovedSubnetsService {
async approveNewSubnet(userId: number, ipAddress: string) {
const subnet = await hash(
anonymize(ipAddress),
this.configService.get<Configuration['security']['saltRounds']>(
'security.saltRounds',
) ?? 10,
this.configService.get<number>('security.saltRounds') ?? 10,
);
const location = await this.geolocationService.getLocation(ipAddress);
const approved = await this.prisma.approvedSubnet.create({
Expand Down
29 changes: 20 additions & 9 deletions src/modules/sessions/sessions.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,54 +5,65 @@ import {
Param,
ParseIntPipe,
Query,
Req,
} from '@nestjs/common';
import { Session } from '@prisma/client';
import { CursorPipe } from '../../pipes/cursor.pipe';
import { OptionalIntPipe } from '../../pipes/optional-int.pipe';
import { OrderByPipe } from '../../pipes/order-by.pipe';
import { WherePipe } from '../../pipes/where.pipe';
import { Expose } from '../../providers/prisma/prisma.interface';
import { UserRequest } from '../auth/auth.interface';
import { Scopes } from '../auth/scope.decorator';
import { SessionsService } from './sessions.service';

@Controller('users/:userId/sessions')
export class SessionController {
constructor(private sessionsService: SessionsService) {}

/** Get sessions for a user */
@Get()
@Scopes('user-{userId}:read-session-*')
async getAll(
@Req() req: UserRequest,
@Param('userId', ParseIntPipe) userId: number,
@Query('skip', OptionalIntPipe) skip?: number,
@Query('take', OptionalIntPipe) take?: number,
@Query('cursor', CursorPipe) cursor?: Record<string, number | string>,
@Query('where', WherePipe) where?: Record<string, number | string>,
@Query('orderBy', OrderByPipe) orderBy?: Record<string, 'asc' | 'desc'>,
): Promise<Expose<Session>[]> {
return this.sessionsService.getSessions(userId, {
skip,
take,
orderBy,
cursor,
where,
});
return this.sessionsService.getSessions(
userId,
{
skip,
take,
orderBy,
cursor,
where,
},
req.user?.sessionId,
);
}

/** Get a session for a user */
@Get(':id')
@Scopes('user-{userId}:read-session-{id}')
async get(
@Req() req: UserRequest,
@Param('userId', ParseIntPipe) userId: number,
@Param('id', ParseIntPipe) id: number,
): Promise<Expose<Session>> {
return this.sessionsService.getSession(userId, Number(id));
return this.sessionsService.getSession(userId, id, req.user?.sessionId);
}

/** Delete a session for a user */
@Delete(':id')
@Scopes('user-{userId}:delete-session-{id}')
async remove(
@Param('userId', ParseIntPipe) userId: number,
@Param('id', ParseIntPipe) id: number,
): Promise<Expose<Session>> {
return this.sessionsService.deleteSession(userId, Number(id));
return this.sessionsService.deleteSession(userId, id);
}
}
37 changes: 26 additions & 11 deletions src/modules/sessions/sessions.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { PrismaService } from '../../providers/prisma/prisma.service';
@Injectable()
export class SessionsService {
constructor(private prisma: PrismaService) {}

async getSessions(
userId: number,
params: {
Expand All @@ -24,27 +25,41 @@ export class SessionsService {
where?: Prisma.SessionWhereInput;
orderBy?: Prisma.SessionOrderByInput;
},
): Promise<Expose<Session>[]> {
sessionId?: number,
): Promise<Expose<Session & { isCurrentSession: boolean }>[]> {
const { skip, take, cursor, where, orderBy } = params;
const sessions = await this.prisma.session.findMany({
skip,
take,
cursor,
where: { ...where, user: { id: userId } },
orderBy,
});
return sessions.map((user) => this.prisma.expose<Session>(user));
try {
const sessions = await this.prisma.session.findMany({
skip,
take,
cursor,
where: { ...where, user: { id: userId } },
orderBy,
});
return sessions
.map((user) => this.prisma.expose<Session>(user))
.map((i) => ({ ...i, isCurrentSession: sessionId === i.id }));
} catch (error) {
return [];
}
}

async getSession(userId: number, id: number): Promise<Expose<Session>> {
async getSession(
userId: number,
id: number,
sessionId?: number,
): Promise<Expose<Session & { isCurrentSession: boolean }>> {
const session = await this.prisma.session.findUnique({
where: { id },
});
if (!session) throw new NotFoundException(SESSION_NOT_FOUND);
if (session.userId !== userId)
throw new UnauthorizedException(UNAUTHORIZED_RESOURCE);
if (!session) throw new NotFoundException(SESSION_NOT_FOUND);
return this.prisma.expose<Session>(session);
return {
...this.prisma.expose<Session>(session),
isCurrentSession: sessionId === session.id,
};
}

async deleteSession(userId: number, id: number): Promise<Expose<Session>> {
Expand Down
15 changes: 11 additions & 4 deletions src/modules/webhooks/webhooks.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { WebhooksService } from './webhooks.service';
export class WebhookController {
constructor(private webhooksService: WebhooksService) {}

/** Create a webhook for a group */
@Post()
@AuditLog('create-webhook')
@Scopes('group-{groupId}:write-webhook-*')
Expand All @@ -39,6 +40,7 @@ export class WebhookController {
return this.webhooksService.createWebhook(groupId, data);
}

/** Get webhooks for a group */
@Get()
@Scopes('group-{groupId}:read-webhook-*')
async getAll(
Expand All @@ -58,21 +60,24 @@ export class WebhookController {
});
}

/** Get webhook scopes for a group */
@Get('scopes')
@Scopes('group-{groupId}:write-webhook-*')
async scopes(): Promise<Record<string, string>> {
return this.webhooksService.getWebhookScopes();
}

/** Get a webhook for a group */
@Get(':id')
@Scopes('group-{groupId}:read-webhook-{id}')
async get(
@Param('groupId', ParseIntPipe) groupId: number,
@Param('id', ParseIntPipe) id: number,
): Promise<Expose<Webhook>> {
return this.webhooksService.getWebhook(groupId, Number(id));
return this.webhooksService.getWebhook(groupId, id);
}

/** Update a webhook for a group */
@Patch(':id')
@AuditLog('update-webhook')
@Scopes('group-{groupId}:write-webhook-{id}')
Expand All @@ -81,9 +86,10 @@ export class WebhookController {
@Param('groupId', ParseIntPipe) groupId: number,
@Param('id', ParseIntPipe) id: number,
): Promise<Expose<Webhook>> {
return this.webhooksService.updateWebhook(groupId, Number(id), data);
return this.webhooksService.updateWebhook(groupId, id, data);
}

/** Replace a webhook for a group */
@Put(':id')
@AuditLog('update-webhook')
@Scopes('group-{groupId}:write-webhook-{id}')
Expand All @@ -92,16 +98,17 @@ export class WebhookController {
@Param('groupId', ParseIntPipe) groupId: number,
@Param('id', ParseIntPipe) id: number,
): Promise<Expose<Webhook>> {
return this.webhooksService.updateWebhook(groupId, Number(id), data);
return this.webhooksService.updateWebhook(groupId, id, data);
}

/** Delete a webhook for a group */
@Delete(':id')
@AuditLog('delete-webhook')
@Scopes('group-{groupId}:delete-webhook-{id}')
async remove(
@Param('groupId', ParseIntPipe) groupId: number,
@Param('id', ParseIntPipe) id: number,
): Promise<Expose<Webhook>> {
return this.webhooksService.deleteWebhook(groupId, Number(id));
return this.webhooksService.deleteWebhook(groupId, id);
}
}
25 changes: 13 additions & 12 deletions src/modules/webhooks/webhooks.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { Webhook } from '@prisma/client';
import got from 'got';
import PQueue from 'p-queue';
import pRetry from 'p-retry';
import { Configuration } from '../../config/configuration.interface';
import {
UNAUTHORIZED_RESOURCE,
WEBHOOK_NOT_FOUND,
Expand Down Expand Up @@ -48,14 +47,18 @@ export class WebhooksService {
},
): Promise<Expose<Webhook>[]> {
const { skip, take, cursor, where, orderBy } = params;
const webhooks = await this.prisma.webhook.findMany({
skip,
take,
cursor,
where: { ...where, group: { id: groupId } },
orderBy,
});
return webhooks.map((group) => this.prisma.expose<Webhook>(group));
try {
const webhooks = await this.prisma.webhook.findMany({
skip,
take,
cursor,
where: { ...where, group: { id: groupId } },
orderBy,
});
return webhooks.map((group) => this.prisma.expose<Webhook>(group));
} catch (error) {
return [];
}
}

async getWebhook(groupId: number, id: number): Promise<Expose<Webhook>> {
Expand Down Expand Up @@ -156,9 +159,7 @@ export class WebhooksService {
.add(() =>
pRetry(() => this.callWebhook(webhook, event), {
retries:
this.configService.get<Configuration['webhooks']['retries']>(
'webhooks.retries',
) ?? 3,
this.configService.get<number>('webhooks.retries') ?? 3,
onFailedAttempt: (error) => {
this.logger.error(
`Triggering webhoook failed, retrying (${error.retriesLeft} attempts left)`,
Expand Down

0 comments on commit 0d02e65

Please sign in to comment.