Skip to content

Commit

Permalink
Merge pull request #5 from isdi-coders-2023/feature/claims
Browse files Browse the repository at this point in the history
Fix guards logic
  • Loading branch information
FerreiroAlberto authored May 3, 2024
2 parents 9725183 + f9f747e commit fbb64f5
Show file tree
Hide file tree
Showing 9 changed files with 38 additions and 15 deletions.
9 changes: 6 additions & 3 deletions src/core/auth/logged.guard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
BadRequestException,
CanActivate,
ExecutionContext,
ForbiddenException,
Expand All @@ -14,12 +13,16 @@ export class LoggedGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const auth = request.headers.authorization;

if (!auth) {
throw new BadRequestException('Authorization header is required');
throw new ForbiddenException('Authorization header is required');
}
const token = auth.split(' ')[1];

try {
request.payload = await this.cryptoService.verifyToken(token);
const decodedToken = await this.cryptoService.verifyToken(token);

request.payload = decodedToken;
return true;
} catch (error) {
throw new ForbiddenException('Invalid token');
Expand Down
2 changes: 1 addition & 1 deletion src/core/auth/owner.guard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe('PolicyOwnerGuard', () => {

it('should allow access if the user is the owner of the policy', async () => {
const request = {
user: { id: 'user5' },
payload: { id: 'user5' },
params: { id: 'policy1' },
};
const policy = {
Expand Down
4 changes: 3 additions & 1 deletion src/core/auth/owner.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ export class PolicyOwnerGuard implements CanActivate {

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const user = request.user;

const user = request.payload;

const policyId = request.params.id;

const policy = await this.policiesService.findOne(policyId);
Expand Down
6 changes: 3 additions & 3 deletions src/core/crypto/crypto.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';

import { hash, compare } from 'bcrypt';
import { SignUser } from 'src/users/entities/user.entity';
import { LogUser } from '../../users/entities/user.entity';
jest.mock('bcrypt', () => ({
hash: jest.fn().mockResolvedValue('hashedValue'),
compare: jest.fn().mockResolvedValue(true),
Expand Down Expand Up @@ -59,10 +59,10 @@ describe('CryptoService', () => {

describe('When we call createToken method', () => {
it('should return a token', async () => {
const user: SignUser = { email: '[email protected]', password: '' };
const user: LogUser = { email: '[email protected]', id: '4' };
const result = await service.createToken(user);
expect(jwtServiceMock.signAsync).toHaveBeenCalledWith(
{ email: '[email protected]' },
{ email: '[email protected]', id: '4' },
{ secret: 'SECRET_JWT' },
);
expect(result).toBe('token');
Expand Down
8 changes: 5 additions & 3 deletions src/core/crypto/crypto.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { hash, compare } from 'bcrypt';
import { SignUser } from 'src/users/entities/user.entity';
import { LogUser } from '../../users/entities/user.entity';

export type TokenPayload = {
email: string;
id: string;
};

@Injectable()
Expand All @@ -23,8 +24,9 @@ export class CryptoService {
return compare(value, hash);
}

async createToken({ email }: SignUser) {
const payload: TokenPayload = { email };
async createToken({ email, id }: LogUser) {
console.log('ID en crypto:', id);
const payload: TokenPayload = { email, id };
const token = await this.jwtService.signAsync(payload, {
secret: this.configService.get('SECRET_JWT'),
});
Expand Down
5 changes: 2 additions & 3 deletions src/policies/policies.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,14 @@ export class PoliciesController {
findOne(@Param('id') id: string) {
return this.policiesService.findOne(id);
}

@UseGuards(LoggedGuard)
@UseGuards(PolicyOwnerGuard)
@UseGuards(LoggedGuard)
@Patch(':id')
update(@Param('id') id: string, @Body() updatePolicyDto: UpdatePolicyDto) {
return this.policiesService.update(id, updatePolicyDto);
}
@UseGuards(LoggedGuard)
@UseGuards(PolicyOwnerGuard)
@UseGuards(LoggedGuard)
@Delete(':id')
delete(@Param('id') id: string) {
return this.policiesService.delete(id);
Expand Down
10 changes: 9 additions & 1 deletion src/policies/policies.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,17 @@ import { PrismaService } from '../prisma/prisma.service';
import { PrismaModule } from '../prisma/prisma.module';
import { CoreModule } from '../core/core.module';

export const REPO_SERVICE = 'REPO_SERVICE';
@Module({
controllers: [PoliciesController],
providers: [PoliciesService, PrismaService],
providers: [
PoliciesService,
PrismaService,
{
provide: 'REPO_SERVICE',
useClass: PoliciesService,
},
],
imports: [PrismaModule, CoreModule],
})
export class PoliciesModule {}
8 changes: 8 additions & 0 deletions src/users/entities/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,11 @@ export class SignUser {
@IsString()
password: string;
}

export class LogUser {
@IsString()
@IsEmail()
email: string;
@IsString()
id: string;
}
1 change: 1 addition & 0 deletions src/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export class UsersService {
select: {
email: true,
password: true,
id: true,
},
});

Expand Down

0 comments on commit fbb64f5

Please sign in to comment.