speedly 2.0.38 → 2.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +470 -171
  2. package/dist/cjs/config/init.js +2 -2
  3. package/dist/cjs/kit/db/db.js +16 -0
  4. package/dist/cjs/model/translation.d.ts +37 -25
  5. package/dist/cjs/util/translator.d.ts +1 -1
  6. package/dist/config/init.d.ts +23 -0
  7. package/dist/config/init.js +93 -0
  8. package/dist/document/document.d.ts +5 -0
  9. package/dist/document/document.js +270 -0
  10. package/dist/document/index.d.ts +2 -0
  11. package/dist/document/index.js +7 -0
  12. package/dist/document/parser.d.ts +1 -0
  13. package/dist/document/parser.js +11 -0
  14. package/dist/esm/config/init.js +2 -2
  15. package/dist/esm/kit/db/db.js +16 -0
  16. package/dist/esm/model/translation.d.ts +37 -25
  17. package/dist/esm/util/translator.d.ts +1 -1
  18. package/dist/index.d.ts +5 -0
  19. package/dist/index.js +13 -0
  20. package/dist/{cjs → kit}/auth/auth.js +1 -1
  21. package/dist/{cjs → kit}/db/db.d.ts +15 -0
  22. package/dist/{cjs → kit}/db/db.js +44 -19
  23. package/dist/kit/index.d.ts +5 -0
  24. package/dist/kit/index.js +14 -0
  25. package/dist/{cjs → kit}/uploader/uploader.d.ts +2 -2
  26. package/dist/{esm → kit}/uploader/uploader.js +22 -17
  27. package/dist/model/index.d.ts +2 -0
  28. package/dist/model/index.js +8 -0
  29. package/dist/model/translation.d.ts +71 -0
  30. package/dist/model/translation.js +13 -0
  31. package/dist/modules/index.d.ts +2 -0
  32. package/dist/modules/index.js +8 -0
  33. package/dist/modules/translation/translation.routes.d.ts +2 -0
  34. package/dist/modules/translation/translation.routes.js +24 -0
  35. package/dist/modules/translation/translation.validator.d.ts +15 -0
  36. package/dist/modules/translation/translation.validator.js +22 -0
  37. package/dist/util/getConfig.d.ts +4 -0
  38. package/dist/util/getConfig.js +40 -0
  39. package/dist/util/index.d.ts +2 -0
  40. package/dist/util/index.js +8 -0
  41. package/dist/util/makeOptional.d.ts +10 -0
  42. package/dist/util/makeOptional.js +47 -0
  43. package/dist/util/strToObj.d.ts +2 -0
  44. package/dist/util/strToObj.js +9 -0
  45. package/dist/util/translator.d.ts +2 -0
  46. package/dist/util/translator.js +74 -0
  47. package/examples/blog-routes/blog/blog.routes.js +15 -0
  48. package/examples/blog-routes/blog/blog.validator.js +35 -0
  49. package/examples/blog-routes/role/role.routes.js +14 -0
  50. package/examples/blog-routes/role/role.validator.js +28 -0
  51. package/examples/blog-routes/user/user.controller.js +97 -0
  52. package/examples/blog-routes/user/user.routes.js +18 -0
  53. package/examples/blog-routes/user/user.validator.js +53 -0
  54. package/package.json +65 -66
  55. package/dist/cjs/auth/auth2.d.ts +0 -18
  56. package/dist/cjs/auth/auth2.js +0 -93
  57. package/dist/cjs/uploader/uploader.js +0 -145
  58. package/dist/cjs/yup.config.d.ts +0 -2
  59. package/dist/cjs/yup.config.js +0 -24
  60. package/dist/esm/auth/auth.d.ts +0 -3
  61. package/dist/esm/auth/auth.js +0 -38
  62. package/dist/esm/auth/types.d.ts +0 -19
  63. package/dist/esm/auth/types.js +0 -2
  64. package/dist/esm/db/db.d.ts +0 -182
  65. package/dist/esm/db/db.js +0 -594
  66. package/dist/esm/db/utils.d.ts +0 -3
  67. package/dist/esm/db/utils.js +0 -15
  68. package/dist/esm/uploader/uploader.d.ts +0 -24
  69. package/dist/esm/validator/validator.d.ts +0 -9
  70. package/dist/esm/validator/validator.js +0 -36
  71. /package/dist/{cjs → kit}/auth/auth.d.ts +0 -0
  72. /package/dist/{cjs → kit}/auth/types.d.ts +0 -0
  73. /package/dist/{cjs → kit}/auth/types.js +0 -0
  74. /package/dist/{cjs → kit}/db/utils.d.ts +0 -0
  75. /package/dist/{cjs → kit}/db/utils.js +0 -0
  76. /package/dist/{cjs → kit}/validator/validator.d.ts +0 -0
  77. /package/dist/{cjs → kit}/validator/validator.js +0 -0
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.default = default_1;
37
+ const yup = __importStar(require("yup"));
38
+ function default_1(schema) {
39
+ if (schema.fields) {
40
+ const shape = {};
41
+ for (const key in schema.fields) {
42
+ shape[key] = schema.fields[key].optional();
43
+ }
44
+ return yup.object().shape(shape);
45
+ }
46
+ return schema;
47
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: (value: string, falseValue?: number, splitValue?: string) => {};
2
+ export default _default;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = (value, falseValue = -1, splitValue = ' ') => {
4
+ return value.split(splitValue).reduce((prev, curr) => {
5
+ if (curr[0] == '-')
6
+ return { ...prev, [curr.slice(1)]: falseValue };
7
+ return { ...prev, [curr]: 1 };
8
+ }, {});
9
+ };
@@ -0,0 +1,2 @@
1
+ declare const _default: (text?: string, lang?: string) => Promise<unknown>;
2
+ export default _default;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const axios_1 = __importDefault(require("axios"));
7
+ const translation_1 = __importDefault(require("./../model/translation"));
8
+ const TIMEOUT = 5000;
9
+ const getConfig_1 = __importDefault(require("./getConfig"));
10
+ const configs = { ...(0, getConfig_1.default)("translate") };
11
+ async function firstSuccessful(promises) {
12
+ return new Promise((resolve, reject) => {
13
+ let rejections = 0;
14
+ const total = promises.length;
15
+ promises.forEach((p) => {
16
+ Promise.resolve(p)
17
+ .then(resolve)
18
+ .catch(() => {
19
+ rejections++;
20
+ if (rejections === total) {
21
+ reject(new Error("همه ترجمه‌ها شکست خوردند"));
22
+ }
23
+ });
24
+ });
25
+ });
26
+ }
27
+ exports.default = async (text = "unspecified text", lang = "fa") => {
28
+ const formattedText = text
29
+ .replaceAll(/[\-\_]/g, " ")
30
+ .replaceAll(/[A-Z]/g, " $&");
31
+ const translationDoc = await translation_1.default.findOne({
32
+ text: formattedText,
33
+ lang,
34
+ });
35
+ if (translationDoc)
36
+ return translationDoc.translatedText;
37
+ const translationPromises = [];
38
+ translationPromises.push((async () => {
39
+ const res = await axios_1.default.get(`https://655.mtis.workers.dev/translate?text=${encodeURIComponent(formattedText)}&source_lang=en&target_lang=${lang}`, { timeout: TIMEOUT });
40
+ if (!res.data?.response?.translated_text)
41
+ throw new Error("Translation failed");
42
+ return res.data.response.translated_text;
43
+ })());
44
+ translationPromises.push((async () => {
45
+ const res = await axios_1.default.post("https://api.one-api.ir/translate/v1/microsoft", {
46
+ text: formattedText,
47
+ target: lang,
48
+ }, {
49
+ timeout: TIMEOUT,
50
+ headers: {
51
+ "one-api-token": "783122:68a02b5c4dcee",
52
+ },
53
+ });
54
+ if (res.data.status === 200) {
55
+ return res.data.result;
56
+ }
57
+ else {
58
+ throw new Error(res.data.message);
59
+ }
60
+ })());
61
+ try {
62
+ const result = await firstSuccessful(translationPromises);
63
+ await translation_1.default.create({
64
+ text: formattedText,
65
+ lang,
66
+ translatedText: result,
67
+ });
68
+ return result;
69
+ }
70
+ catch (err) {
71
+ console.error("translator error:", err);
72
+ return formattedText;
73
+ }
74
+ };
@@ -0,0 +1,15 @@
1
+ const express = require('express');
2
+ const { auth, db, validator } = require('speedly/kit');
3
+
4
+ const v = require('./blog.validator');
5
+
6
+ const router = express.Router();
7
+
8
+ router.route('/').get(db('blog').find().populate([{ path: 'author_id', select: '-password -phone' }, 'thumbnail_id']))
9
+ .post(auth.admin(), validator(v.post), db('blog').create(req => ({ author_id: req.user._id })))
10
+
11
+ router.get('/:slug', db('blog').findOneAndUpdate(req => ({ slug: req.params.slug }, { $inc: { views: 1 } })).populate([{ path: 'author_id', select: '-password -phone' }, 'thumbnail_id']))
12
+ router.route('/:id').put(auth.admin(), validator(v.put), db('blog').findByIdAndUpdate())
13
+ .delete(auth.admin(), validator(v.delete), db('blog').findByIdAndDelete())
14
+
15
+ module.exports = router;
@@ -0,0 +1,35 @@
1
+ const makeOptional = require("../../util/makeOptional");
2
+ const { string, object,array, lazy,number } = require("../../yup.config");
3
+
4
+ const paramId = object({
5
+ id: string().required('id is required').oid('id is invalid')
6
+ })
7
+
8
+ const schema = object({
9
+ title :string().required(),
10
+ slug : string().required().matches(/[\d\w]+/i ,'slug can contain english letter or numbers and dash'),
11
+ subTitle : string(),
12
+ category_id : string().oid(),
13
+ thumbnail_id : array().media({image: {max : 1}}),
14
+ content : string(),
15
+ tag_ids : array(string().oid()),
16
+ status : string().oneOf(['draft', 'published', 'hidden']),
17
+ priority : number()
18
+ })
19
+
20
+ //? exports
21
+
22
+ exports.post = {
23
+ body: lazy(value =>
24
+ Array.isArray(value)
25
+ ? array().of(schema)
26
+ : schema
27
+ )
28
+ }
29
+ exports.put ={
30
+ params: paramId,
31
+ body : makeOptional(schema)
32
+ }
33
+ exports.delete = {
34
+ params : paramId
35
+ }
@@ -0,0 +1,14 @@
1
+ const express = require('express');
2
+ const { auth, db, validator } = require('speedly/kit');
3
+
4
+ const v = require('./role.validator');
5
+
6
+ const router = express.Router();
7
+
8
+ router.route('/').get(auth.admin({ permission: 'OWNER' }), db('role').find())
9
+ .post(auth.admin({ permission: 'OWNER' }), validator(v.post), db('role').create())
10
+
11
+ router.route('/:id').put(auth.admin({ permission: 'OWNER' }), validator(v.put), db('role').findByIdAndUpdate())
12
+ .delete(auth.admin({ permission: 'OWNER' }), validator(v.delete), db('role').findByIdAndDelete())
13
+
14
+ module.exports = router;
@@ -0,0 +1,28 @@
1
+ const makeOptional = require("../../util/makeOptional");
2
+ const { string, object, array, lazy, boolean } = require("../../yup.config");
3
+
4
+ const paramId = object({
5
+ id: string().required('id is required').oid('id is invalid')
6
+ })
7
+
8
+ const schema = object({
9
+ title: string().required('title is required'),
10
+ access: string().required('access is required').oneOf(['OWNER', 'ADMIN', 'EXPERT'], 'access must be one of OWNER, ADMIN, EXPERT')
11
+ })
12
+
13
+ //? exports
14
+
15
+ exports.post = {
16
+ body: lazy(value =>
17
+ Array.isArray(value)
18
+ ? array().of(schema)
19
+ : schema
20
+ )
21
+ }
22
+ exports.put = {
23
+ params: paramId,
24
+ body: makeOptional(schema)
25
+ }
26
+ exports.delete = {
27
+ params: paramId
28
+ }
@@ -0,0 +1,97 @@
1
+ const userModel = require("../../model/user");
2
+ const otpModel = require("../../model/otp");
3
+ const roleModel = require("../../model/role");
4
+ const bcrypt = require("bcrypt");
5
+ const jwt = require("jsonwebtoken");
6
+ const { randomNumber } = require("../../util/generator");
7
+ const sms = require("../../util/sms");
8
+ const otpSender = async (phone) => {
9
+ let otpDoc = await otpModel.findOne({ phone });
10
+ try {
11
+ if (!otpDoc)
12
+ otpDoc = await otpModel.create({ phone, code: randomNumber(5) });
13
+ console.log("user.controller", 10, otpDoc);
14
+ await sms.otp(phone, "809162", otpDoc.code);
15
+ } catch (err) {
16
+ console.error("OTP sending failed:", err.cause?.response?.data?.meta?.errors || err);
17
+ //! DEVELOPE MODE
18
+ err.otpDoc = otpDoc
19
+ //! END DEVELOPE
20
+ throw err;
21
+ }
22
+ return otpDoc;
23
+ };
24
+
25
+ exports.checkPhone = async (req, res) => {
26
+ const { phone } = req.body;
27
+
28
+ const userDoc = await userModel.findOne({ phone });
29
+
30
+ const resBody = {
31
+ type: userDoc ? "login-otp" : "register",
32
+ };
33
+ try {
34
+ if (req.body.type == 'login-otp' || !userDoc || !userDoc.password) {
35
+ //! DEVELOPE MODE
36
+ resBody.IMPORTANT = '⚠ OTP is included in the response in development mode only. Must be removed before production release.'
37
+ //! END DEVELOPE
38
+
39
+ const otpRes = await otpSender(phone);
40
+
41
+ resBody.expireAt = otpRes.expireAt;
42
+
43
+ console.log('user.controller', 37,);
44
+
45
+ if (userDoc && !userDoc.password) {
46
+ resBody.type = "login-otp";
47
+ }
48
+ } else {
49
+ resBody.type = "login-password";
50
+ }
51
+
52
+ return res.json({ ...resBody, message: "OTP sent successfully" });
53
+ } catch (err) {
54
+ //! DEVELOPE MODE
55
+ if (err.otpDoc) resBody.code = err.otpDoc.code
56
+ //! END DEVELOPE
57
+
58
+ return res.status(err.statusCode || 500).json({ ...resBody, message: "OTP sending failed: " + err.message, });
59
+
60
+ }
61
+ };
62
+ exports.register = async (req, res) => {
63
+ const { phone, otpCode } = req.body;
64
+ let userDoc = await userModel.findOne({ phone });
65
+ let type = req.body.type || userDoc ? userDoc.password ? 'login-password' : "login-otp" : "register";
66
+ if (type === "register" || type === "login-otp") {
67
+ const otpDoc = await otpModel.findOne({ phone, code: otpCode });
68
+ if (!otpDoc) return res.status(400).json({ message: "Invalid OTP code" });
69
+ if (type === "register") {
70
+ let userObj = { phone };
71
+ if ((await userModel.countDocuments()) == 0) {
72
+ const ownerRole =
73
+ (await roleModel.findOne({ access: "OWNER" })) ||
74
+ (await roleModel.create({ title: "Owner", access: "OWNER" }));
75
+ userObj.role_id = ownerRole._id;
76
+ }
77
+ userDoc = await userModel.create(userObj);
78
+ }
79
+ }
80
+ else if (type === "login-password") {
81
+ const { password } = req.body;
82
+ userDoc = await userModel.findOne({ phone });
83
+ if (!userDoc) return res.status(400).json({ message: "User not found" });
84
+ if (!userDoc.password) return res.status(400).json({ message: "Password not set for this user" });
85
+ if (bcrypt.compareSync(password, userDoc.password)) {
86
+ return res.status(400).json({ message: "Incorrect password" })
87
+ }
88
+ } else {
89
+ return res.status(400).json({ message: "Invalid type" });
90
+ }
91
+ const token = jwt.sign({ id: userDoc._id, }, process.env.JWT_SECRET);
92
+ res.setCookie("accessToken", token)
93
+ res.json({
94
+ message: "Authentication successful",
95
+ token,
96
+ });
97
+ }
@@ -0,0 +1,18 @@
1
+ const express = require('express');
2
+ const { auth, db, validator } = require('speedly/kit');
3
+
4
+ const v = require('./user.validator');
5
+ const c = require('./user.controller');
6
+ const router = express.Router();
7
+
8
+ router.route('/check-phone').post(validator(v.checkPhone), c.checkPhone)
9
+ router.route('/register').post(validator(v.register), c.register)
10
+ router.route('/me').get(auth.user(), db('user').findOne(req => ({ _id: req.user._id })).populate('role_id').select('-password'))
11
+ router.route('/').get(auth.admin({ permission: 'owner' }), db('user').find())
12
+ .post(auth.admin(), validator(v.post), db('user').create())
13
+
14
+
15
+ router.route('/:id').put(auth.admin(), validator(v.put), db('user').findByIdAndUpdate())
16
+ .delete(auth.admin(), validator(v.delete), db('user').findByIdAndDelete())
17
+
18
+ module.exports = router;
@@ -0,0 +1,53 @@
1
+ const makeOptional = require("../../util/makeOptional");
2
+ const { string, object, array, lazy } = require("../../yup.config");
3
+
4
+ const paramId = object({
5
+ id: string().required("id is required").oid("id is invalid"),
6
+ });
7
+
8
+ const schema = object({});
9
+
10
+ //? exports
11
+
12
+ exports.register = {
13
+ body: object({
14
+ phone: string()
15
+ .required("phone is required")
16
+ .matches(
17
+ /^09\d{9}$/,
18
+ "phone is invalid enter 11 digit in format 09*********",
19
+ ),
20
+ otpCode: string().when("type", ([type]) => {
21
+ if (type === "register" || type === "login")
22
+ return string().required(
23
+ "otpCode is required for register and login type",
24
+ );
25
+ }),
26
+ password: string().when("type", ([type]) => {
27
+ if (type === "login-password")
28
+ return string()
29
+ .required("password is required for login-password type")
30
+ }),
31
+ }),
32
+ };
33
+
34
+ exports.checkPhone = {
35
+ body: object({
36
+ phone: string()
37
+ .required("phone is required")
38
+ .matches(
39
+ /^09\d{9}$/,
40
+ "phone is invalid enter 11 digit in format 09*********",
41
+ ),
42
+ }),
43
+ };
44
+ exports.post = {
45
+ body: lazy((value) => (Array.isArray(value) ? array().of(schema) : schema)),
46
+ };
47
+ exports.put = {
48
+ params: paramId,
49
+ body: makeOptional(schema),
50
+ };
51
+ exports.delete = {
52
+ params: paramId,
53
+ };
package/package.json CHANGED
@@ -1,66 +1,65 @@
1
- {
2
- "name": "speedly",
3
- "version": "2.0.38",
4
- "main": "dist/cjs/index.js",
5
- "module": "dist/esm/index.js",
6
- "types": "dist/esm/index.d.ts",
7
- "exports": {
8
- ".": {
9
- "import": "./dist/esm/index.js",
10
- "require": "./dist/cjs/index.js"
11
- },
12
- "./kit": {
13
- "import": "./dist/esm/kit/index.js",
14
- "require": "./dist/cjs/kit/index.js"
15
- },
16
- "./util": {
17
- "import": "./dist/esm/util/index.js",
18
- "require": "./dist/cjs/util/index.js"
19
- },
20
- "./modules": {
21
- "import": "./dist/esm/modules/index.js",
22
- "require": "./dist/cjs/modules/index.js"
23
- },
24
- "./document": {
25
- "import": "./dist/esm/document/index.js",
26
- "require": "./dist/cjs/document/index.js"
27
- },
28
- "./model": {
29
- "import": "./dist/esm/model/index.js",
30
- "require": "./dist/cjs/model/index.js"
31
- }
32
- },
33
- "scripts": {
34
- "build": "npm run build:cjs && npm run build:esm",
35
- "build:cjs": "tsc -p tsconfig.cjs.json",
36
- "build:esm": "tsc -p tsconfig.esm.json",
37
- "pub": "npm run build && git add . && git commit -m 'publish' && npm version patch && npm publish ",
38
- "dev": "ts-node src/index.ts"
39
- },
40
- "author": "MAHSERIN",
41
- "license": "MIT",
42
- "description": "",
43
- "devDependencies": {
44
- "@types/express": "^5.0.3",
45
- "@types/multer": "^2.0.0",
46
- "@types/node": "^24.5.2",
47
- "@types/swagger-ui-express": "^4.1.8",
48
- "ts-node": "^10.9.2",
49
- "tsc": "^2.0.4",
50
- "typescript": "^5.9.3"
51
- },
52
- "peerDependencies": {
53
- "express": "^5",
54
- "mongoose": ">=8 <10",
55
- "multer": "^2"
56
- },
57
- "dependencies": {
58
- "axios": "^1.11.0",
59
- "cosmiconfig": "^9.0.0",
60
- "jsonwebtoken": "^9.0.2",
61
- "swagger-themes": "^1.4.3",
62
- "swagger-ui-express": "^5.0.1",
63
- "translate": "^3.0.1",
64
- "yup": "^1.7.1"
65
- }
66
- }
1
+ {
2
+ "name": "speedly",
3
+ "version": "2.0.42",
4
+ "main": "dist/cjs/index.js",
5
+ "module": "dist/esm/index.js",
6
+ "types": "dist/esm/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/esm/index.js",
10
+ "require": "./dist/cjs/index.js"
11
+ },
12
+ "./kit": {
13
+ "import": "./dist/esm/kit/index.js",
14
+ "require": "./dist/cjs/kit/index.js"
15
+ },
16
+ "./util": {
17
+ "import": "./dist/esm/util/index.js",
18
+ "require": "./dist/cjs/util/index.js"
19
+ },
20
+ "./modules": {
21
+ "import": "./dist/esm/modules/index.js",
22
+ "require": "./dist/cjs/modules/index.js"
23
+ },
24
+ "./document": {
25
+ "import": "./dist/esm/document/index.js",
26
+ "require": "./dist/cjs/document/index.js"
27
+ },
28
+ "./model": {
29
+ "import": "./dist/esm/model/index.js",
30
+ "require": "./dist/cjs/model/index.js"
31
+ }
32
+ },
33
+ "scripts": {
34
+ "build": "npm run build:cjs && npm run build:esm",
35
+ "build:cjs": "tsc -p tsconfig.cjs.json",
36
+ "build:esm": "tsc -p tsconfig.esm.json",
37
+ "pub": "npm run build && git add . && git commit -m 'publish' && npm version patch && npm publish ",
38
+ "dev": "ts-node src/index.ts"
39
+ },
40
+ "author": "MAHSERIN",
41
+ "license": "MIT",
42
+ "description": "",
43
+ "devDependencies": {
44
+ "@types/express": "^5.0.3",
45
+ "@types/multer": "^2.0.0",
46
+ "@types/node": "^24.5.2",
47
+ "@types/swagger-ui-express": "^4.1.8",
48
+ "ts-node": "^10.9.2"
49
+ },
50
+ "peerDependencies": {
51
+ "express": "^5",
52
+ "mongoose": ">=8 <10",
53
+ "multer": "^2"
54
+ },
55
+ "dependencies": {
56
+ "axios": "^1.11.0",
57
+ "cosmiconfig": "^9.0.0",
58
+ "jsonwebtoken": "^9.0.2",
59
+ "swagger-themes": "^1.4.3",
60
+ "swagger-ui-express": "^5.0.1",
61
+ "translate": "^3.0.1",
62
+ "typescript": "^6.0.3",
63
+ "yup": "^1.7.1"
64
+ }
65
+ }
@@ -1,18 +0,0 @@
1
- import { Request, Response, NextFunction } from "express";
2
- type Handler = (req: Request, res: Response, next: (errorMessage?: string) => unknown) => unknown;
3
- type UseAuth = (req: Request, res: Response, next: NextFunction) => UseAuth | {
4
- user?: (...handlers: Handler[]) => unknown;
5
- admin?: (...handlers: [{
6
- permission: string;
7
- }, ...Handler[]] | Handler[]) => unknown;
8
- any?: (...handlers: Handler[]) => unknown;
9
- };
10
- declare const auth: (config?: {
11
- admin: {
12
- role: string;
13
- model: string;
14
- };
15
- jwtSecretEnv: string;
16
- customValidator: (req: Request, key: string) => boolean;
17
- }) => UseAuth;
18
- export default auth;
@@ -1,93 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const getConfig_1 = __importDefault(require("../util/getConfig"));
7
- const gConfig = {
8
- admin: { role: "ADMIN", model: "../models/admin" },
9
- jwtSecretEnv: "JWT_KEY",
10
- customValidator: (req, key) => {
11
- return true;
12
- },
13
- ...(0, getConfig_1.default)("auth"),
14
- };
15
- const holders = {};
16
- const auth = (config = gConfig) => {
17
- // const adminModel = require('../models/admin')
18
- let handlerState = {};
19
- let useAuth = async (req, res, next) => {
20
- try {
21
- const nextFunc = (handlers, index = 0) => (errorMessage = "") => {
22
- if (errorMessage)
23
- return next(errorMessage);
24
- if (!handlers.length || !handlers[index + 1])
25
- return next();
26
- handlers[index + 1](req, res, nextFunc(handlers, index + 1));
27
- };
28
- const keys = Object.keys(handlerState);
29
- for (let i = 0; i < keys.length; i++) {
30
- const key = keys[i];
31
- if (!handlerState[key]?.handlers?.length)
32
- continue;
33
- if (await gConfig?.customValidator?.(req, key)) {
34
- return await handlerState[key].handlers[0](req, res, nextFunc(handlerState[key].handlers));
35
- }
36
- else if ((await gConfig?.customValidator?.(req, key)) == null) {
37
- return next({ status: 401, json: { message: "unauthorized" } });
38
- }
39
- else if (i === keys.length - 1) {
40
- next({
41
- status: 405,
42
- json: { message: "you don't have access to this section" },
43
- });
44
- }
45
- else
46
- continue;
47
- }
48
- }
49
- catch (error) {
50
- console.log("auth", 42, error);
51
- next({
52
- status: 403,
53
- json: {
54
- message: error instanceof Error
55
- ? error.message
56
- : "error on authentication please login again",
57
- },
58
- });
59
- }
60
- };
61
- holders.admin = (...handlers) => {
62
- if (!Array.isArray(handlers))
63
- throw new Error("handlers must be an array");
64
- const hasConfig = typeof handlers[0] === "object" && "permission" in handlers[0];
65
- const configObj = hasConfig
66
- ? handlers[0]
67
- : undefined;
68
- const handlerFns = hasConfig
69
- ? handlers.slice(1)
70
- : handlers;
71
- handlerState[`admin${configObj?.permission ? `:${configObj.permission}` : ""}`] = {
72
- ...(configObj ? { config: configObj } : {}),
73
- handlers: handlerFns,
74
- };
75
- return useAuth;
76
- };
77
- holders.user = (...handlers) => {
78
- if (!Array.isArray(handlers))
79
- throw new Error("handlers must be an array");
80
- handlerState.user = { handlers };
81
- return useAuth;
82
- };
83
- holders.any = (...handlers) => {
84
- if (!Array.isArray(handlers))
85
- throw new Error("handlers must be an array");
86
- handlerState.any = { handlers };
87
- return useAuth;
88
- };
89
- useAuth = Object.assign(useAuth, holders);
90
- return useAuth;
91
- };
92
- console.log("auth", 81, typeof auth);
93
- exports.default = auth;