Skip to content

Commit

Permalink
Merge pull request #4 from Matheus-kb/master
Browse files Browse the repository at this point in the history
login authentication
  • Loading branch information
Cabreira97 authored Jul 3, 2024
2 parents 85925ac + 99e6ca9 commit a544938
Show file tree
Hide file tree
Showing 22 changed files with 167 additions and 13 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ node_modules/

# Ignorar arquivos de build
dist/


3 changes: 2 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"singleQuote": true,
"trailingComma": "all"
"trailingComma": "all",
"endOfLine": "lf"
}
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"files.eol": "\n"
}
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest

<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
Expand Down Expand Up @@ -70,4 +70,4 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors

## License

Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ services:
- POSTGRES_PASSWORD=${DATABASE_PASSWORD}
- POSTGRES_DB=${DATABASE_NAME}
ports:
- "5432:5432"
- '5432:5432'
volumes:
- postgres_data:/var/lib/postgresql/data

Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 16 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import configuration from './config/configuration';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { EventModule } from './event/event.module';
import { OrganizerModule } from './organizer/organizer.module';
import { VolunteerModule } from './volunteer/volunteer.module';
import { AuthModule } from './auth/auth.module';
import { PrismaModule } from './prisma/prisma.module';

@Module({
imports: [EventModule, OrganizerModule, VolunteerModule],
imports: [
ConfigModule.forRoot({
load: [configuration],
isGlobal: true,
}),
EventModule,
OrganizerModule,
VolunteerModule,
AuthModule,
PrismaModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
export class AppModule {}
26 changes: 26 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Controller, Post, Body, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { JwtService } from '@nestjs/jwt';

@Controller('auth')
export class AuthController {
constructor(
private authService: AuthService,
private jwtService: JwtService,
) {}

@Post('login')
async login(@Body() body: { email: string; password: string }) {
const user = await this.authService.validateUser(body.email, body.password);
if (!user) {
throw new UnauthorizedException('Invalid credentials');
}

const payload = { email: user.email, sub: user.id, type: user.type };
const accessToken = this.jwtService.sign(payload);
return {
access_token: accessToken,
user: user,
};
}
}
23 changes: 23 additions & 0 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';

import { PrismaModule } from '../prisma/prisma.module';
import { JwtModule } from '@nestjs/jwt';

import { PassportModule } from '@nestjs/passport';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './jwt.strategy';

@Module({
imports: [
PrismaModule,
PassportModule,
JwtModule.register({
secret: 'your_jwt_secret_key',
signOptions: { expiresIn: '60m' },
}),
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
})
export class AuthModule {}
27 changes: 27 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class AuthService {
constructor(private prisma: PrismaService) {}

async validateUser(email: string, password: string): Promise<any> {
const organizer = await this.prisma.organizer.findUnique({
where: { email },
});

if (organizer && organizer.password === password) {
return { ...organizer, type: 'organizer' };
}

const volunteer = await this.prisma.volunteer.findUnique({
where: { email },
});

if (volunteer && volunteer.password === password) {
return { ...volunteer, type: 'volunteer' };
}

throw new UnauthorizedException('Invalid credentials');
}
}
19 changes: 19 additions & 0 deletions src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>('JWT_SECRET'),
});
}

async validate(payload: any) {
return { userId: payload.sub, email: payload.email, type: payload.type };
}
}
3 changes: 3 additions & 0 deletions src/config/configuration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default () => ({
JWT_SECRET: process.env.JWT_SECRET,
});
5 changes: 5 additions & 0 deletions src/config/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
declare namespace NodeJS {
interface ProcessEnv {
JWT_SECRET: string;
}
}
2 changes: 1 addition & 1 deletion src/event/event.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { CreateEventDto, EventService } from './event.service';
@ApiTags('events')
@Controller('events')
export class EventController {
constructor(private readonly eventService: EventService) { }
constructor(private readonly eventService: EventService) {}

@Post()
@ApiOperation({ summary: 'Create an event' })
Expand Down
2 changes: 1 addition & 1 deletion src/event/event.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ import { EventService } from './event.service';
controllers: [EventController],
providers: [EventService],
})
export class EventModule { }
export class EventModule {}
7 changes: 7 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);

// Configurar CORS usando enableCors
app.enableCors({
origin: 'http://localhost:3001', // Adicione a origem permitida aqui
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true, // Se precisar permitir cookies entre diferentes origens
});

const config = new DocumentBuilder()
.setTitle('API-MAIN --- ConnectTech')
.setDescription('Connect Tech ')
Expand Down
2 changes: 1 addition & 1 deletion src/organizer/organizer.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { Organizer } from '@prisma/client';
@ApiTags('organizers')
@Controller('organizers')
export class OrganizerController {
constructor(private readonly organizerService: OrganizerService) { }
constructor(private readonly organizerService: OrganizerService) {}

@Post()
@ApiOperation({ summary: 'Create organizer' })
Expand Down
2 changes: 1 addition & 1 deletion src/organizer/organizer.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ import { OrganizerService } from './organizer.service';
controllers: [OrganizerController],
providers: [OrganizerService],
})
export class OrganizerModule { }
export class OrganizerModule {}
8 changes: 8 additions & 0 deletions src/prisma/prisma.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';

@Module({
providers: [PrismaService],
exports: [PrismaService],
})
export class PrismaModule {}
16 changes: 16 additions & 0 deletions src/prisma/prisma.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
async onModuleInit() {
await this.$connect();
}

async onModuleDestroy() {
await this.$disconnect();
}
}
2 changes: 1 addition & 1 deletion src/volunteer/volunteer.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { Volunteer } from '@prisma/client';
@ApiTags('volunteers')
@Controller('volunteers')
export class VolunteerController {
constructor(private readonly volunteerService: VolunteerService) { }
constructor(private readonly volunteerService: VolunteerService) {}

@Post()
@ApiOperation({ summary: 'Create a new volunteer' })
Expand Down
2 changes: 1 addition & 1 deletion src/volunteer/volunteer.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ import { VolunteerService } from './volunteer.service';
controllers: [VolunteerController],
providers: [VolunteerService],
})
export class VolunteerModule { }
export class VolunteerModule {}

0 comments on commit a544938

Please sign in to comment.