Skip to content

Commit

Permalink
Merge pull request #16 from hebertsanto/feature-auth
Browse files Browse the repository at this point in the history
Feature auth
  • Loading branch information
hebertzin authored Apr 3, 2024
2 parents d9dcd0a + 68b04e4 commit 985d584
Show file tree
Hide file tree
Showing 25 changed files with 217 additions and 108 deletions.
32 changes: 20 additions & 12 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { Module } from '@nestjs/common';
import {
MiddlewareConsumer,
Module,
NestModule,
RequestMethod,
} from '@nestjs/common';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { ProjectsModule } from './projects/projects.module';
Expand All @@ -16,9 +21,8 @@ import { EmailModule } from './send-email/email.module';
import { HashModule } from './hash/hash.module';
import { LoggerModule } from './logger/logger.module';
import { JwtModule } from '@nestjs/jwt';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { JwtInterceptor } from './auth/auth.service';
import { TaskListProjectModule } from './task-list-project/task-list-project.module';
import { JwtMiddleware } from './middlewares/jwt-middleware';

@Module({
imports: [
Expand All @@ -43,13 +47,17 @@ import { TaskListProjectModule } from './task-list-project/task-list-project.mod
LoggerModule,
TaskListProjectModule,
],
controllers: [],
providers: [
AppService,
{
provide: APP_INTERCEPTOR,
useClass: JwtInterceptor,
},
],

providers: [AppService],
})
export class AppModule {}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(JwtMiddleware)
.exclude(
{ path: '/user/login', method: RequestMethod.POST },
{ path: '/user', method: RequestMethod.POST },
)
.forRoutes('*');
}
}
9 changes: 0 additions & 9 deletions src/auth/auth.module.ts

This file was deleted.

33 changes: 0 additions & 33 deletions src/auth/auth.service.ts

This file was deleted.

7 changes: 3 additions & 4 deletions src/comments/comments.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { Module } from '@nestjs/common';
import { CommentsController } from './controller/comments/comments.controller';
import { CommentsService } from './services/comments/comments.service';
import { ProjectsService } from 'src/projects/services/projects/projects.service';
import { UserService } from 'src/user/services/user/user.service';
import { HashService } from 'src/hash/service/hash/hash.service';
import { SharedServicesModule } from 'src/shared/shared-services.module';

@Module({
imports: [SharedServicesModule],
controllers: [CommentsController],
providers: [CommentsService, ProjectsService, UserService, HashService],
providers: [CommentsService],
})
export class CommentsModule {}
11 changes: 10 additions & 1 deletion src/comments/controller/comments/comments.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import {
Post,
Put,
Res,
Req,
} from '@nestjs/common';

