Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: addition of apiDecoratorFactory to manage the creation of docum… #15

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Database
DATABASE_URL=
PG_HOST=
DB_PORT=
PG_USER=
PG_PASSWORD=
PG_DB=
DATABASE_URL=postgresql://${PG_USER}:${PG_PASSWORD}@${PG_HOST}:${DB_PORT}/${PG_DB}

# Auth
AUTH0_AUDIENCE=
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@
$ npm install
```

## Creating migrations
```bash
# development
$ npm prisma migration dev
```


## Running the app

```bash
Expand Down
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"email:dev": "email dev -p 3001"
},
"dependencies": {
"@apollo/server": "^4.11.0",
yurimutti marked this conversation as resolved.
Show resolved Hide resolved
"@apollo/subgraph": "^2.0.5",
"@aws-sdk/client-s3": "^3.137.0",
"@aws-sdk/s3-request-presigner": "3.67.0",
Expand All @@ -42,9 +43,9 @@
"apollo-server-express": "^3.10.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"express-jwt": "^7.7.5",
"express-jwt": "^8.4.1",
"graphql": "^16.5.0",
"jwks-rsa": "^2.1.4",
"jwks-rsa": "^3.1.0",
"react-email": "2.1.6",
"reflect-metadata": "^0.1.13",
"resend": "^3.5.0",
Expand Down Expand Up @@ -78,4 +79,4 @@
"wrap-ansi": "7.0.0",
"string-width": "4.1.0"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "ProfileType" ADD VALUE 'ADMIN';
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ enum ProfileType {
HODLER
RECYCLER
WASTE_GENERATOR
ADMIN
}

enum ResidueType {
Comment on lines 16 to 22
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We will need run a migration here ?

Expand Down
60 changes: 60 additions & 0 deletions src/decorators/apiDecoratorFactory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import {
applyDecorators,
Delete,
Get,
Post,
Put,
UseGuards,
} from '@nestjs/common';
import {
ApiBearerAuth,
ApiOkResponse,
ApiOperation,
ApiUnauthorizedResponse,
} from '@nestjs/swagger';

import { Roles } from '@/auth/roles.decorator';
import { RestAuthorizationGuard } from '@/guards/authorization.guard';
import { MessagesHelper } from '@/helpers/messages.helper';
import { Role } from '@/util/constants';

interface ApiAuthOptions {
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
path: string;
summary: string;
description: string;
authRoute: boolean;
responseType: any;
roles?: Role;
}

export function ApiAuthOperation(options: ApiAuthOptions) {
const decorators = [
ApiOperation({
summary: options.summary,
description: options.description,
}),
ApiUnauthorizedResponse({ description: MessagesHelper.USER_UNAUTHORIZED }),
ApiOkResponse({ description: options.summary, type: options.responseType }),
options.authRoute && ApiBearerAuth('access-token'),
options.authRoute && UseGuards(RestAuthorizationGuard),
Roles(options.roles),
].filter(Boolean) as MethodDecorator[];

switch (options.method) {
case 'GET':
decorators.push(Get(options.path));
break;
case 'POST':
decorators.push(Post(options.path));
break;
case 'PUT':
decorators.push(Put(options.path));
break;
case 'DELETE':
decorators.push(Delete(options.path));
break;
}

return applyDecorators(...decorators);
}
14 changes: 14 additions & 0 deletions src/decorators/current-user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export interface AuthUser {
sub: string;
permissions?: string[];
}

export const RestCurrentUser = createParamDecorator(
(data: unknown, context: ExecutionContext): AuthUser => {
const request = context.switchToHttp().getRequest();

return request.user;
},
);
12 changes: 8 additions & 4 deletions src/forms/forms.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Body, Controller, Get, Param, Post, Put, Query } from '@nestjs/common';
import {
ApiBearerAuth,
ApiOkResponse,
ApiOperation,
ApiParam,
ApiTags,
} from '@nestjs/swagger';

import { ApiAuthOperation } from '@/decorators/apiDecoratorFactory';
import { ApiOkResponsePaginated } from '@/dto/paginated.dto';

import {
Expand All @@ -19,7 +19,7 @@ import {
import { FormsService } from './forms.service';

@ApiTags('forms')
@ApiBearerAuth('access-token')
// @ApiBearerAuth('access-token')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This decorator is now being applied individually to each route, using the custom decorator created by Vinicius. When authRoute is true, it applies @ApiBearerAuth('access-token') to the route in question. In this case, to maintain the same logic as before, I believe authRoute should remain true for all the form endpoints.

@Controller({ path: 'forms', version: '1' })
export class FormsController {
constructor(private readonly formsService: FormsService) {}
Expand All @@ -37,10 +37,14 @@ export class FormsController {
return this.formsService.aggregateFormByUserProfile();
}

@Post(':formId/image-url')
@ApiOperation({
@ApiAuthOperation({
path: ':formId/image-url',
method: 'POST',
summary: 'returns presigned url for image upload',
description: 'Returns presigned url for image upload',
authRoute: false,

responseType: String,
})
submitFormImage(@Param('formId') formId: string) {
return this.formsService.submitFormImage(formId);
Expand Down
10 changes: 9 additions & 1 deletion src/graphql/authorization.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { expressJwtSecret, GetVerificationKey } from 'jwks-rsa';
import { PERMISSION_SCOPES, Role, ROLES_KEY } from 'src/util/constants';
import { promisify } from 'util';

import { MessagesHelper } from '@/helpers/messages.helper';

@Injectable()
export class AuthorizationGuard implements CanActivate {
private AUTH0_AUDIENCE: string;
Expand Down Expand Up @@ -60,14 +62,20 @@ export class AuthorizationGuard implements CanActivate {

const scopeRules = req?.auth.permissions as string[];
if (requiredRoles) {
if (!scopeRules?.length) return false;
if (!scopeRules?.length) {
throw new UnauthorizedException(MessagesHelper.USER_UNAUTHORIZED);
}

const [requiredRole] = requiredRoles;

const hasAccess = scopeRules.every((scopeType) =>
PERMISSION_SCOPES[requiredRole].includes(scopeType),
);

if (!hasAccess) {
throw new UnauthorizedException(MessagesHelper.USER_UNAUTHORIZED);
}

return hasAccess;
}

Expand Down
78 changes: 78 additions & 0 deletions src/guards/authorization.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Reflector } from '@nestjs/core';
import { Request, Response } from 'express';
import { expressjwt, GetVerificationKey } from 'express-jwt';
import { expressJwtSecret } from 'jwks-rsa';
import { PERMISSION_SCOPES, Role, ROLES_KEY } from 'src/util/constants';
import { promisify } from 'util';

interface AuthenticatedRequest extends Request {
auth?: {
permissions?: string[];
};
}

@Injectable()
export class RestAuthorizationGuard implements CanActivate {
private AUTH0_AUDIENCE: string;
private AUTH0_DOMAIN: string;

constructor(
private configService: ConfigService,
private reflector: Reflector,
) {
this.AUTH0_AUDIENCE = this.configService.get('AUTH0_AUDIENCE');
this.AUTH0_DOMAIN = this.configService.get('AUTH0_DOMAIN');
}

async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest<AuthenticatedRequest>();
const res = context.switchToHttp().getResponse<Response>();

const checkJWT = promisify(
expressjwt({
secret: expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `${this.AUTH0_DOMAIN}.well-known/jwks.json`,
}) as GetVerificationKey,
audience: this.AUTH0_AUDIENCE,
issuer: this.AUTH0_DOMAIN,
algorithms: ['RS256'],
}),
);

try {
await checkJWT(req, res);

const requiredRoles = this.reflector.getAllAndOverride<Role[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);

const scopeRules = req?.auth?.permissions;
if (requiredRoles) {
if (!scopeRules?.length) return false;

const [requiredRole] = requiredRoles;

const hasAccess = scopeRules.every((scopeType) =>
PERMISSION_SCOPES[requiredRole].includes(scopeType),
);

return hasAccess;
}

return true;
} catch (err) {
throw new UnauthorizedException(err);
}
}
}
1 change: 1 addition & 0 deletions src/helpers/messages.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const usersMessages = {
USER_NOT_FOUND: 'User not found',
USER_DOES_NOT_HAS_PERMISSION_TO_UPLOAD:
'User do not have permission to submit files',
USER_UNAUTHORIZED: "User doesn't have access to this route",
};

const formMessages = {
Expand Down