validate token

This commit is contained in:
TuNombreDeUsuario
2024-06-12 11:40:20 -06:00
parent 3c1f35962b
commit f91ce40371
6 changed files with 68 additions and 30 deletions
+20 -9
View File
@@ -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<string, any>) {
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<string, any>) {
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);
}
}
-1
View File
@@ -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';
+29 -13
View File
@@ -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<User>
) {}
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<User> {
try {
const decoded = this.jwtService.verify(token, {
secret: this.configService.get<string>('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');
}
}
}