revision
This commit is contained in:
+1
-1
@@ -3,8 +3,8 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { UsersModule } from './users/users.module';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { UsersModule } from './users/users.module';
|
||||
import { User } from "./users/entities/user.entity";
|
||||
|
||||
@Module({
|
||||
|
||||
+2
-3
@@ -1,11 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
console.log("Todo bien")
|
||||
console.log("it's ok ")
|
||||
|
||||
return 'Hello World!';
|
||||
return "hei verden";
|
||||
}
|
||||
}
|
||||
|
||||
+20
-10
@@ -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,35 +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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
@@ -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{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');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { IsEmail, IsNotEmpty, IsString, MinLength } from "class-validator";
|
||||
|
||||
export class CreateUserDto{
|
||||
export class UserDto{
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
@@ -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<void> {
|
||||
await this.users.update(id, { jwt, lastlog, expirationjwt });
|
||||
async update(userId: number, updateUserDto: UserDto): Promise<User> {
|
||||
await this.users.update(userId, updateUserDto);
|
||||
return this.users.findOne({where:{userId}});
|
||||
}
|
||||
|
||||
async remove(userId: number): Promise<void> {
|
||||
await this.users.delete(userId);
|
||||
}
|
||||
|
||||
async updateTokenAndDates(id: number, token: string, lastLogin: Date, jwtExpiry: Date): Promise<void> {
|
||||
await this.users.update(id, {
|
||||
jwt:token,
|
||||
lastlog:lastLogin,
|
||||
expirationjwt:jwtExpiry,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user