Skip to content
This repository was archived by the owner on May 6, 2022. It is now read-only.

Commit 020fd44

Browse files
authored
Merge pull request #78 from Tolfix/dev
v2.3
2 parents 81918f1 + 5910aad commit 020fd44

30 files changed

Lines changed: 208 additions & 161 deletions

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "cpg-api",
3-
"version": "v2.2",
3+
"version": "v2.3",
44
"description": "Central Payment Gateway",
55
"main": "./build/Main.js",
66
"dependencies": {
@@ -28,6 +28,7 @@
2828
"easyinvoice": "^2.0.8",
2929
"express": "^4.17.1",
3030
"express-fileupload": "^1.2.1",
31+
"express-rate-limit": "^6.2.0",
3132
"express-session": "^1.17.2",
3233
"express-swagger-generator": "github:Tolfix/express-swagger-generator",
3334
"graphql-compose": "^9.0.6",

src/Cache/reCache.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,6 @@ export async function reCache_Images()
196196
});
197197
}
198198

199-
/**
200-
* @deprecated
201-
*/
202199
export async function reCache()
203200
{
204201
await reCache_Configs();

src/Database/Models/Transactions.model.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const TransactionsSchema = new Schema
1717
},
1818

1919
customer_uid: {
20-
type: Number,
20+
type: Number || String,
2121
required: true
2222
},
2323

src/Lib/MongoFind.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,32 @@ import { Request } from "express"
33
import { MongooseQueryParser } from "mongoose-query-parser";
44
const p = new MongooseQueryParser();
55

6-
export default function MongoFind<T>(model: Model<T>, query: Request["query"], eQuery?: any)
6+
export default async function MongoFind<T>(model: Model<T>, query: Request["query"], eQuery?: any)
77
{
88
const data = p.parse(query);
99

1010
const b = model.find({
1111
...data.filter,
1212
...eQuery ?? {}
1313
}).sort(data.sort ?? "1").skip(data.skip ?? 0).limit(data.limit ?? 10);
14+
1415
if(data.select)
1516
b.select(data.select);
1617

1718
if(data.populate)
1819
b.populate(data.populate);
1920

20-
return b.exec();
21+
const c = await b.exec();
22+
23+
// Total count
24+
const count = await model.countDocuments({
25+
...data.filter,
26+
...eQuery ?? {},
27+
});
28+
29+
return {
30+
data: c,
31+
totalPages: Math.ceil(count / (data.limit ?? 10)),
32+
totalCount: count,
33+
}
2134
}

src/Middlewares/EnsureAdmin.ts

Lines changed: 48 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -6,66 +6,66 @@ import jwt from "jsonwebtoken";
66
import { JWT_Access_Token } from "../Config";
77
import Logger from "../Lib/Logger";
88

