From f91ce4037174d5e91f6c613e898b8b2d3d3c13ce Mon Sep 17 00:00:00 2001 From: TuNombreDeUsuario Date: Wed, 12 Jun 2024 11:40:20 -0600 Subject: [PATCH] validate token --- src/auth/auth.controller.ts | 29 +++++++++---- src/auth/auth.module.ts | 1 - src/auth/auth.service.ts | 42 +++++++++++++------ src/auth/{Dto => dto}/registerDto.dto.ts | 0 .../{create-user.dto.ts => userDto.dto.ts} | 7 ++-- src/users/users.service.ts | 19 +++++++-- 6 files changed, 68 insertions(+), 30 deletions(-) rename src/auth/{Dto => dto}/registerDto.dto.ts (100%) rename src/users/dto/{create-user.dto.ts => userDto.dto.ts} (51%) diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index 1bffc79..c72d9ff 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -14,6 +14,7 @@ import { import { AuthGuard } from './auth.guard'; import { AuthService } from './auth.service'; import { registerDto } from './dto/registerDto.dto'; +import { UserDto } from 'src/users/dto/userDto.dto'; @Controller('auth') export class AuthController { @@ -21,34 +22,44 @@ export class AuthController { @HttpCode(HttpStatus.OK) @Post('login') - signIn(@Body() data: registerDto) { + async signIn(@Body() data: registerDto) { return this.authService.signIn(data); } + @Post("register") + async postRegister(@Body() data: registerDto){ + return this.authService.register(data) + } + @UseGuards(AuthGuard) @Get('profile') - getProfile(@Request() req) { + async getProfile(@Request() req) { return req.user; } - @Post("register") - postRegister(@Body() data: registerDto){ - return this.authService.register(data) - } - + @UseGuards(AuthGuard) @Post('Alta') - async create(@Body() createUserDto: Record) { - return this.authService.create(createUserDto.username,createUserDto.password); + async create(@Body() data: UserDto) { + return this.authService.create(data); } + @UseGuards(AuthGuard) @Put('Modificacion/:id') async update(@Param('id') id: number, @Body() updateUserDto: Record) { return this.authService.update(id, updateUserDto); } + @UseGuards(AuthGuard) @Delete('Borrado/:id') async remove(@Param('id') id: number) { await this.authService.remove(id); return { message: 'User successfully deleted' }; } + + @HttpCode(HttpStatus.OK) + @Post('validate') + async validateToken(@Body('token') token: string) { + return this.authService.validateToken(token); + } + } \ No newline at end of file diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts index 5910219..4e64999 100644 --- a/src/auth/auth.module.ts +++ b/src/auth/auth.module.ts @@ -5,7 +5,6 @@ import { UsersModule } from '../users/users.module'; import { JwtModule } from '@nestjs/jwt'; import { AuthController } from './auth.controller'; import { ConfigService } from '@nestjs/config'; -import { UsersService } from 'src/users/users.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { User } from 'src/users/entities/user.entity'; diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index e23b824..078b532 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -8,41 +8,39 @@ import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { hash } from 'bcrypt'; import { compare } from 'bcryptjs'; +import { ConfigService } from '@nestjs/config'; @Injectable() export class AuthService { constructor( private usersService: UsersService, private jwtService: JwtService, + private configService:ConfigService, @InjectRepository(User) private userRepository: Repository ) {} async register(data: registerDto){ const{username, password,} = data; - //Seeks the password and if it finds it, it doesn't register if(await this.usersService.findOne(data.username)){ throw new HttpException("User already exist",403); } - //Encrypt the password - const hashedpassword = await hash(password, 10); + const hashedpassword = await hash(password, 10); - //Place the password in data data = {...data, password:hashedpassword} return this.userRepository.save( this.userRepository.create(data) ) } + async signIn(data: registerDto) { const{password} = data; const user = await this.usersService.findOne(data.username); - //compare encrypt password with the password entered const checkPassword = await compare(password, (await user).password) - //if the password is incorrect, won't let you in if (!checkPassword) { throw new UnauthorizedException(); } @@ -50,20 +48,14 @@ export class AuthService { idUser: user.userId, username: user.username }; - - //create the token with the payload const token = this.jwtService.sign(payload); - //update all await this.usersService.updateTokenAndDates(user.userId,token, new Date(), new Date(Date.now() + 3600 * 1000)); return {token: token}; } - async create( - username: string, - pass: string, - ){ + async create(data){ } @@ -80,4 +72,28 @@ export class AuthService { } + async validateToken(token: string): Promise { + try { + const decoded = this.jwtService.verify(token, { + secret: this.configService.get('JWT_SECRET'), + }); + + //verify JWT's username with DB's username + const user = await this.usersService.findOne(decoded.username); + if (!user) { + throw new UnauthorizedException('Invalid token'); + } + + //verify JWT doesn't expired + const currentTime = Math.floor(Date.now() / 1000); + if (decoded.exp < currentTime) { + throw new UnauthorizedException('Token has expired'); + } + + return user; + } catch (error) { + throw new UnauthorizedException('validation token failed'); + } + } + } diff --git a/src/auth/Dto/registerDto.dto.ts b/src/auth/dto/registerDto.dto.ts similarity index 100% rename from src/auth/Dto/registerDto.dto.ts rename to src/auth/dto/registerDto.dto.ts diff --git a/src/users/dto/create-user.dto.ts b/src/users/dto/userDto.dto.ts similarity index 51% rename from src/users/dto/create-user.dto.ts rename to src/users/dto/userDto.dto.ts index 05d95e8..ef254ec 100644 --- a/src/users/dto/create-user.dto.ts +++ b/src/users/dto/userDto.dto.ts @@ -1,11 +1,10 @@ import { IsEmail, IsNotEmpty, IsString, MinLength } from "class-validator"; -export class CreateUserDto{ +export class UserDto{ @IsString() - readonly name: string; + name: string; @IsNotEmpty() - @MinLength(10) - readonly password: string; + password: string; } \ No newline at end of file diff --git a/src/users/users.service.ts b/src/users/users.service.ts index af7a994..af3a934 100644 --- a/src/users/users.service.ts +++ b/src/users/users.service.ts @@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './entities/user.entity'; +import { UserDto } from './dto/userDto.dto'; @Injectable() export class UsersService { @@ -19,11 +20,23 @@ export class UsersService { return this.users.save(newUser); } - async updateTokenAndDates(id: number, jwt: string, lastlog: Date, expirationjwt: Date): Promise { - await this.users.update(id, { jwt, lastlog, expirationjwt }); + async update(userId: number, updateUserDto: UserDto): Promise { + await this.users.update(userId, updateUserDto); + return this.users.findOne({where:{userId}}); + } + + async remove(userId: number): Promise { + await this.users.delete(userId); + } + + async updateTokenAndDates(id: number, token: string, lastLogin: Date, jwtExpiry: Date): Promise { + await this.users.update(id, { + jwt:token, + lastlog:lastLogin, + expirationjwt:jwtExpiry, + }); } - }