@modular-rest/server 1.11.14 → 1.11.15
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.
- package/dist/application.d.ts +29 -0
- package/dist/application.js +217 -0
- package/dist/class/cms_trigger.d.ts +52 -0
- package/dist/class/cms_trigger.js +47 -0
- package/dist/class/collection_definition.d.ts +112 -0
- package/dist/class/collection_definition.js +87 -0
- package/dist/class/combinator.d.ts +43 -0
- package/dist/class/combinator.js +174 -0
- package/dist/class/database_trigger.d.ts +90 -0
- package/dist/class/database_trigger.js +64 -0
- package/dist/class/db_schemas.d.ts +25 -0
- package/dist/class/db_schemas.js +28 -0
- package/dist/class/directory.d.ts +20 -0
- package/dist/class/directory.js +87 -0
- package/dist/class/paginator.d.ts +31 -0
- package/dist/class/paginator.js +43 -0
- package/dist/class/reply.d.ts +29 -0
- package/dist/class/reply.js +44 -0
- package/dist/class/security.d.ts +186 -0
- package/dist/class/security.js +178 -0
- package/dist/class/trigger_operator.d.ts +92 -0
- package/dist/class/trigger_operator.js +99 -0
- package/dist/class/user.d.ts +81 -0
- package/dist/class/user.js +151 -0
- package/dist/class/validator.d.ts +19 -0
- package/dist/class/validator.js +101 -0
- package/dist/config.d.ts +113 -0
- package/dist/config.js +26 -0
- package/dist/defult-permissions.d.ts +2 -0
- package/dist/defult-permissions.js +31 -0
- package/dist/events.d.ts +23 -0
- package/dist/events.js +47 -0
- package/dist/helper/data_insertion.d.ts +38 -0
- package/dist/helper/data_insertion.js +110 -0
- package/dist/helper/presetup_services.d.ts +60 -0
- package/dist/helper/presetup_services.js +108 -0
- package/dist/index.d.ts +118 -0
- package/dist/middlewares.d.ts +53 -0
- package/dist/middlewares.js +106 -0
- package/dist/play-test.d.ts +1 -0
- package/dist/play-test.js +9 -0
- package/dist/services/data_provider/router.d.ts +4 -0
- package/dist/services/data_provider/router.js +412 -0
- package/dist/services/data_provider/service.d.ts +132 -0
- package/dist/services/data_provider/service.js +253 -0
- package/dist/services/data_provider/typeCasters.d.ts +9 -0
- package/dist/services/data_provider/typeCasters.js +18 -0
- package/dist/services/file/db.d.ts +1 -0
- package/dist/services/file/db.js +31 -0
- package/dist/services/file/router.d.ts +4 -0
- package/dist/services/file/router.js +115 -0
- package/dist/services/file/service.d.ts +204 -0
- package/dist/services/file/service.js +341 -0
- package/dist/services/functions/router.d.ts +4 -0
- package/dist/services/functions/router.js +68 -0
- package/dist/services/functions/service.d.ts +132 -0
- package/dist/services/functions/service.js +159 -0
- package/dist/services/jwt/router.d.ts +4 -0
- package/dist/services/jwt/router.js +99 -0
- package/dist/services/jwt/service.d.ts +97 -0
- package/dist/services/jwt/service.js +135 -0
- package/dist/services/user_manager/db.d.ts +1 -0
- package/dist/services/user_manager/db.js +75 -0
- package/dist/services/user_manager/permissionManager.d.ts +19 -0
- package/dist/services/user_manager/permissionManager.js +42 -0
- package/dist/services/user_manager/router.d.ts +4 -0
- package/dist/services/user_manager/router.js +195 -0
- package/dist/services/user_manager/service.d.ts +317 -0
- package/dist/services/user_manager/service.js +632 -0
- package/package.json +3 -3
- package/src/application.ts +1 -1
- package/src/class/cms_trigger.ts +8 -14
- package/src/class/database_trigger.ts +10 -4
- package/src/class/user.ts +1 -1
- package/src/services/data_provider/router.ts +293 -0
- package/src/services/data_provider/service.ts +2 -1
- package/src/services/functions/router.ts +3 -2
- package/src/services/user_manager/db.ts +5 -5
- package/src/services/user_manager/service.ts +20 -15
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.User = void 0;
|
|
4
|
+
const config_1 = require("../config");
|
|
5
|
+
const validator_1 = require("./validator");
|
|
6
|
+
/**
|
|
7
|
+
* User class representing a user in the system
|
|
8
|
+
*
|
|
9
|
+
* @public
|
|
10
|
+
*/
|
|
11
|
+
class User {
|
|
12
|
+
/**
|
|
13
|
+
* Create a user
|
|
14
|
+
* @param id - User ID
|
|
15
|
+
* @param permissionGroup - Permission group name
|
|
16
|
+
* @param phone - User phone
|
|
17
|
+
* @param email - User email
|
|
18
|
+
* @param password - User password
|
|
19
|
+
* @param type - User type
|
|
20
|
+
* @param model - Database model
|
|
21
|
+
*
|
|
22
|
+
* @hidden
|
|
23
|
+
*/
|
|
24
|
+
constructor(id, permissionGroup, phone, email, password, type, model) {
|
|
25
|
+
this.id = id;
|
|
26
|
+
this.permissionGroup = permissionGroup;
|
|
27
|
+
this.email = email;
|
|
28
|
+
this.phone = phone;
|
|
29
|
+
this.password = password;
|
|
30
|
+
this.type = type;
|
|
31
|
+
this.dbModel = model;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Get brief user information
|
|
35
|
+
* @returns Brief user info object
|
|
36
|
+
*/
|
|
37
|
+
getBrief() {
|
|
38
|
+
const permissionGroup = config_1.config.permissionGroups?.find(group => group.title === this.permissionGroup);
|
|
39
|
+
if (!permissionGroup) {
|
|
40
|
+
throw new Error('Permission group not found on user object');
|
|
41
|
+
}
|
|
42
|
+
const brief = {
|
|
43
|
+
id: this.id,
|
|
44
|
+
permissionGroup: permissionGroup,
|
|
45
|
+
phone: this.phone,
|
|
46
|
+
email: this.email,
|
|
47
|
+
type: this.type,
|
|
48
|
+
};
|
|
49
|
+
return brief;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Update user details
|
|
53
|
+
* @param detail - Object containing user details to update
|
|
54
|
+
*/
|
|
55
|
+
setNewDetail(detail) {
|
|
56
|
+
if (detail.phone)
|
|
57
|
+
this.phone = detail.phone;
|
|
58
|
+
if (detail.email)
|
|
59
|
+
this.email = detail.email;
|
|
60
|
+
if (detail.password)
|
|
61
|
+
this.password = detail.password;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Check if user has a specific permission
|
|
65
|
+
* @param accessType - Permission to check
|
|
66
|
+
* @returns True if user has permission, false otherwise
|
|
67
|
+
*/
|
|
68
|
+
hasPermission(accessType) {
|
|
69
|
+
const permissionGroup = config_1.config.permissionGroups?.find(group => group.title === this.permissionGroup);
|
|
70
|
+
if (permissionGroup == null)
|
|
71
|
+
return false;
|
|
72
|
+
let key = false;
|
|
73
|
+
if (permissionGroup.allowedAccessTypes) {
|
|
74
|
+
for (let i = 0; i < permissionGroup.allowedAccessTypes.length; i++) {
|
|
75
|
+
const userPermissionType = permissionGroup.allowedAccessTypes[i];
|
|
76
|
+
if (userPermissionType === accessType) {
|
|
77
|
+
key = true;
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return key;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Save user to database
|
|
86
|
+
*/
|
|
87
|
+
async save() {
|
|
88
|
+
if (!this.dbModel) {
|
|
89
|
+
throw new Error('User model is not initialized');
|
|
90
|
+
}
|
|
91
|
+
this.dbModel['permissionGroup'] = this.permissionGroup;
|
|
92
|
+
this.dbModel['phone'] = this.phone;
|
|
93
|
+
this.dbModel['email'] = this.email;
|
|
94
|
+
this.dbModel['password'] = this.password;
|
|
95
|
+
await this.dbModel.save();
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Load user from database model
|
|
99
|
+
* @param model - Database model
|
|
100
|
+
* @returns Promise resolving to User instance
|
|
101
|
+
*/
|
|
102
|
+
static loadFromModel(model) {
|
|
103
|
+
return new Promise((done, reject) => {
|
|
104
|
+
// check required fields
|
|
105
|
+
const isValidData = (0, validator_1.validator)(model, '_id permissionGroup');
|
|
106
|
+
if (!isValidData.isValid) {
|
|
107
|
+
return reject(User.notValid(model));
|
|
108
|
+
}
|
|
109
|
+
const id = model.id;
|
|
110
|
+
const permissionGroup = model.permissionGroup;
|
|
111
|
+
const phone = model.phone;
|
|
112
|
+
const email = model.email;
|
|
113
|
+
const password = model.password;
|
|
114
|
+
const type = model.type;
|
|
115
|
+
//create user
|
|
116
|
+
const newUser = new User(id, permissionGroup, phone, email, password, type, model);
|
|
117
|
+
done(newUser);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Create user from model and details
|
|
122
|
+
* @param model - Mongoose model
|
|
123
|
+
* @param detail - User details
|
|
124
|
+
* @returns Promise resolving to User instance
|
|
125
|
+
*/
|
|
126
|
+
static createFromModel(model, detail) {
|
|
127
|
+
return new Promise(async (done, reject) => {
|
|
128
|
+
//create user
|
|
129
|
+
try {
|
|
130
|
+
const newUserDoc = await new model(detail).save();
|
|
131
|
+
const newUser = await User.loadFromModel(newUserDoc);
|
|
132
|
+
done(newUser);
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
reject(error);
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Create error for invalid user
|
|
141
|
+
* @param object - Invalid user object
|
|
142
|
+
* @returns Error message
|
|
143
|
+
*/
|
|
144
|
+
static notValid(object) {
|
|
145
|
+
const error = `user detail are not valid ${JSON.stringify(object)}`;
|
|
146
|
+
console.error(error);
|
|
147
|
+
return error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
exports.User = User;
|
|
151
|
+
exports.default = User;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validation result interface
|
|
3
|
+
*/
|
|
4
|
+
export interface ValidationResult {
|
|
5
|
+
isValid: boolean;
|
|
6
|
+
requires: string[];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Validates an object by checking if it contains all the required fields.
|
|
10
|
+
* @param obj - The object to be validated.
|
|
11
|
+
* @param requiredFields - The list of required fields. If it's a string, it should contain keys separated by spaces. If it's an object, it should contain key-value pairs where the key is the field name and the value is a boolean indicating whether the field is required or not.
|
|
12
|
+
* @returns Returns a ValidationResult object with validation status and missing fields.
|
|
13
|
+
* @throws Throws an error if the requiredFields parameter is not a string or an object.
|
|
14
|
+
*/
|
|
15
|
+
export declare function validator(obj: Record<string, any> | null, requiredFields: string | Record<string, string>): ValidationResult;
|
|
16
|
+
/**
|
|
17
|
+
* Return the validator function to maintain compatibility with the JavaScript version
|
|
18
|
+
*/
|
|
19
|
+
export declare const validateObject: typeof validator;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateObject = void 0;
|
|
4
|
+
exports.validator = validator;
|
|
5
|
+
/**
|
|
6
|
+
* Validates an object by checking if it contains all the required fields.
|
|
7
|
+
* @param obj - The object to be validated.
|
|
8
|
+
* @param requiredFields - The list of required fields. If it's a string, it should contain keys separated by spaces. If it's an object, it should contain key-value pairs where the key is the field name and the value is a boolean indicating whether the field is required or not.
|
|
9
|
+
* @returns Returns a ValidationResult object with validation status and missing fields.
|
|
10
|
+
* @throws Throws an error if the requiredFields parameter is not a string or an object.
|
|
11
|
+
*/
|
|
12
|
+
function validator(obj, requiredFields) {
|
|
13
|
+
/*
|
|
14
|
+
this method could validate an Object by given field's name list and return bool.
|
|
15
|
+
- requiredFields: is a string that contains keys being spared by " ".
|
|
16
|
+
*/
|
|
17
|
+
const type = typeof requiredFields;
|
|
18
|
+
let result;
|
|
19
|
+
if (type === 'string')
|
|
20
|
+
result = checkSimple(obj, requiredFields);
|
|
21
|
+
else if (type === 'object')
|
|
22
|
+
result = checkComplex(obj, requiredFields);
|
|
23
|
+
else
|
|
24
|
+
throw 'requiredFields has wrong form, it must be string or object';
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Check simple validation with space-separated string of keys
|
|
29
|
+
*/
|
|
30
|
+
function checkSimple(obj, requiredFields = '') {
|
|
31
|
+
let isValid = false;
|
|
32
|
+
const requires = requiredFields.split(' ');
|
|
33
|
+
const validMembers = [];
|
|
34
|
+
const notValidKeys = [];
|
|
35
|
+
// return if obj is null
|
|
36
|
+
if (obj == null)
|
|
37
|
+
return _returnResult(isValid, requires);
|
|
38
|
+
// Filter empty strings that might result from extra spaces
|
|
39
|
+
const requiredKeys = requires.filter(key => key !== '');
|
|
40
|
+
for (const key of requiredKeys) {
|
|
41
|
+
if (obj[key] !== undefined && obj[key] !== null)
|
|
42
|
+
validMembers.push(key);
|
|
43
|
+
else
|
|
44
|
+
notValidKeys.push(key);
|
|
45
|
+
}
|
|
46
|
+
// check validation
|
|
47
|
+
isValid = requiredKeys.length === validMembers.length;
|
|
48
|
+
return _returnResult(isValid, notValidKeys);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Check complex validation with object containing expected values
|
|
52
|
+
*/
|
|
53
|
+
function checkComplex(obj, requiredFields = {}) {
|
|
54
|
+
let isValid = false;
|
|
55
|
+
const requireKeys = Object.keys(requiredFields);
|
|
56
|
+
let validMembers = 0;
|
|
57
|
+
const notValidKeys = [];
|
|
58
|
+
// return if obj is null
|
|
59
|
+
if (obj == null)
|
|
60
|
+
return _returnResult(isValid, requireKeys);
|
|
61
|
+
for (let i = 0; i < requireKeys.length; i++) {
|
|
62
|
+
const key = requireKeys[i];
|
|
63
|
+
let isValidField = false;
|
|
64
|
+
// if field has specific values
|
|
65
|
+
if (requiredFields[key].length > 0) {
|
|
66
|
+
const expectedValues = requiredFields[key].split(' ');
|
|
67
|
+
if (typeof expectedValues !== 'object')
|
|
68
|
+
throw `${key} must be array of strings`;
|
|
69
|
+
for (const value of expectedValues) {
|
|
70
|
+
if (obj[key] === value) {
|
|
71
|
+
isValidField = true;
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
// else does not have specific value
|
|
77
|
+
else if (obj[key] != null) {
|
|
78
|
+
isValidField = true;
|
|
79
|
+
}
|
|
80
|
+
if (isValidField)
|
|
81
|
+
validMembers++;
|
|
82
|
+
else
|
|
83
|
+
notValidKeys.push(key);
|
|
84
|
+
}
|
|
85
|
+
// check validation
|
|
86
|
+
isValid = requireKeys.length === validMembers;
|
|
87
|
+
return _returnResult(isValid, notValidKeys);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Create a validation result object
|
|
91
|
+
*/
|
|
92
|
+
function _returnResult(isValid, notValidKeys) {
|
|
93
|
+
return {
|
|
94
|
+
isValid: isValid,
|
|
95
|
+
requires: notValidKeys,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Return the validator function to maintain compatibility with the JavaScript version
|
|
100
|
+
*/
|
|
101
|
+
exports.validateObject = validator;
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import Koa from 'koa';
|
|
2
|
+
import { CollectionDefinition } from './class/collection_definition';
|
|
3
|
+
import { PermissionGroup } from './class/security';
|
|
4
|
+
import { CmsTrigger } from './class/cms_trigger';
|
|
5
|
+
import { DefinedFunction } from './services/functions/service';
|
|
6
|
+
import { Options as KoaCorsOptions } from '@koa/cors';
|
|
7
|
+
import { Options as KoaStaticOptionsBase } from 'koa-static';
|
|
8
|
+
/**
|
|
9
|
+
* The options for the static file server, it's a combination of modular-rest and [koa-static options](https://github.com/koajs/static?tab=readme-ov-file#options)
|
|
10
|
+
*/
|
|
11
|
+
export type StaticPathOptions = KoaStaticOptionsBase & {
|
|
12
|
+
/**
|
|
13
|
+
* The actual path of the static files on your server
|
|
14
|
+
*/
|
|
15
|
+
actualPath: string;
|
|
16
|
+
/**
|
|
17
|
+
* The path you want to serve the static files from
|
|
18
|
+
*/
|
|
19
|
+
path: string;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* JWT keypair configuration
|
|
23
|
+
* @interface KeyPair
|
|
24
|
+
* @property {string} private - Private key for JWT signing
|
|
25
|
+
* @property {string} public - Public key for JWT verification
|
|
26
|
+
*/
|
|
27
|
+
interface KeyPair {
|
|
28
|
+
private: string;
|
|
29
|
+
public: string;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* MongoDB connection options
|
|
33
|
+
* @interface MongoOptions
|
|
34
|
+
* @property {string} dbPrefix - Prefix for database names
|
|
35
|
+
* @property {string} mongoBaseAddress - MongoDB connection URL
|
|
36
|
+
*/
|
|
37
|
+
interface MongoOptions {
|
|
38
|
+
dbPrefix: string;
|
|
39
|
+
mongoBaseAddress: string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Admin user configuration
|
|
43
|
+
* @interface AdminUser
|
|
44
|
+
* @property {string} email - Admin user email
|
|
45
|
+
* @property {string} password - Admin user password
|
|
46
|
+
*/
|
|
47
|
+
interface AdminUser {
|
|
48
|
+
email: string;
|
|
49
|
+
password: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Configuration options for creating a REST API instance
|
|
53
|
+
* @interface RestOptions
|
|
54
|
+
* @property {KoaCorsOptions} [cors] - CORS configuration [options](https://github.com/koajs/cors?tab=readme-ov-file#corsoptions)
|
|
55
|
+
* @property {string} [modulesPath] - Path to custom modules directory
|
|
56
|
+
* @property {string} [uploadDirectory] - Directory for file uploads
|
|
57
|
+
* @property {any} [koaBodyOptions] - Options for koa-body middleware
|
|
58
|
+
* @property {StaticPathOptions} [staticPath] - Static file serving options
|
|
59
|
+
* @property {Function} [onBeforeInit] - Hook called before initialization
|
|
60
|
+
* @property {Function} [onAfterInit] - Hook called after initialization
|
|
61
|
+
* @property {number} [port] - Port to listen on
|
|
62
|
+
* @property {boolean} [dontListen] - Don't start the server
|
|
63
|
+
* @property {MongoOptions} [mongo] - MongoDB connection options
|
|
64
|
+
* @property {Object} [keypair] - JWT keypair for authentication
|
|
65
|
+
* @property {AdminUser} [adminUser] - Admin user configuration
|
|
66
|
+
* @property {Function} [verificationCodeGeneratorMethod] - Custom verification code generator
|
|
67
|
+
* @property {CollectionDefinition[]} [collectionDefinitions] - Custom collection definitions
|
|
68
|
+
* @property {PermissionGroup[]} [permissionGroups] - Custom permission groups
|
|
69
|
+
* @property {CmsTrigger[]} [authTriggers] - Authentication triggers
|
|
70
|
+
* @property {CmsTrigger[]} [fileTriggers] - File handling triggers
|
|
71
|
+
* @property {DefinedFunction[]} [functions] - Custom API functions
|
|
72
|
+
*/
|
|
73
|
+
export interface RestOptions {
|
|
74
|
+
cors?: KoaCorsOptions;
|
|
75
|
+
modulesPath?: string;
|
|
76
|
+
uploadDirectory?: string;
|
|
77
|
+
koaBodyOptions?: any;
|
|
78
|
+
staticPath?: StaticPathOptions;
|
|
79
|
+
onBeforeInit?: (koaApp: Koa) => void;
|
|
80
|
+
onAfterInit?: (koaApp: Koa) => void;
|
|
81
|
+
port?: number;
|
|
82
|
+
dontListen?: boolean;
|
|
83
|
+
mongo?: MongoOptions;
|
|
84
|
+
keypair?: KeyPair;
|
|
85
|
+
adminUser?: AdminUser;
|
|
86
|
+
verificationCodeGeneratorMethod?: () => string;
|
|
87
|
+
collectionDefinitions?: CollectionDefinition[];
|
|
88
|
+
permissionGroups?: PermissionGroup[];
|
|
89
|
+
authTriggers?: CmsTrigger[];
|
|
90
|
+
fileTriggers?: CmsTrigger[];
|
|
91
|
+
functions?: DefinedFunction[];
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Global configuration object
|
|
95
|
+
* @type {RestOptions}
|
|
96
|
+
*/
|
|
97
|
+
export declare const config: RestOptions;
|
|
98
|
+
/**
|
|
99
|
+
* Updates the global configuration with new options
|
|
100
|
+
* @param {RestOptions} options - New configuration options to merge
|
|
101
|
+
* @example
|
|
102
|
+
* ```typescript
|
|
103
|
+
* setConfig({
|
|
104
|
+
* port: 3000,
|
|
105
|
+
* mongo: {
|
|
106
|
+
* mongoBaseAddress: 'mongodb://localhost:27017',
|
|
107
|
+
* dbPrefix: 'myapp_'
|
|
108
|
+
* }
|
|
109
|
+
* });
|
|
110
|
+
* ```
|
|
111
|
+
*/
|
|
112
|
+
export declare function setConfig(options: RestOptions): void;
|
|
113
|
+
export {};
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.config = void 0;
|
|
4
|
+
exports.setConfig = setConfig;
|
|
5
|
+
/**
|
|
6
|
+
* Global configuration object
|
|
7
|
+
* @type {RestOptions}
|
|
8
|
+
*/
|
|
9
|
+
exports.config = {};
|
|
10
|
+
/**
|
|
11
|
+
* Updates the global configuration with new options
|
|
12
|
+
* @param {RestOptions} options - New configuration options to merge
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* setConfig({
|
|
16
|
+
* port: 3000,
|
|
17
|
+
* mongo: {
|
|
18
|
+
* mongoBaseAddress: 'mongodb://localhost:27017',
|
|
19
|
+
* dbPrefix: 'myapp_'
|
|
20
|
+
* }
|
|
21
|
+
* });
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
function setConfig(options) {
|
|
25
|
+
Object.assign(exports.config, options);
|
|
26
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.permissionGroups = void 0;
|
|
4
|
+
const security_1 = require("./class/security");
|
|
5
|
+
exports.permissionGroups = [
|
|
6
|
+
new security_1.PermissionGroup({
|
|
7
|
+
title: 'anonymous',
|
|
8
|
+
isAnonymous: true,
|
|
9
|
+
allowedAccessTypes: ['anonymous_access'],
|
|
10
|
+
}),
|
|
11
|
+
new security_1.PermissionGroup({
|
|
12
|
+
title: 'end-user',
|
|
13
|
+
isDefault: true,
|
|
14
|
+
allowedAccessTypes: [
|
|
15
|
+
'user_access',
|
|
16
|
+
'anonymous_access',
|
|
17
|
+
'upload_file_access',
|
|
18
|
+
'remove_file_access',
|
|
19
|
+
],
|
|
20
|
+
}),
|
|
21
|
+
new security_1.PermissionGroup({
|
|
22
|
+
title: 'administrator',
|
|
23
|
+
allowedAccessTypes: [
|
|
24
|
+
'user_access',
|
|
25
|
+
'anonymous_access',
|
|
26
|
+
'upload_file_access',
|
|
27
|
+
'remove_file_access',
|
|
28
|
+
'advanced_settings',
|
|
29
|
+
],
|
|
30
|
+
}),
|
|
31
|
+
];
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Supported event types:
|
|
3
|
+
* - onBeforeInit: (koaApp: Koa) => void; // A callback called before initializing the Koa server.
|
|
4
|
+
* - onAfterInit: (koaApp: Koa) => void; // A callback called after server initialization.
|
|
5
|
+
* - onNewUser: (user: any) => void; // A callback called when a new user is created.
|
|
6
|
+
*
|
|
7
|
+
* @param event - The event name to register
|
|
8
|
+
* @param callback - The callback function to be called when the event is triggered
|
|
9
|
+
* @throws Error if event is not a string or callback is not a function
|
|
10
|
+
*/
|
|
11
|
+
export declare function registerEventCallback(event: string, callback: (...args: any[]) => void): void;
|
|
12
|
+
/**
|
|
13
|
+
* Get all registered callbacks for a specific event
|
|
14
|
+
* @param event - The event name to get callbacks for
|
|
15
|
+
* @returns Array of callbacks registered for the event
|
|
16
|
+
*/
|
|
17
|
+
export declare function getEventCallbacks(event: string): ((...args: any[]) => void)[];
|
|
18
|
+
/**
|
|
19
|
+
* Trigger an event with arguments
|
|
20
|
+
* @param event - The event name to trigger
|
|
21
|
+
* @param args - Arguments to pass to the callback functions
|
|
22
|
+
*/
|
|
23
|
+
export declare function triggerEvent(event: string, ...args: any[]): void;
|
package/dist/events.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerEventCallback = registerEventCallback;
|
|
4
|
+
exports.getEventCallbacks = getEventCallbacks;
|
|
5
|
+
exports.triggerEvent = triggerEvent;
|
|
6
|
+
/**
|
|
7
|
+
* Array to store all registered event callbacks
|
|
8
|
+
*/
|
|
9
|
+
const eventCallbacks = [];
|
|
10
|
+
/**
|
|
11
|
+
* Supported event types:
|
|
12
|
+
* - onBeforeInit: (koaApp: Koa) => void; // A callback called before initializing the Koa server.
|
|
13
|
+
* - onAfterInit: (koaApp: Koa) => void; // A callback called after server initialization.
|
|
14
|
+
* - onNewUser: (user: any) => void; // A callback called when a new user is created.
|
|
15
|
+
*
|
|
16
|
+
* @param event - The event name to register
|
|
17
|
+
* @param callback - The callback function to be called when the event is triggered
|
|
18
|
+
* @throws Error if event is not a string or callback is not a function
|
|
19
|
+
*/
|
|
20
|
+
function registerEventCallback(event, callback) {
|
|
21
|
+
if (typeof event !== "string")
|
|
22
|
+
throw new Error("Event must be a string");
|
|
23
|
+
if (typeof callback !== "function")
|
|
24
|
+
throw new Error("Callback must be a function");
|
|
25
|
+
eventCallbacks.push({ event, callback });
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Get all registered callbacks for a specific event
|
|
29
|
+
* @param event - The event name to get callbacks for
|
|
30
|
+
* @returns Array of callbacks registered for the event
|
|
31
|
+
*/
|
|
32
|
+
function getEventCallbacks(event) {
|
|
33
|
+
return eventCallbacks
|
|
34
|
+
.filter((cb) => cb.event === event)
|
|
35
|
+
.map((cb) => cb.callback);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Trigger an event with arguments
|
|
39
|
+
* @param event - The event name to trigger
|
|
40
|
+
* @param args - Arguments to pass to the callback functions
|
|
41
|
+
*/
|
|
42
|
+
function triggerEvent(event, ...args) {
|
|
43
|
+
const callbacks = getEventCallbacks(event);
|
|
44
|
+
for (const callback of callbacks) {
|
|
45
|
+
callback(...args);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Admin user credentials interface
|
|
3
|
+
* @interface AdminCredentials
|
|
4
|
+
* @property {string} email - Admin user email address
|
|
5
|
+
* @property {string} password - Admin user password
|
|
6
|
+
*/
|
|
7
|
+
interface AdminCredentials {
|
|
8
|
+
email: string;
|
|
9
|
+
password: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Creates default system users if they don't exist
|
|
13
|
+
* @function createAdminUser
|
|
14
|
+
* @param {AdminCredentials} credentials - Admin user credentials
|
|
15
|
+
* @returns {Promise<void>} A promise that resolves when the operation is complete
|
|
16
|
+
* @throws {Error} If admin credentials are invalid or if the operation fails
|
|
17
|
+
* @description
|
|
18
|
+
* This function performs the following operations:
|
|
19
|
+
* 1. Checks if an anonymous user exists, creates one if it doesn't
|
|
20
|
+
* 2. Checks if an administrator user exists, creates one if it doesn't
|
|
21
|
+
* 3. Uses the provided credentials for the administrator user
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```typescript
|
|
25
|
+
* // Create default system users
|
|
26
|
+
* await createAdminUser({
|
|
27
|
+
* email: 'admin@example.com',
|
|
28
|
+
* password: 'secure-password'
|
|
29
|
+
* });
|
|
30
|
+
*
|
|
31
|
+
* // The function will:
|
|
32
|
+
* // 1. Create an anonymous user if it doesn't exist
|
|
33
|
+
* // 2. Create an admin user with the provided credentials if it doesn't exist
|
|
34
|
+
* // 3. Do nothing if both users already exist
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export declare function createAdminUser({ email, password }: AdminCredentials): Promise<void>;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,110 @@
|
|
|
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.createAdminUser = createAdminUser;
|
|
37
|
+
const DataProvider = __importStar(require("../services/data_provider/service"));
|
|
38
|
+
const permissionManager_1 = require("../services/user_manager/permissionManager");
|
|
39
|
+
const userManager = __importStar(require("../services/user_manager/service"));
|
|
40
|
+
/**
|
|
41
|
+
* Creates default system users if they don't exist
|
|
42
|
+
* @function createAdminUser
|
|
43
|
+
* @param {AdminCredentials} credentials - Admin user credentials
|
|
44
|
+
* @returns {Promise<void>} A promise that resolves when the operation is complete
|
|
45
|
+
* @throws {Error} If admin credentials are invalid or if the operation fails
|
|
46
|
+
* @description
|
|
47
|
+
* This function performs the following operations:
|
|
48
|
+
* 1. Checks if an anonymous user exists, creates one if it doesn't
|
|
49
|
+
* 2. Checks if an administrator user exists, creates one if it doesn't
|
|
50
|
+
* 3. Uses the provided credentials for the administrator user
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* // Create default system users
|
|
55
|
+
* await createAdminUser({
|
|
56
|
+
* email: 'admin@example.com',
|
|
57
|
+
* password: 'secure-password'
|
|
58
|
+
* });
|
|
59
|
+
*
|
|
60
|
+
* // The function will:
|
|
61
|
+
* // 1. Create an anonymous user if it doesn't exist
|
|
62
|
+
* // 2. Create an admin user with the provided credentials if it doesn't exist
|
|
63
|
+
* // 3. Do nothing if both users already exist
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
async function createAdminUser({ email, password }) {
|
|
67
|
+
const authModel = DataProvider.getCollection('cms', 'auth');
|
|
68
|
+
try {
|
|
69
|
+
const isAnonymousExisted = await authModel.countDocuments({ type: 'anonymous' }).exec();
|
|
70
|
+
const isAdministratorExisted = await authModel
|
|
71
|
+
.countDocuments({ type: 'user', email: email })
|
|
72
|
+
.exec();
|
|
73
|
+
if (isAnonymousExisted === 0) {
|
|
74
|
+
await userManager.main.registerUser({
|
|
75
|
+
permissionGroup: (0, permissionManager_1.getDefaultAnonymousPermissionGroup)().title,
|
|
76
|
+
email: '',
|
|
77
|
+
phone: '',
|
|
78
|
+
password: '',
|
|
79
|
+
type: 'anonymous',
|
|
80
|
+
});
|
|
81
|
+
// await new authModel({
|
|
82
|
+
// permission: getDefaultAnonymousPermissionGroup().title,
|
|
83
|
+
// email: "",
|
|
84
|
+
// phone: "",
|
|
85
|
+
// password: "",
|
|
86
|
+
// type: "anonymous",
|
|
87
|
+
// }).save();
|
|
88
|
+
}
|
|
89
|
+
if (isAdministratorExisted === 0) {
|
|
90
|
+
if (!email || !password) {
|
|
91
|
+
return Promise.reject('Invalid email or password for admin user.');
|
|
92
|
+
}
|
|
93
|
+
await userManager.main.registerUser({
|
|
94
|
+
permissionGroup: (0, permissionManager_1.getDefaultAdministratorPermissionGroup)().title,
|
|
95
|
+
email: email,
|
|
96
|
+
password: password,
|
|
97
|
+
type: 'user',
|
|
98
|
+
});
|
|
99
|
+
// await new authModel({
|
|
100
|
+
// permission: getDefaultAdministratorPermissionGroup().title,
|
|
101
|
+
// email: email,
|
|
102
|
+
// password: password,
|
|
103
|
+
// type: "user",
|
|
104
|
+
// }).save();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
catch (e) {
|
|
108
|
+
return Promise.reject(e);
|
|
109
|
+
}
|
|
110
|
+
}
|