9-
export default function EnsureAdmin(req: Request, res: Response, next: NextFunction)
9+
export default function EnsureAdmin(eR = false)
1010
{
11-
const authHeader = req.headers['authorization'];
12-
if(!authHeader)
13-
return APIError("Missing 'authorization' in header")(res);
14-
15-
const b64auth = (authHeader).split(' ');
16-
17-
if(!b64auth[0].toLocaleLowerCase().match(/basic|bearer/g))
18-
return APIError("Missing 'basic' or 'bearer' in authorization")(res);
19-
20-
if(!b64auth[1])
21-
return APIError("Missing 'buffer' in authorization")(res);
22-
23-
if(b64auth[0].toLocaleLowerCase() === "basic")
11+
return (req: Request, res: Response, next?: NextFunction) =>
2412
{
25-
// Check if buffer, or base64
26-
let [login, password] = (Buffer.isBuffer(b64auth[1]) ? Buffer.from(b64auth[1], 'base64') : b64auth[1]).toString().split(':');
27-
if(login.includes("==") || password.includes("=="))
28-
{
29-
// Assuming base64 string
30-
// Convert it to normal string
31-
Logger.error(`Admin authorizing with base64 string`);
32-
Logger.info(`Encoding admin credentials to normal string`);
33-
login = atob(login);
34-
password = login.split(":")[1];
35-
login = login.split(":")[0];
36-
}
37-
38-
Logger.warning(`Authoring admin with username: ${login}`);
3913

40-
return bcrypt.compare(password, (CacheAdmin.get(getAdminByUsername(login) ?? "ADM_")?.["password"]) ?? "", (err, match) =>
14+
const authHeader = req.headers['authorization'];
15+
if(!authHeader)
16+
return eR ? Promise.resolve(false) : APIError("Missing 'authorization' in header")(res);
17+
18+
const b64auth = (authHeader).split(' ');
19+
20+
if(!b64auth[0].toLocaleLowerCase().match(/basic|bearer/g))
21+
return eR ? Promise.resolve(false) : APIError("Missing 'basic' or 'bearer' in authorization")(res);
22+
23+
if(!b64auth[1])
24+
return eR ? Promise.resolve(false) : APIError("Missing 'buffer' in authorization")(res);
25+
26+
if(b64auth[0].toLocaleLowerCase() === "basic")
4127
{
28+
// Check if buffer, or base64
29+
let [login, password] = (Buffer.isBuffer(b64auth[1]) ? Buffer.from(b64auth[1], 'base64') : b64auth[1]).toString().split(':');
30+
if(login.includes("==") || password.includes("=="))
31+
{
32+
// Assuming base64 string
33+
// Convert it to normal string
34+
Logger.error(`Admin authorizing with base64 string`);
35+
Logger.info(`Encoding admin credentials to normal string`);
36+
login = atob(login);
37+
password = login.split(":")[1];
38+
login = login.split(":")[0];
39+
}
40+
41+
eR ? null : Logger.warning(`Authoring admin with username: ${login}`);
42+
43+
const match = bcrypt.compare(password, (CacheAdmin.get(getAdminByUsername(login) ?? "ADM_")?.["password"]) ?? "")
4244
if(!match)
4345
{
44-
Logger.warning(`Authorization failed for admin with username: ${login}`);
45-
return APIError("Unauthorized admin", 403)(res);
46+
eR ? null : Logger.warning(`Authorization failed for admin with username: ${login}`);
47+
return eR ? Promise.resolve(false) : APIError("Unauthorized admin", 403)(res);
4648
}
4749

48-
return next();
49-
});
50-
}
51-
52-
if(b64auth[0].toLocaleLowerCase() === "bearer")
53-
{
54-
const token = (Buffer.isBuffer(b64auth[1]) ? Buffer.from(b64auth[1], 'base64') : b64auth[1]).toString();
55-
Logger.warning(`Authoring admin with token: ${token}`);
56-
jwt.verify(token, JWT_Access_Token, (err, payload) =>
50+
return eR ? Promise.resolve(true) : next?.();
51+
}
52+
53+
if(b64auth[0].toLocaleLowerCase() === "bearer")
5754
{
58-
if(err || !payload)
55+
const token = (Buffer.isBuffer(b64auth[1]) ? Buffer.from(b64auth[1], 'base64') : b64auth[1]).toString();
56+
eR ? null : Logger.warning(`Authoring admin with token: ${token}`);
57+
const payload = jwt.verify(token, JWT_Access_Token);
58+
if(!payload)
5959
{
60-
Logger.warning(`Authorization failed for admin with token: ${token}`);
61-
return APIError("Unauthorized admin", 403)(res);
60+
eR ? null : Logger.warning(`Authorization failed for admin with token: ${token}`);
61+
return eR ? Promise.resolve(false) : APIError("Unauthorized admin", 403)(res);
6262
}
6363

64-
Logger.warning(`Authorized admin with token: ${token}`);
64+
eR ? null : Logger.warning(`Authorized admin with token: ${token}`);
6565

66-
return next();
67-
});
66+
return eR ? Promise.resolve(true) : next?.();
67+
}
68+
69+
return Promise.resolve(false);
6870
}
69-
70-
return null;
7171
}

src/Middlewares/EnsureAuth.ts

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ import { JWT_Access_Token } from "../Config";
44
import Logger from "../Lib/Logger";
55
import { APIError } from "../Lib/Response";
66

