29 lines
791 B
TypeScript
29 lines
791 B
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { ApiKeyEntity } from '@/entities/apiKey.entity';
|
|
import * as crypto from 'crypto';
|
|
|
|
@Injectable()
|
|
export class AuthService {
|
|
constructor(
|
|
@InjectRepository(ApiKeyEntity)
|
|
private readonly apiKeyRepository: Repository<ApiKeyEntity>,
|
|
) {}
|
|
|
|
async isAllowed(apiKey: string, apiSecret: string): Promise<boolean> {
|
|
const apiKeyEntity = await this.apiKeyRepository.findOneBy({
|
|
apiKey,
|
|
});
|
|
|
|
if (!apiKeyEntity || !apiKeyEntity.enabled) {
|
|
return false;
|
|
}
|
|
|
|
const hmac = crypto.createHmac('sha256', apiSecret);
|
|
const digest = hmac.update(apiKey).digest('hex');
|
|
|
|
return digest === apiKeyEntity.digest;
|
|
}
|
|
}
|