Tafar commited on
Commit
0a764cc
·
1 Parent(s): 45cdeaf

Upload 2 files

Browse files
service_src_middleware_auth.ts ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { isNotEmptyString } from '../utils/is'
2
+
3
+ const auth = async (req, res, next) => {
4
+ const AUTH_SECRET_KEY = process.env.AUTH_SECRET_KEY
5
+ if (isNotEmptyString(AUTH_SECRET_KEY)) {
6
+ try {
7
+ const Authorization = req.header('Authorization')
8
+ if (!Authorization || Authorization.replace('Bearer ', '').trim() !== AUTH_SECRET_KEY.trim())
9
+ throw new Error('Error: 无访问权限 | No access rights')
10
+ next()
11
+ }
12
+ catch (error) {
13
+ res.send({ status: 'Unauthorized', message: error.message ?? 'Please authenticate.', data: null })
14
+ }
15
+ }
16
+ else {
17
+ next()
18
+ }
19
+ }
20
+
21
+ export { auth }
service_src_middleware_limiter.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { rateLimit } from 'express-rate-limit'
2
+ import { isNotEmptyString } from '../utils/is'
3
+
4
+ const MAX_REQUEST_PER_HOUR = process.env.MAX_REQUEST_PER_HOUR
5
+
6
+ const maxCount = (isNotEmptyString(MAX_REQUEST_PER_HOUR) && !isNaN(Number(MAX_REQUEST_PER_HOUR)))
7
+ ? parseInt(MAX_REQUEST_PER_HOUR)
8
+ : 0 // 0 means unlimited
9
+
10
+ const limiter = rateLimit({
11
+ // windowMs: 60 * 60 * 1000, // Maximum number of accesses within an hour
12
+ max: maxCount,
13
+ statusCode: 200, // 200 means success,but the message is 'Too many request from this IP in 1 hour'
14
+ message: async (req, res) => {
15
+ res.send({ status: 'Fail', message: 'Giới hạn trò chuyện trong 1h.', data: null })
16
+ },
17
+ })
18
+
19
+ export { limiter }