7-
export default function EnsureAuth()
7+
export default function EnsureAuth(eR = false)
88
{
9-
return (req: Request, res: Response, next: NextFunction) =>
9+
return (req: Request, res: Response, next?: NextFunction) =>
1010
{
1111
const authHeader = req.headers['authorization'];
1212
const tokenQuery = req.query.access_token;
1313
if(!authHeader && !tokenQuery)
14-
return APIError({
14+
return eR ? Promise.resolve(false) : APIError({
1515
text: "Missing 'authorization' in header"
1616
})(res);
1717

@@ -24,13 +24,13 @@ export default function EnsureAuth()
2424

2525
// @ts-ignore
2626
if(!b64auth[0].toLocaleLowerCase().match(/query|bearer/g))
27-
return APIError({
27+
return eR ? Promise.resolve(false) : APIError({
2828
text: "Missing 'basic' or 'bearer' in authorization"
2929
})(res);
3030

3131
// @ts-ignore
3232
if(!b64auth[1])
33-
return APIError({
33+
return eR ? Promise.resolve(false) : APIError({
3434
text: "Missing 'buffer' in authorization"
3535
})(res);
3636

@@ -39,22 +39,21 @@ export default function EnsureAuth()
3939
{
4040
// @ts-ignore
4141
const token = (Buffer.isBuffer(b64auth[1]) ? Buffer.from(b64auth[1], 'base64') : b64auth[1]).toString();
42-
jwt.verify(token, JWT_Access_Token, (err, payload) =>
43-
{
44-
if (err)
45-
return APIError(`Unauthorized user.`, 403)(res);
46-
47-
// @ts-ignore
48-
if(!payload?.data?.id)
49-
return APIError(`Wrong payload.`, 403)(res);
50-
51-
//@ts-ignore
52-
req.customer = payload.data;
53-
// @ts-ignore
54-
Logger.api(`Authorizing`, payload.data);
55-
56-
return next();
57-
});
42+
43+
const payload = jwt.verify(token, JWT_Access_Token);
44+
if (!payload)
45+
return eR ? Promise.resolve(false) : APIError(`Unauthorized user.`, 403)(res);
46+
47+
// @ts-ignore
48+
if(!payload?.data?.id)
49+
return eR ? Promise.resolve(false) : APIError(`Wrong payload.`, 403)(res);
50+
51+
//@ts-ignore
52+
req.customer = payload.data;
53+
// @ts-ignore
54+
eR ? null : Logger.api(`Authorizing`, payload.data);
55+
56+
return eR ? Promise.resolve(true) : next?.();
5857
}
5958

6059

src/Models/BaseModelAPI.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Request } from "express";
1+
import { Request, Response } from "express";
22
import MongoFind from "../Lib/MongoFind";
33

44
export default class BaseModelAPI<IModel extends { uid: string }>
@@ -42,19 +42,23 @@ export default class BaseModelAPI<IModel extends { uid: string }>
4242
});
4343
}
4444

45-
public findAll(query: Request["query"]): Promise<Array<IModel>>
45+
public findAll(query: Request["query"], res: Response): Promise<Array<IModel>>
4646
{
4747
return new Promise((resolve, reject) =>
4848
{
49-
MongoFind(this.iModel, query).then((result: any) =>
49+
MongoFind(this.iModel, query).then((result) =>
5050
{
51-
const r = result.map((i: any) =>
51+
const r = result.data.map((i: any) =>
5252
{
5353
const r = i.toJSON();
5454
//@ts-ignore
5555
delete r.__v;
5656
return r;
5757
});
58+
59+
res.setHeader("X-Total-Pages", result.totalPages);
60+
res.setHeader("X-Total", result.totalCount);
61+
5862
resolve(r);
5963
}).catch(reject);
6064
});

src/Server/Routes/v1/Admin/Admin.config.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export = class AdminRouter
1919
* @group Admin - Admin routes
2020
* @security JWT
2121
*/
22-
this.router.get("/validate", EnsureAdmin, (req, res) =>
22+
this.router.get("/validate", EnsureAdmin(), (req, res) =>
2323
{
2424
APISuccess("Authenticated", 202)(res);
2525
});
@@ -32,7 +32,7 @@ export = class AdminRouter
3232
* @returns {APIError} 404 - Failed
3333
* @security Basic
3434
*/
35-
this.router.post("/auth", EnsureAdmin, (req, res) =>
35+
this.router.post("/auth", EnsureAdmin(), (req, res) =>
3636
{
3737
const token = jwt.sign({
3838
data: 'admin',

src/Server/Routes/v2/Categories/Categories.config.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,22 @@ export = class CategoryRouter
2525
])
2626

2727
this.router.post("/", [
28-
EnsureAdmin,
28+
EnsureAdmin(),
2929
CategoryController.insert
3030
]);
3131

3232
this.router.patch("/:uid", [
33-
EnsureAdmin,
33+
EnsureAdmin(),
3434
CategoryController.patch
3535
]);
3636

3737
this.router.put("/:uid", [
38-
EnsureAdmin,
38+
EnsureAdmin(),
3939
CategoryController.patch
4040
]);
4141

4242
this.router.delete("/:uid", [
43-
EnsureAdmin,
43+
EnsureAdmin(),
4444
CategoryController.removeById
4545
]);
4646
}

src/Server/Routes/v2/Categories/Categories.controller.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ function getByUid(req: Request, res: Response)
3333

3434
function list(req: Request, res: Response)
3535
{
36-
API.findAll(req.query).then((result: any) =>
36+
API.findAll(req.query, res).then((result: any) =>
3737
{
3838
APISuccess(result)(res)
3939
})

0 commit comments

Comments
 (0)