This repository has been archived by the owner on Dec 10, 2024. It is now read-only.
generated from IgrowkerTraining/template-express-ts
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat / auth module (auth.login.dto, auth.register.dto, auth.controlle…
…r, auth.service) #26
- Loading branch information
1 parent
29a1f17
commit 4191e4f
Showing
10 changed files
with
434 additions
and
3 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | ||
} | ||
} | ||
} |
Oops, something went wrong.