import {
ApiBadRequestResponse,
ApiInternalServerErrorResponse,
Expand Down Expand Up @@ -35,7 +37,14 @@ export class CommentsController {
description: 'Internal server error',
})
@Get('/:id')
async getCommentById(@Param('id') id: string, @Res() res: Response) {
async getCommentById(
@Param('id') id: string,
@Res() res: Response,
@Req() req,
) {
const user = req.user;

console.log(user);
const commentFound = await this.commentsServices.findCommentById(id);

return res.status(200).json({
Expand Down
63 changes: 60 additions & 3 deletions src/comments/services/comments/comments.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,87 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CommentsService } from './comments.service';
import { UserService } from 'src/user/services/user/user.service';
import { PrismaService } from 'src/database/prisma.service';
import { HashService } from 'src/hash/service/hash/hash.service';
import { ProjectsService } from 'src/projects/services/projects/projects.service';
import { LoggerService } from 'src/logger/logger.service';
import { HashService } from 'src/hash/service/hash/hash.service';
import { PrismaService } from 'src/database/prisma.service';
import { Comment } from 'src/comments/types/comments';
import { PrismaModule } from 'src/database/prisma.module';

describe('CommentsService', () => {
let service: CommentsService;
let userService: UserService;
let projectService: ProjectsService;
let prismaService: PrismaService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
CommentsService,
UserService,
PrismaService,
HashService,
ProjectsService,
HashService,
LoggerService,
],
imports: [PrismaModule],
}).compile();

service = module.get<CommentsService>(CommentsService);
userService = module.get<UserService>(UserService);
projectService = module.get<ProjectsService>(ProjectsService);
prismaService = module.get<PrismaService>(PrismaService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});

it('should create a comment', async () => {
const commentData: Comment = {
userId: 'user_id',
projectId: 'project_id',
comment: 'com',
questionId: 'fda',
// add other required fields
};

const createCommentSpy = jest
.spyOn(prismaService.comments, 'create')
.mockResolvedValueOnce(commentData as any);

const checkUserExistenceSpy = jest
.spyOn(userService, 'checkUserExistence')
.mockResolvedValueOnce({
id: 'fad',
name: 'Hebert',
email: '[email protected]',
emailStatus: 'PENDING',
password: '203040',
createAt: new Date(),
updateAt: new Date(),
teamMemberShipId: '303002',
});

const checkProjectExistenceSpy = jest
.spyOn(projectService, 'checkProjectExistence')
.mockResolvedValueOnce({
id: 'uuid',
name: 'Awesome Project',
description: 'This is a sample project',
priority: 'MIN',
userId: 'fmadm',
url: 'https://example.com/project',
visibility: true,
createAt: new Date(),
updateAt: new Date(),
});

const createdComment = await service.createComment(commentData);

expect(checkUserExistenceSpy).toHaveBeenCalledWith('user_id');
expect(checkProjectExistenceSpy).toHaveBeenCalledWith('project_id');
expect(createCommentSpy).toHaveBeenCalledWith({ data: commentData });
expect(createdComment).toEqual(commentData as any);
});
});
2 changes: 1 addition & 1 deletion src/database/prisma.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export class PrismaService extends PrismaClient implements OnModuleInit {
}

async disconnect() {
await this.$on('beforeExist' as never, async (app: any) => {
this.$on('beforeExist' as never, async (app: any) => {
await app.close;
});
}
Expand Down
7 changes: 3 additions & 4 deletions src/decisions/decisions.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { Module } from '@nestjs/common';
import { DecisionsController } from './controller/decisions/decisions.controller';
import { DecisionsService } from './services/decisions/decisions.service';
import { UserService } from 'src/user/services/user/user.service';
import { ProjectsService } from 'src/projects/services/projects/projects.service';
import { HashService } from 'src/hash/service/hash/hash.service';
import { SharedServicesModule } from 'src/shared/shared-services.module';

@Module({
imports: [SharedServicesModule],
controllers: [DecisionsController],
providers: [DecisionsService, UserService, ProjectsService, HashService],
providers: [DecisionsService],
})
export class DecisionsModule {}
7 changes: 3 additions & 4 deletions src/follow-project/follow-project.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { Module } from '@nestjs/common';
import { FollowProjectService } from './service/follow-project/follow-project.service';
import { FollowProjectController } from './controller/follow-project/follow-project.controller';
import { UserService } from 'src/user/services/user/user.service';
import { ProjectsService } from 'src/projects/services/projects/projects.service';
import { HashService } from 'src/hash/service/hash/hash.service';
import { SharedServicesModule } from 'src/shared/shared-services.module';

@Module({
providers: [FollowProjectService, UserService, ProjectsService, HashService],
imports: [SharedServicesModule],
providers: [FollowProjectService],
controllers: [FollowProjectController],
})
export class FollowProjectModule {}
7 changes: 3 additions & 4 deletions src/goals/goals.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { Module } from '@nestjs/common';
import { GoalsController } from './controller/goals/goals.controller';
import { GoalsService } from './services/goals/goals.service';
import { UserService } from 'src/user/services/user/user.service';
import { ProjectsService } from 'src/projects/services/projects/projects.service';
import { HashService } from 'src/hash/service/hash/hash.service';
import { SharedServicesModule } from 'src/shared/shared-services.module';

@Module({
imports: [SharedServicesModule],
controllers: [GoalsController],
providers: [GoalsService, UserService, ProjectsService, HashService],
providers: [GoalsService],
})
export class GoalsModule {}
6 changes: 6 additions & 0 deletions src/hash/service/hash/hash.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,10 @@ export class HashService {
return error;
}
}

async compare(password: string, password_hash: string) {
const compare = await crypto.compare(password, password_hash);

return compare;
}
}
3 changes: 2 additions & 1 deletion src/i18n/en/users-messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
"message.user.update": "User has been updated successfully",
"message.user.get": "User found successfully",
"message.user.notFound": "User not found",
"message.user.conflict": "User already exist"
"message.user.conflict": "User already exist",
"message.user.login": "User logged"
}
15 changes: 15 additions & 0 deletions src/jwt/services/jwt.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
constructor(private jwtService: JwtService) {}

