import { BindingScope, injectable } from '@loopback/core'; import { BlockedUserRepository } from '../repositories'; import { repository } from '@loopback/repository'; interface BlockedUser { key: string; timeoutId: NodeJS.Timeout; startTime: number; // Store the timestamp when the timeout was set duration: number; // Store the duration of the timeout in milliseconds } @injectable({ scope: BindingScope.SINGLETON }) export class UserBlockingService { constructor( @repository(BlockedUserRepository) public blockedUserRepository: BlockedUserRepository, ) { } async blockUser(ip: string, device: string, timeoutDuration: number): Promise { try { const blockedUser = await this.blockedUserRepository.findOne({ where: { device: device, user_ip: ip } }) if (blockedUser) { await this.blockedUserRepository.updateById(blockedUser.id, { block_start_time: Date.now().toString(), duration: timeoutDuration, count: blockedUser!.count! + 1, is_blocked: true }) } else { await this.blockedUserRepository.create({ user_ip: ip, device: device, block_start_time: Date.now().toString(), duration: timeoutDuration, is_blocked: true, count: 1 }) } } catch (error) { console.error("Error in blockUser:", error); } } async getTimeUntilUnblock(ip: string, device: string): Promise { try { const blockedUser = await this.blockedUserRepository.findOne({ where: { device: device, user_ip: ip, is_blocked: true } }); if (blockedUser) { const currentTime = Date.now(); const elapsedTime = currentTime - Number(blockedUser.block_start_time); const remainingTime = blockedUser.duration - elapsedTime; if (remainingTime > 0) { const hours = Math.floor(remainingTime / (1000 * 60 * 60)); const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60)); let formattedTime = ''; if (hours > 0) { formattedTime += `${hours} hour${hours !== 1 ? 's' : ''}`; } if (hours > 0 && minutes > 0) { formattedTime += ' and '; } if (minutes > 0) { formattedTime += `${minutes} minute${minutes !== 1 ? 's' : ''}`; } return formattedTime; } else { await this.blockedUserRepository.updateById(blockedUser.id, { is_blocked: false }) return undefined; } } } catch (error) { console.error("Error in checking block user:", error); } return undefined; } }