This commit is contained in:
IO
2024-06-12 21:33:20 -06:00
8 changed files with 69 additions and 32 deletions
+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{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');
}
}
}