Skip to content
This repository has been archived by the owner on Dec 10, 2024. It is now read-only.

Commit

Permalink
feat / auth module (auth.login.dto, auth.register.dto, auth.controlle…
Browse files Browse the repository at this point in the history
…r, auth.service) #26
  • Loading branch information
exogenesispr committed Nov 18, 2024
1 parent 29a1f17 commit 4191e4f
Show file tree
Hide file tree
Showing 10 changed files with 434 additions and 3 deletions.
126 changes: 123 additions & 3 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.3.0",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mapped-types": "^2.0.6",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^8.0.7",
Expand Down
20 changes: 20 additions & 0 deletions src/modules/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';

describe('AuthController', () => {
let controller: AuthController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
providers: [AuthService],
}).compile();

controller = module.get<AuthController>(AuthController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
30 changes: 30 additions & 0 deletions src/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Controller, Post, Body, Res, HttpCode, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthLoginDto } from './dto/auth.login.dto';
import { AuthRegisterDto } from './dto/auth.register.dto';
import { ApiBody, ApiTags } from '@nestjs/swagger';

@ApiTags('auth')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) { }

@Post('register')
@ApiBody({
description: 'Cuerpo de la solicitud para registro de nuevo usuario',
type: AuthRegisterDto,
})
async create(@Res({ passthrough: true }) res: Response, @Body() authRegisterDto: AuthRegisterDto) {
return await this.authService.register(authRegisterDto);
}

@Post('login')
@ApiBody({
description: 'Cuerpo de solicitud para iniciar sesión',
type: AuthLoginDto,
})
@HttpCode(HttpStatus.OK)
async login(@Body() authLoginDto: AuthLoginDto) {
return await this.authService.login(authLoginDto)
}
}
9 changes: 9 additions & 0 deletions src/modules/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';

@Module({
controllers: [AuthController],
providers: [AuthService],
})
export class AuthModule {}
18 changes: 18 additions & 0 deletions src/modules/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';

describe('AuthService', () => {
let service: AuthService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();

service = module.get<AuthService>(AuthService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
98 changes: 98 additions & 0 deletions src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { ConflictException, Injectable, InternalServerErrorException, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt'
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuthRegisterDto } from './dto/auth.register.dto';
import { AuthLoginDto } from './dto/auth.login.dto';
import * as bcrypt from 'bcryptjs'
import { User } from '../users/entities/user.entity';

@Injectable()
export class AuthService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
private readonly jwtService: JwtService,
) { }

async register(authRegisterDto: AuthRegisterDto): Promise<any> {
const { name, username, email, password, confirmPassword, tel } = authRegisterDto

try {

if (password !== confirmPassword) {
throw new ConflictException('Contraseña y confirmar contraseña no coinciden')
}

const existingUser = await this.userRepository.findOne({
where: [{ email }, { username }]
})

if (existingUser) {
throw new ConflictException(
'El correo o el nombre de usuario ya han sido usados.'
)
}

const hashPassword: string = await bcrypt.hash(password, 10)

const user = this.userRepository.create({
name,
username,
email,
password: hashPassword,
tel,
})

await this.userRepository.save(user)

return { message: 'Usuario registrado correctamente' }

} catch (error) {
throw new InternalServerErrorException('Ha surgido un error inesperado en el registro',)
}
}

async login(authLoginDto: AuthLoginDto): Promise<any> {
const { email, password } = authLoginDto

try {

const user = await this.userRepository.findOne({
where: { email }
})

if (!user) {
throw new UnauthorizedException('Los datos ingresados no son correctos.')
}

const isPasswordValid = await bcrypt.compare(password, user.password)

if (!isPasswordValid) {
throw new UnauthorizedException('Los datos ingresados no son correctos.')
}

const payload = { username: user.username, sub: user.id }
const token = this.jwtService.sign(payload)

return {
userData: {
id: user.id,
name: user.name,
username: user.username,
email: user.email,
tel: user.tel,
age: user.age,
gender: user.gender,
role: user.role,
preferences: user.preferences,
travelHistory: user.travelHistory,
favorites: user.favorites,
},
token,
}
} catch (error) {
throw new InternalServerErrorException('Un error ha surgido en el inicio de sesión')
}
}
}
Loading

0 comments on commit 4191e4f

Please sign in to comment.