bid-tool/auto-bid-server/src/modules/auth/middlewares/client-authentication.middl...

45 lines
1.1 KiB
TypeScript

// auth.middleware.ts
import { GenerateKeysService } from '@/modules/admins/services/generate-key.service';
import AppResponse from '@/response/app-response';
import {
HttpStatus,
Injectable,
NestMiddleware,
UnauthorizedException,
} from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
@Injectable()
export class ClientAuthenticationMiddleware implements NestMiddleware {
constructor(private readonly generateKeysService: GenerateKeysService) {}
async getKey(key: string) {
if (!key) return null;
const data = await this.generateKeysService.generateKeyRepo.findOne({
where: { client_key: key },
});
return data;
}
async use(req: Request, res: Response, next: NextFunction) {
const client_key: string = req.headers.authorization;
const key = await this.getKey(client_key);
if (!key) {
return next(
new UnauthorizedException(
AppResponse.toResponse(null, {
message: 'Unauthorized',
status_code: HttpStatus.UNAUTHORIZED,
}),
),
);
}
next();
}
}