async generateToken(payload: any) {
return this.jwtService.sign(payload);
}

async verifyToken(token: string) {
return this.jwtService.verify(token);
}
}
27 changes: 27 additions & 0 deletions src/middlewares/jwt-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Injectable, NestMiddleware, NotFoundException } from '@nestjs/common';
import { JsonWebTokenError, JwtService } from '@nestjs/jwt';
import { i18n } from 'src/i18n';

@Injectable()
export class JwtMiddleware implements NestMiddleware {
constructor(private jwtService: JwtService) {}

use(req: any, _res: any, next: () => void) {
console.log(req);
const token = req.headers.authorization?.split(' ')[1];

if (!token) {
throw new NotFoundException(i18n()['exception.tokenNotProvided']);
}

const decoded = this.jwtService.verify(token);

if (!decoded) {
throw new JsonWebTokenError(i18n()['exception.tokenMalformed']);
}

req.user = decoded;

next();
}
}
6 changes: 3 additions & 3 deletions src/profile/profile.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Module } from '@nestjs/common';
import { ProfileController } from './controller/profile/profile.controller';
import { ProfileService } from './services/profile/profile.service';
import { UserService } from 'src/user/services/user/user.service';
import { HashService } from 'src/hash/service/hash/hash.service';
import { SharedServicesModule } from 'src/shared/shared-services.module';

@Module({
imports: [SharedServicesModule],
controllers: [ProfileController],
providers: [ProfileService, UserService, HashService],
providers: [ProfileService],
})
export class ProfileModule {}
6 changes: 3 additions & 3 deletions src/project-idea/project-idea.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Module } from '@nestjs/common';
import { ProjectIdeaController } from './controllers/project-idea.controller';
import { ProjectIdeaService } from './services/project-idea.service';
import { UserService } from 'src/user/services/user/user.service';
import { HashService } from 'src/hash/service/hash/hash.service';
import { SharedServicesModule } from 'src/shared/shared-services.module';

@Module({
imports: [SharedServicesModule],
controllers: [ProjectIdeaController],
providers: [ProjectIdeaService, UserService, HashService],
providers: [ProjectIdeaService],
})
export class ProjectIdea {}
6 changes: 3 additions & 3 deletions src/projects/projects.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Module } from '@nestjs/common';
import { ProjectsController } from './controller/projects/projects.controller';
import { ProjectsService } from './services/projects/projects.service';
import { UserService } from 'src/user/services/user/user.service';
import { HashService } from 'src/hash/service/hash/hash.service';
import { SharedServicesModule } from 'src/shared/shared-services.module';

@Module({
imports: [SharedServicesModule],
controllers: [ProjectsController],
providers: [ProjectsService, UserService, HashService],
providers: [ProjectsService],
})
export class ProjectsModule {}
Loading

0 comments on commit 985d584

Please sign in to comment.