Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Register 70%, ajustes realizables #7

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,25 @@ import { AuthService } from './auth.service';
import { CreateAuthDto } from './dto/create-auth.dto';
import { AuthGuard } from './guard/auth.guard';
import { Request } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}

@Post('login')
create(@Body() createAuthDto: CreateAuthDto) {
createJWT(@Body() createAuthDto: CreateAuthDto) {
console.log('createAuthDto', createAuthDto);
return this.authService.create(createAuthDto);
return this.authService.createJWT(createAuthDto);
}

@Post('register')
createUser(@Body() createUserDto: CreateUserDto) {
return this.authService.createUser(createUserDto);
}

@UseGuards(AuthGuard)
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
}
}
63 changes: 57 additions & 6 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';

import { Injectable, UnauthorizedException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateAuthDto } from './dto/create-auth.dto';
import { User } from 'src/model/user.entity';
import { JwtService } from '@nestjs/jwt';
import { CreateUserDto } from './dto/create-user.dto';
import * as bcrypt from 'bcrypt';

@Injectable()
export class AuthService {
Expand All @@ -13,16 +16,23 @@ export class AuthService {
private readonly jwtService: JwtService,
) {}

async create(createAuthDto: CreateAuthDto): Promise<{ access_token: string }> {
async comparePassword(plainPassword, hashedPassword) {
const match = await bcrypt.compare(plainPassword, hashedPassword);
return match;
}

async createJWT(createAuthDto: CreateAuthDto): Promise<{ access_token: string }> {
const existingUser = await this.userRepository.findOne({
where: {
dni: createAuthDto.dni,
password: createAuthDto.password,
},
});
if (!existingUser) {
throw new UnauthorizedException('No existe el usuario.');
const existingPassword = await bcrypt.compare(createAuthDto.password, existingUser.password);

if (!existingUser || !existingPassword) {
throw new UnauthorizedException('No existe el usuario o la contraseña es incorrecta.');
}

const payload = {
dni: existingUser.dni,
name: existingUser.name,
Expand All @@ -35,4 +45,45 @@ export class AuthService {
access_token: this.jwtService.sign(payload),
};
}
}

async createUser(createUserDto: CreateUserDto) {
const existingUser1 = await this.userRepository.findOne({
where: {
dni: createUserDto.dni,
},
});
const existingUser2 = await this.userRepository.findOne({
where: {
email: createUserDto.email,
},
});
if (existingUser1) {
throw new ConflictException('El DNI ya está registrado.');
}
if (existingUser2) {
throw new ConflictException('El Email ya está registrado.');
}
const hashedPassword = await bcrypt.hash(createUserDto.password, 10);

await this.userRepository.insert({
dni: createUserDto.dni,
password: hashedPassword,
name: createUserDto.name,
lastname: createUserDto.lastname,
email: createUserDto.email,
image_url: createUserDto.image_url,
created_at: Date(),
updated_at: Date(),
});

const payload = {
dni: createUserDto.dni,
name: createUserDto.name,
lastname: createUserDto.lastname,
email: createUserDto.email,
image_url: createUserDto.image_url,
};
const access_token = this.jwtService.sign(payload);
return { access_token };
}
}
34 changes: 34 additions & 0 deletions src/auth/dto/create-user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { IsString, IsNotEmpty, IsEmail, IsUrl, IsOptional, Matches } from 'class-validator';

export class CreateUserDto {
@IsString()
@IsNotEmpty({ message: 'El DNI no puede estar vacío' })
@Matches(/^\d{8}$/, { message: 'El DNI debe tener exactamente 8 dígitos' })
dni: string;

@IsString()
@IsNotEmpty({ message: 'El nombre no puede estar vacío' })
name: string;

@IsString()
@IsNotEmpty({ message: 'El apellido no puede estar vacío' })
lastname: string;

@IsEmail({}, { message: 'Debe ser un correo electrónico válido' })
@IsNotEmpty({ message: 'El correo electrónico no puede estar vacío' })
email: string;

@IsString()
@IsNotEmpty({ message: 'La contraseña no puede estar vacía' })
password: string;

@IsUrl({}, { message: 'Debe ser una URL válida' })
@IsOptional()
image_url?: string;

@IsOptional()
created_at?: Date = new Date();

@IsOptional()
updated_at?: Date = new Date();
}
Loading