From 31d6f2c65d9072bf7937ac471685031595a3bd6f Mon Sep 17 00:00:00 2001 From: IO Date: Thu, 6 Jun 2024 20:32:46 -0600 Subject: [PATCH] guard creation and more --- src/Profesor/profesor.controller.ts | 8 ------ src/Profesor/profesor.module.ts | 12 -------- src/Profesor/profesor.service.ts | 8 ------ src/app.module.ts | 8 ++---- src/auth/auth.controller.ts | 21 ++++++++++++-- src/auth/auth.guard.ts | 43 +++++++++++++++++++++++++++++ src/auth/auth.module.ts | 17 ++++++++---- src/auth/constants.ts | 4 --- src/users/entities/user.entity.ts | 13 +++++++++ src/users/users.module.ts | 3 ++ src/users/users.service.ts | 30 ++++++++++---------- 11 files changed, 105 insertions(+), 62 deletions(-) delete mode 100644 src/Profesor/profesor.controller.ts delete mode 100644 src/Profesor/profesor.module.ts delete mode 100644 src/Profesor/profesor.service.ts create mode 100644 src/auth/auth.guard.ts delete mode 100644 src/auth/constants.ts create mode 100644 src/users/entities/user.entity.ts diff --git a/src/Profesor/profesor.controller.ts b/src/Profesor/profesor.controller.ts deleted file mode 100644 index 8807e43..0000000 --- a/src/Profesor/profesor.controller.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* -https://docs.nestjs.com/controllers#controllers -*/ - -import { Controller } from '@nestjs/common'; - -@Controller() -export class ProfesorController {} diff --git a/src/Profesor/profesor.module.ts b/src/Profesor/profesor.module.ts deleted file mode 100644 index ca1cd0d..0000000 --- a/src/Profesor/profesor.module.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* -https://docs.nestjs.com/modules -*/ - -import { Module } from '@nestjs/common'; - -@Module({ - imports: [], - controllers: [], - providers: [], -}) -export class ProfesorModule { } diff --git a/src/Profesor/profesor.service.ts b/src/Profesor/profesor.service.ts deleted file mode 100644 index d965d37..0000000 --- a/src/Profesor/profesor.service.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* -https://docs.nestjs.com/providers#services -*/ - -import { Injectable } from '@nestjs/common'; - -@Injectable() -export class ProfesorService {} diff --git a/src/app.module.ts b/src/app.module.ts index 97214e8..a6cdb14 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -1,6 +1,3 @@ -import { ProfesorModule } from './Profesor/profesor.module'; -import { ProfesorController } from './Profesor/profesor.controller'; -import { ProfesorService } from './Profesor/profesor.service'; import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { AppController } from './app.controller'; @@ -31,9 +28,8 @@ import { TypeOrmModule } from '@nestjs/typeorm'; synchronize: configservice.get('DB_SYNCRONIZE'), }), }), - ProfesorModule, ], - controllers: [ProfesorController, AppController], - providers: [ProfesorService, AppService], + controllers: [AppController], + providers: [AppService], }) export class AppModule {} diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index d66a0f7..57e7b5f 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -1,5 +1,14 @@ - -import { Body, Controller, Post, HttpCode, HttpStatus } from '@nestjs/common'; +import { + Body, + Controller, + Get, + HttpCode, + HttpStatus, + Post, + Request, + UseGuards +} from '@nestjs/common'; +import { AuthGuard } from './auth.guard'; import { AuthService } from './auth.service'; @Controller('auth') @@ -11,4 +20,10 @@ export class AuthController { signIn(@Body() signInDto: Record) { return this.authService.signIn(signInDto.username, signInDto.password); } -} + + @UseGuards(AuthGuard) + @Get('profile') + getProfile(@Request() req) { + return req.user; + } +} \ No newline at end of file diff --git a/src/auth/auth.guard.ts b/src/auth/auth.guard.ts new file mode 100644 index 0000000..7f5aba5 --- /dev/null +++ b/src/auth/auth.guard.ts @@ -0,0 +1,43 @@ +import { + CanActivate, + ExecutionContext, + Injectable, + UnauthorizedException, + } from '@nestjs/common'; + import { JwtService } from '@nestjs/jwt'; + import { Request } from 'express'; + import { ConfigService } from '@nestjs/config'; + + @Injectable() + export class AuthGuard implements CanActivate { + constructor( + private jwtService: JwtService, + private configService: ConfigService + ) {} + + async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + const token = this.extractTokenFromHeader(request); + if (!token) { + throw new UnauthorizedException(); + } + try { + const payload = await this.jwtService.verifyAsync( + token, + { + secret: this.configService.get('JWT_SECRET'), + } + ); + + request['user'] = payload; + } catch { + throw new UnauthorizedException(); + } + return true; + } + + private extractTokenFromHeader(request: Request): string | undefined { + const [type, token] = request.headers.authorization?.split(' ') ?? []; + return type === 'Bearer' ? token : undefined; + } + } \ No newline at end of file diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts index dc69a64..84bb1ba 100644 --- a/src/auth/auth.module.ts +++ b/src/auth/auth.module.ts @@ -4,15 +4,22 @@ import { AuthService } from './auth.service'; import { UsersModule } from '../users/users.module'; import { JwtModule } from '@nestjs/jwt'; import { AuthController } from './auth.controller'; -import { jwtConstants } from './constants'; +import { ConfigService } from '@nestjs/config'; @Module({ imports: [ UsersModule, - JwtModule.register({ - global: true, - secret: jwtConstants.secret, - signOptions: { expiresIn: '60s' }, + JwtModule.registerAsync({ + inject:[ConfigService], + useFactory:async(configService:ConfigService)=>{ + return{ + global: true, + secret: configService.get('JWT_SECRET'), + signOptions: { + expiresIn: configService.get('JWT_EXPIRE') + }, + } + } }), ], providers: [AuthService], diff --git a/src/auth/constants.ts b/src/auth/constants.ts deleted file mode 100644 index a94a56a..0000000 --- a/src/auth/constants.ts +++ /dev/null @@ -1,4 +0,0 @@ -export const jwtConstants = { - secret: 'secret', - }; - \ No newline at end of file diff --git a/src/users/entities/user.entity.ts b/src/users/entities/user.entity.ts new file mode 100644 index 0000000..8d95ac6 --- /dev/null +++ b/src/users/entities/user.entity.ts @@ -0,0 +1,13 @@ +import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; + +@Entity() +export class User { + @PrimaryGeneratedColumn() + userId: number; + + @Column() + username: string; + + @Column() + password: string; +} diff --git a/src/users/users.module.ts b/src/users/users.module.ts index dac33ad..6355cda 100644 --- a/src/users/users.module.ts +++ b/src/users/users.module.ts @@ -1,8 +1,11 @@ import { Module } from '@nestjs/common'; +import { TypeOrmModule } from '@nestjs/typeorm'; import { UsersService } from './users.service'; +import { User } from './entities/user.entity'; @Module({ + imports: [TypeOrmModule.forFeature([User])], providers: [UsersService], exports: [UsersService], }) diff --git a/src/users/users.service.ts b/src/users/users.service.ts index 2a55682..5fc5069 100644 --- a/src/users/users.service.ts +++ b/src/users/users.service.ts @@ -1,24 +1,22 @@ - import { Injectable } from '@nestjs/common'; - -export type User = any; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; +import { User } from './entities/user.entity'; @Injectable() export class UsersService { - private readonly users = [ - { - userId: 1, - username: 'john', - password: 'changeme', - }, - { - userId: 2, - username: 'maria', - password: 'guess', - }, - ]; + constructor( + @InjectRepository(User) + private users: Repository, + ) {} async findOne(username: string): Promise { - return this.users.find(user => user.username === username); + return this.users.findOne({ where: { username } }); + } + + async create(user: User): Promise { + return this.users.save(user); } } + +