Skip to content

Commit 6591d99

Browse files
committed
chore: add metrics to auth middleware
1 parent b5fcf87 commit 6591d99

File tree

3 files changed

+140
-11
lines changed

3 files changed

+140
-11
lines changed

package-lock.json

+124-9
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
"nestjs-throttler-storage-redis": "^0.3.3",
5656
"pino-http": "^8.3.3",
5757
"pino-pretty": "^9.3.0",
58+
"readmeio": "^6.1.0",
5859
"redis": "^4.6.5",
5960
"reflect-metadata": "^0.1.13",
6061
"release-please": "^15.8.0",

src/auth/middleware/auth.middleware.ts

+15-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/commo
33
import { AuthService } from '../auth.service';
44
import { FastifyReply, FastifyRequest } from 'fastify';
55
import * as ApiKey from 'uuid-apikey';
6+
import { log } from 'readmeio';
67

78
@Injectable()
89
export class AuthMiddleware implements NestMiddleware {
@@ -11,15 +12,27 @@ export class AuthMiddleware implements NestMiddleware {
1112
async use(req: FastifyRequest['raw'], res: FastifyReply['raw'], next: () => void) {
1213
const token = req?.headers['x-api-key'] || req['query']['token'];
1314

14-
if (!token) throw new UnauthorizedException('В запросе не указан токен!');
15+
if (!token) {
16+
log(process.env.README_API_KEY, req, res, { apiKey: null, label: null });
17+
18+
throw new UnauthorizedException('В запросе не указан токен!');
19+
}
1520
// @ts-ignore
16-
if (!ApiKey.isAPIKey(token)) throw new UnauthorizedException('Переданный токен некорректен!');
21+
if (!ApiKey.isAPIKey(token)) {
22+
log(process.env.README_API_KEY, req, res, { apiKey: null, label: null });
23+
24+
throw new UnauthorizedException('Переданный токен некорректен!');
25+
}
1726

1827
const user = await this.authService.findUserByToken(token);
28+
1929
const isLimitNotExceeded = await this.authService.checkAndDecreaseLimit(token);
2030

31+
log(process.env.README_API_KEY, req, res, { apiKey: token, label: user.username || String(user.userId) });
32+
2133
req['user'] = user;
2234
req['isLimitNotExceeded'] = isLimitNotExceeded;
35+
2336
next();
2437
}
2538
}

0 commit comments

Comments
 (0)