48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
import { Cache } from 'cache-manager';
|
|
import { TokenService } from '../utility/services/token.service';
|
|
|
|
export interface IPLimit {
|
|
ip: string;
|
|
attempts: number;
|
|
reported: boolean;
|
|
}
|
|
|
|
@Injectable()
|
|
export class IPLimitService {
|
|
constructor(
|
|
@Inject(CACHE_MANAGER)
|
|
private readonly cache: Cache,
|
|
private readonly token: TokenService,
|
|
) {}
|
|
|
|
public async getAddressLimit(ip: string) {
|
|
const ipHash = this.token.insecureHash(ip);
|
|
const entry = await this.cache.get<IPLimit>(`iplimit-${ipHash}`);
|
|
if (!entry) return null;
|
|
return entry;
|
|
}
|
|
|
|
public async limitUntil(ip: string, expires: number, reported = false) {
|
|
const ipHash = this.token.insecureHash(ip);
|
|
const existing = await this.cache.get<IPLimit>(`iplimit-${ipHash}`);
|
|
if (existing) {
|
|
existing.attempts++;
|
|
if (reported) existing.reported = true;
|
|
await this.cache.set(`iplimit-${ipHash}`, existing, expires + Date.now());
|
|
return existing;
|
|
}
|
|
|
|
const newObj = {
|
|
ip,
|
|
attempts: 0,
|
|
reported,
|
|
};
|
|
|
|
await this.cache.set(`iplimit-${ipHash}`, newObj, expires + Date.now());
|
|
|
|
return newObj;
|
|
}
|
|
}
|