storemw-core-api 1.0.145 → 1.0.147
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/features/auth_token/authTokenRegistry.js +1 -1
- package/dist/features/auth_token/authTokenRegistry.js.map +1 -1
- package/dist/features/auth_token/authTokenType.d.ts +3 -2
- package/dist/features/auth_token/authTokenType.js.map +1 -1
- package/dist/features/core_config/coreConfigType.js.map +1 -1
- package/dist/features/file_storage/fileStorageType.d.ts +4 -3
- package/dist/features/file_storage/fileStorageType.js.map +1 -1
- package/dist/features/index.d.ts +3 -0
- package/dist/features/index.js +5 -1
- package/dist/features/index.js.map +1 -1
- package/dist/features/reset_password/resetPasswordType.d.ts +7 -6
- package/dist/features/reset_password/resetPasswordType.js.map +1 -1
- package/dist/features/smtp_email/smtpEmailType.d.ts +7 -6
- package/dist/features/smtp_email/smtpEmailType.js.map +1 -1
- package/dist/features/user_me/userMeRegister.d.ts +5 -0
- package/dist/features/user_me/userMeRegister.js +11 -0
- package/dist/features/user_me/userMeRegister.js.map +1 -0
- package/dist/features/user_me/userMeRegistry.d.ts +2 -0
- package/dist/features/user_me/userMeRegistry.js +14 -0
- package/dist/features/user_me/userMeRegistry.js.map +1 -0
- package/dist/features/user_me/userMeType.d.ts +9 -0
- package/dist/features/user_me/userMeType.js +3 -0
- package/dist/features/user_me/userMeType.js.map +1 -0
- package/dist/services/access_control/AccessControlService.js +2 -2
- package/dist/services/access_control/AccessControlService.js.map +1 -1
- package/dist/services/auth/AuthService.js +17 -2
- package/dist/services/auth/AuthService.js.map +1 -1
- package/dist/services/file/FileService.js +56 -50
- package/dist/services/file/FileService.js.map +1 -1
- package/dist/services/gateway/SmtpEmailService.js +12 -6
- package/dist/services/gateway/SmtpEmailService.js.map +1 -1
- package/dist/services/reset_password/ResetPasswordService.js +18 -12
- package/dist/services/reset_password/ResetPasswordService.js.map +1 -1
- package/dist/services/user/UserMeService.js +33 -211
- package/dist/services/user/UserMeService.js.map +1 -1
- package/dist/utils/featureUtils.d.ts +5 -0
- package/dist/utils/featureUtils.js +3 -0
- package/dist/utils/featureUtils.js.map +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/serviceUtils.d.ts +2 -18
- package/dist/utils/serviceUtils.js +0 -1
- package/dist/utils/serviceUtils.js.map +1 -1
- package/package.json +1 -1
|
@@ -4,7 +4,7 @@ exports.AuthTokenHook = void 0;
|
|
|
4
4
|
// import { throwError } from '../../utils'
|
|
5
5
|
// Runtime for injected hook
|
|
6
6
|
exports.AuthTokenHook = {
|
|
7
|
-
onSuccessAuthenticate: async (
|
|
7
|
+
onSuccessAuthenticate: async (props) => {
|
|
8
8
|
// console.log('authTokenResult', authTokenResult)
|
|
9
9
|
// example to add custom props into return auth token result
|
|
10
10
|
// return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authTokenRegistry.js","sourceRoot":"","sources":["../../../src/features/auth_token/authTokenRegistry.ts"],"names":[],"mappings":";;;AAEA,uCAAuC;AAEvC,4BAA4B;AACf,QAAA,aAAa,GAA0B;IAChD,qBAAqB,EAAE,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"authTokenRegistry.js","sourceRoot":"","sources":["../../../src/features/auth_token/authTokenRegistry.ts"],"names":[],"mappings":";;;AAEA,uCAAuC;AAEvC,4BAA4B;AACf,QAAA,aAAa,GAA0B;IAChD,qBAAqB,EAAE,KAAK,EAAE,KAA+C,EAAE,EAAE;QAE7E,kDAAkD;QAElD,4DAA4D;QAE5D,WAAW;QACX,0BAA0B;QAC1B,qBAAqB;QACrB,IAAI;IAGR,CAAC;CACJ,CAAA","sourcesContent":["import { FeatureAuthTokenProps, FeatureAuthTokenSuccessAuthenticateProps } from './authTokenType'\n\n// import { throwError } from '@/utils'\n\n// Runtime for injected hook\nexport const AuthTokenHook: FeatureAuthTokenProps = {\n onSuccessAuthenticate: async (props: FeatureAuthTokenSuccessAuthenticateProps) => {\n\n // console.log('authTokenResult', authTokenResult)\n\n // example to add custom props into return auth token result\n\n // return {\n // ...authTokenResult,\n // workerId: 1000\n // }\n\n\n }\n}"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AuthTokenResult } from "../../services";
|
|
2
|
-
|
|
2
|
+
import { FeatureCallbackProps } from '../../utils';
|
|
3
|
+
export type FeatureAuthTokenSuccessAuthenticateProps = FeatureCallbackProps<AuthTokenResult>;
|
|
3
4
|
export type FeatureAuthTokenProps = {
|
|
4
|
-
onSuccessAuthenticate
|
|
5
|
+
onSuccessAuthenticate?: (payload: FeatureAuthTokenSuccessAuthenticateProps) => Promise<any>;
|
|
5
6
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authTokenType.js","sourceRoot":"","sources":["../../../src/features/auth_token/authTokenType.ts"],"names":[],"mappings":"","sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"authTokenType.js","sourceRoot":"","sources":["../../../src/features/auth_token/authTokenType.ts"],"names":[],"mappings":"","sourcesContent":["import { AuthTokenResult } from \"../../services\"\nimport { FeatureCallbackProps } from '@/utils';\n\nexport type FeatureAuthTokenSuccessAuthenticateProps = FeatureCallbackProps<AuthTokenResult>\n\nexport type FeatureAuthTokenProps = {\n onSuccessAuthenticate?: (payload: FeatureAuthTokenSuccessAuthenticateProps) => Promise<any>\n}"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coreConfigType.js","sourceRoot":"","sources":["../../../src/features/core_config/coreConfigType.ts"],"names":[],"mappings":"","sourcesContent":["import { UserType } from \"@/services\"\nimport { AccessPolicyWithExtra } from \"@/access_control\"\n\nexport type FeatureCoreConfigOptions = {\n authSecretKey: string\n accessKeyEncryptionSecretKey: string\n prisma: any,\n\n // New optional hook for access control policies\n // extendAccessControl?: <ExtraScopes extends string>(\n // policies: Record<UserType, AccessPolicyWithExtra<ExtraScopes>>\n // ) => void\n\n /**\n * Hook to extend access control policies.\n * Must return the extra maps for consumer-defined scopes/modules/actions.\n */\n extendAccessControl?: <ExtraScopes extends string>(\n policies: Record<UserType, AccessPolicyWithExtra<ExtraScopes>>\n ) => {\n extraScopeModuleMap: Map<string, { value: string; label: string }[]>;\n extraActionMap: Map<string, string>;\n };\n}\n\nexport type FeatureCoreConfigProps = {\n onSetup: () => FeatureCoreConfigOptions\n}"]}
|
|
1
|
+
{"version":3,"file":"coreConfigType.js","sourceRoot":"","sources":["../../../src/features/core_config/coreConfigType.ts"],"names":[],"mappings":"","sourcesContent":["import { UserType } from \"@/services\"\nimport { AccessPolicyWithExtra } from \"@/access_control\"\n\nexport type FeatureCoreConfigOptions = {\n authSecretKey: string\n accessKeyEncryptionSecretKey: string\n prisma: any,\n\n // New optional hook for access control policies\n // extendAccessControl?: <ExtraScopes extends string>(\n // policies: Record<UserType, AccessPolicyWithExtra<ExtraScopes>>\n // ) => void\n\n /**\n * Hook to extend access control policies.\n * Must return the extra maps for consumer-defined scopes/modules/actions.\n */\n extendAccessControl?: <ExtraScopes extends string>(\n policies: Record<UserType, AccessPolicyWithExtra<ExtraScopes>>\n ) => {\n extraScopeModuleMap: Map<string, { value: string; label: string }[]>;\n extraActionMap: Map<string, string>;\n };\n}\n\n// export type FeatureCoreConfigOptions = {\n// authSecretKey: string\n// accessKeyEncryptionSecretKey: string\n// prisma: any,\n\n// // New optional hook for access control policies\n// // extendAccessControl?: <ExtraScopes extends string>(\n// // policies: Record<UserType, AccessPolicyWithExtra<ExtraScopes>>\n// // ) => void\n\n// /**\n// * Hook to extend access control policies.\n// * Must return the extra maps for consumer-defined scopes/modules/actions.\n// */\n// extendAccessControl?: <ExtraScopes extends string>(\n// policies: Record<UserType, AccessPolicyWithExtra<ExtraScopes>>\n// ) => {\n// extraScopeModuleMap: Map<string, { value: string; label: string }[]>;\n// extraActionMap: Map<string, string>;\n// };\n// }\n\nexport type FeatureCoreConfigProps = {\n onSetup: () => FeatureCoreConfigOptions\n}"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { FileStorageProviderType, FileLocalProviderOptions, FileGoogleCloudProviderOptions, FileAwsS3ProviderOptions, FileImageCompressionOptions, FileVideoCompressionOptions, FileUploadProps, FileCategoryName, FileUploadItem } from "../../services";
|
|
2
|
+
import { FeatureCallbackProps } from "../../utils";
|
|
2
3
|
export type FeatureFileStorageType = FileStorageProviderType;
|
|
3
4
|
export type FeatureFileStorageConfiguration = {
|
|
4
5
|
uploadMaxSize: number;
|
|
@@ -74,13 +75,13 @@ type DefaultUpload = {
|
|
|
74
75
|
imageCompressionOptions?: FileImageCompressionOptions;
|
|
75
76
|
videoCompressionOptions?: FileVideoCompressionOptions;
|
|
76
77
|
};
|
|
77
|
-
export type FeatureFileStorageStartUploadProps = DefaultUpload & {}
|
|
78
|
-
export type FeatureFileStorageSuccessUploadProps = DefaultUpload & {
|
|
78
|
+
export type FeatureFileStorageStartUploadProps = FeatureCallbackProps<DefaultUpload & {}>;
|
|
79
|
+
export type FeatureFileStorageSuccessUploadProps = FeatureCallbackProps<DefaultUpload & {
|
|
79
80
|
fileId: number;
|
|
80
81
|
fileThumbnailUrl: string;
|
|
81
82
|
fileAssetUrl: string;
|
|
82
83
|
fileDurationSeconds: number;
|
|
83
|
-
}
|
|
84
|
+
}>;
|
|
84
85
|
export type FeatureFileStorageProps = {
|
|
85
86
|
onSetup: () => Promise<FeatureFileStorageOptions>;
|
|
86
87
|
onStartUpload: (payload: FeatureFileStorageStartUploadProps) => Promise<any>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileStorageType.js","sourceRoot":"","sources":["../../../src/features/file_storage/fileStorageType.ts"],"names":[],"mappings":"","sourcesContent":["import {\n FileStorageProviderType,\n FileLocalProviderOptions,\n FileGoogleCloudProviderOptions,\n FileAwsS3ProviderOptions,\n FileImageCompressionOptions,\n FileVideoCompressionOptions,\n FileUploadProps,\n FileCategoryName,\n FileUploadItem\n} from \"../../services\";\n\nexport type FeatureFileStorageType = FileStorageProviderType\n\nexport type FeatureFileStorageConfiguration = {\n uploadMaxSize: number // e.g., 52428800 (50 MB)\n allowedFileTypes: string[] // e.g., [\"image/jpeg\", \"image/png\", \"application/pdf\", \"video/mp4\"]\n imageMaxWidth?: number // max width for images (e.g., 800)\n imageQuality?: number // compression quality (1-100)\n videoCRF?: number // Compression rate factor, lower = higher quality (e.g., 28)\n videoPreset?: \"ultrafast\" | \"superfast\" | \"veryfast\" | \"faster\" | \"fast\" | \"medium\" | \"slow\" | \"slower\" | \"veryslow\";\n videoResolution?: number; // Max width for videos, preserves aspect ratio (e.g., 1280)\n}\n\nexport type FeatureFileStorageLocalOptions = {\n basePath: string\n baseUrl: string\n skipFolderNameModuleRef: boolean\n skipFolderNameYearMonth: boolean\n}\n\nexport type FeatureFileStorageGoogleCloudOptions = {\n bucketName: string\n credentialPath: string\n baseUrl: string\n basePath: string\n skipFolderNameModuleRef: boolean\n skipFolderNameYearMonth: boolean\n}\n\nexport type FeatureFileStorageAwsS3Options = {\n bucketName: string\n region: string\n baseUrl: string\n basePath: string\n skipFolderNameModuleRef: boolean\n skipFolderNameYearMonth: boolean\n credentials: {\n accessKeyId: string\n secretAccessKey: string\n sessionToken?: string\n }\n}\n\n/* 🔑 Discriminated union */\nexport type FeatureFileStorageOptions =\n | {\n storageType: \"local\"\n storageConfiguration: FeatureFileStorageConfiguration\n localStorageOptions: FeatureFileStorageLocalOptions\n }\n | {\n storageType: \"gcloud\"\n storageConfiguration: FeatureFileStorageConfiguration\n gcloudStorageOptions: FeatureFileStorageGoogleCloudOptions\n }\n | {\n storageType: \"aws\"\n storageConfiguration: FeatureFileStorageConfiguration\n awsStorageOptions: FeatureFileStorageAwsS3Options\n }\n\ntype DefaultUpload = {\n fieldRef: FileUploadProps[\"field_ref\"],\n fieldModule: FileUploadProps[\"field_module\"],\n tagName: FileUploadProps[\"tagName\"],\n label: FileUploadProps[\"label\"],\n refId: FileUploadProps[\"refId\"],\n refId2: FileUploadProps[\"refId2\"],\n refLabel: FileUploadProps[\"refLabel\"],\n refLabel2: FileUploadProps[\"refLabel2\"],\n remark: FileUploadProps[\"remark\"],\n description: FileUploadProps[\"description\"],\n foldernameDate: FileUploadProps[\"foldernameDate\"],\n file: FileUploadItem,\n storageProviderName: FileStorageProviderType,\n storageProviderOptions: FileLocalProviderOptions | FileGoogleCloudProviderOptions | FileAwsS3ProviderOptions,\n fileCategoryName: FileCategoryName,\n batchCode: string,\n mimeType: string,\n bufferFilebuffer: Buffer,\n bufferFileThumbnail?: Buffer,\n outputSizeBytes: number,\n fileCompressFormat: any,\n imageCompressionOptions?: FileImageCompressionOptions,\n videoCompressionOptions?: FileVideoCompressionOptions\n}\n\nexport type FeatureFileStorageStartUploadProps = DefaultUpload & {\n\n}
|
|
1
|
+
{"version":3,"file":"fileStorageType.js","sourceRoot":"","sources":["../../../src/features/file_storage/fileStorageType.ts"],"names":[],"mappings":"","sourcesContent":["import {\n FileStorageProviderType,\n FileLocalProviderOptions,\n FileGoogleCloudProviderOptions,\n FileAwsS3ProviderOptions,\n FileImageCompressionOptions,\n FileVideoCompressionOptions,\n FileUploadProps,\n FileCategoryName,\n FileUploadItem\n} from \"../../services\";\n\nimport { FeatureCallbackProps } from \"@/utils\";\n\nexport type FeatureFileStorageType = FileStorageProviderType\n\nexport type FeatureFileStorageConfiguration = {\n uploadMaxSize: number // e.g., 52428800 (50 MB)\n allowedFileTypes: string[] // e.g., [\"image/jpeg\", \"image/png\", \"application/pdf\", \"video/mp4\"]\n imageMaxWidth?: number // max width for images (e.g., 800)\n imageQuality?: number // compression quality (1-100)\n videoCRF?: number // Compression rate factor, lower = higher quality (e.g., 28)\n videoPreset?: \"ultrafast\" | \"superfast\" | \"veryfast\" | \"faster\" | \"fast\" | \"medium\" | \"slow\" | \"slower\" | \"veryslow\";\n videoResolution?: number; // Max width for videos, preserves aspect ratio (e.g., 1280)\n}\n\nexport type FeatureFileStorageLocalOptions = {\n basePath: string\n baseUrl: string\n skipFolderNameModuleRef: boolean\n skipFolderNameYearMonth: boolean\n}\n\nexport type FeatureFileStorageGoogleCloudOptions = {\n bucketName: string\n credentialPath: string\n baseUrl: string\n basePath: string\n skipFolderNameModuleRef: boolean\n skipFolderNameYearMonth: boolean\n}\n\nexport type FeatureFileStorageAwsS3Options = {\n bucketName: string\n region: string\n baseUrl: string\n basePath: string\n skipFolderNameModuleRef: boolean\n skipFolderNameYearMonth: boolean\n credentials: {\n accessKeyId: string\n secretAccessKey: string\n sessionToken?: string\n }\n}\n\n/* 🔑 Discriminated union */\nexport type FeatureFileStorageOptions =\n | {\n storageType: \"local\"\n storageConfiguration: FeatureFileStorageConfiguration\n localStorageOptions: FeatureFileStorageLocalOptions\n }\n | {\n storageType: \"gcloud\"\n storageConfiguration: FeatureFileStorageConfiguration\n gcloudStorageOptions: FeatureFileStorageGoogleCloudOptions\n }\n | {\n storageType: \"aws\"\n storageConfiguration: FeatureFileStorageConfiguration\n awsStorageOptions: FeatureFileStorageAwsS3Options\n }\n\ntype DefaultUpload = {\n fieldRef: FileUploadProps[\"field_ref\"],\n fieldModule: FileUploadProps[\"field_module\"],\n tagName: FileUploadProps[\"tagName\"],\n label: FileUploadProps[\"label\"],\n refId: FileUploadProps[\"refId\"],\n refId2: FileUploadProps[\"refId2\"],\n refLabel: FileUploadProps[\"refLabel\"],\n refLabel2: FileUploadProps[\"refLabel2\"],\n remark: FileUploadProps[\"remark\"],\n description: FileUploadProps[\"description\"],\n foldernameDate: FileUploadProps[\"foldernameDate\"],\n file: FileUploadItem,\n storageProviderName: FileStorageProviderType,\n storageProviderOptions: FileLocalProviderOptions | FileGoogleCloudProviderOptions | FileAwsS3ProviderOptions,\n fileCategoryName: FileCategoryName,\n batchCode: string,\n mimeType: string,\n bufferFilebuffer: Buffer,\n bufferFileThumbnail?: Buffer,\n outputSizeBytes: number,\n fileCompressFormat: any,\n imageCompressionOptions?: FileImageCompressionOptions,\n videoCompressionOptions?: FileVideoCompressionOptions\n}\n\nexport type FeatureFileStorageStartUploadProps = FeatureCallbackProps<DefaultUpload & {\n\n}>\n\nexport type FeatureFileStorageSuccessUploadProps = FeatureCallbackProps<DefaultUpload & {\n fileId: number,\n fileThumbnailUrl: string,\n fileAssetUrl: string,\n fileDurationSeconds: number,\n}>\n\nexport type FeatureFileStorageProps = {\n onSetup: () => Promise<FeatureFileStorageOptions>,\n onStartUpload: (payload: FeatureFileStorageStartUploadProps) => Promise<any>\n onSuccessUpload: (payload: FeatureFileStorageSuccessUploadProps) => Promise<any>\n}"]}
|
package/dist/features/index.d.ts
CHANGED
|
@@ -13,3 +13,6 @@ export { registerSmtpEmailHook } from "./smtp_email/smtpEmailRegister";
|
|
|
13
13
|
export { FeatureFileStorageProps, FeatureFileStorageOptions, FeatureFileStorageConfiguration, FeatureFileStorageLocalOptions, FeatureFileStorageGoogleCloudOptions, FeatureFileStorageStartUploadProps, FeatureFileStorageSuccessUploadProps } from './file_storage/fileStorageType';
|
|
14
14
|
export { FileStorageHook } from "./file_storage/fileStorageRegistry";
|
|
15
15
|
export { registerFileStorageHook } from "./file_storage/fileStorageRegister";
|
|
16
|
+
export { FeatureUserMeProps, FeatureUserMeSuccessUpdateProps, FeatureUserMeSuccessChangePasswordProps, FeatureUserMeSuccessRemoveProps } from './user_me/userMeType';
|
|
17
|
+
export { UserMeHook } from "./user_me/userMeRegistry";
|
|
18
|
+
export { registerUserMeHook } from "./user_me/userMeRegister";
|
package/dist/features/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.registerFileStorageHook = exports.FileStorageHook = exports.registerSmtpEmailHook = exports.SmtpEmailHook = exports.registerResetPasswordHook = exports.ResetPasswordHook = exports.registerAuthTokenHook = exports.AuthTokenHook = exports.registerCoreConfigHook = exports.CoreConfigHook = void 0;
|
|
3
|
+
exports.registerUserMeHook = exports.UserMeHook = exports.registerFileStorageHook = exports.FileStorageHook = exports.registerSmtpEmailHook = exports.SmtpEmailHook = exports.registerResetPasswordHook = exports.ResetPasswordHook = exports.registerAuthTokenHook = exports.AuthTokenHook = exports.registerCoreConfigHook = exports.CoreConfigHook = void 0;
|
|
4
4
|
var coreConfigRegistry_1 = require("./core_config/coreConfigRegistry");
|
|
5
5
|
Object.defineProperty(exports, "CoreConfigHook", { enumerable: true, get: function () { return coreConfigRegistry_1.CoreConfigHook; } });
|
|
6
6
|
var coreConfigRegister_1 = require("./core_config/coreConfigRegister");
|
|
@@ -21,4 +21,8 @@ var fileStorageRegistry_1 = require("./file_storage/fileStorageRegistry");
|
|
|
21
21
|
Object.defineProperty(exports, "FileStorageHook", { enumerable: true, get: function () { return fileStorageRegistry_1.FileStorageHook; } });
|
|
22
22
|
var fileStorageRegister_1 = require("./file_storage/fileStorageRegister");
|
|
23
23
|
Object.defineProperty(exports, "registerFileStorageHook", { enumerable: true, get: function () { return fileStorageRegister_1.registerFileStorageHook; } });
|
|
24
|
+
var userMeRegistry_1 = require("./user_me/userMeRegistry");
|
|
25
|
+
Object.defineProperty(exports, "UserMeHook", { enumerable: true, get: function () { return userMeRegistry_1.UserMeHook; } });
|
|
26
|
+
var userMeRegister_1 = require("./user_me/userMeRegister");
|
|
27
|
+
Object.defineProperty(exports, "registerUserMeHook", { enumerable: true, get: function () { return userMeRegister_1.registerUserMeHook; } });
|
|
24
28
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/features/index.ts"],"names":[],"mappings":";;;AACA,uEAAiE;AAAxD,oHAAA,cAAc,OAAA;AACvB,uEAAyE;AAAhE,4HAAA,sBAAsB,OAAA;AAG/B,oEAA8D;AAArD,kHAAA,aAAa,OAAA;AACtB,oEAAsE;AAA7D,0HAAA,qBAAqB,OAAA;AAG9B,gFAA0E;AAAjE,0HAAA,iBAAiB,OAAA;AAC1B,gFAAkF;AAAzE,kIAAA,yBAAyB,OAAA;AAGlC,oEAA8D;AAArD,kHAAA,aAAa,OAAA;AACtB,oEAAsE;AAA7D,0HAAA,qBAAqB,OAAA;AAG9B,0EAAoE;AAA3D,sHAAA,eAAe,OAAA;AACxB,0EAA4E;AAAnE,8HAAA,uBAAuB,OAAA","sourcesContent":["export { FeatureCoreConfigProps, FeatureCoreConfigOptions } from './core_config/coreConfigType'\nexport { CoreConfigHook } from \"./core_config/coreConfigRegistry\"\nexport { registerCoreConfigHook } from \"./core_config/coreConfigRegister\"\n\nexport { FeatureAuthTokenProps, FeatureAuthTokenSuccessAuthenticateProps } from './auth_token/authTokenType'\nexport { AuthTokenHook } from \"./auth_token/authTokenRegistry\"\nexport { registerAuthTokenHook } from \"./auth_token/authTokenRegister\"\n\nexport { FeatureResetPasswordProps, FeatureResetPasswordSuccessProps, FeatureResetPasswordRequestProps } from './reset_password/resetPasswordType'\nexport { ResetPasswordHook } from \"./reset_password/resetPasswordRegistry\"\nexport { registerResetPasswordHook } from \"./reset_password/resetPasswordRegister\"\n\nexport { FeatureSmtpEmailProps, FeatureSmtpEmailOptions, FeatureSmtpEmailHbsOptions, FeatureSmtpEmailStartSendProps, FeatureSmtpEmailSuccessSendProps } from './smtp_email/smtpEmailType'\nexport { SmtpEmailHook } from \"./smtp_email/smtpEmailRegistry\"\nexport { registerSmtpEmailHook } from \"./smtp_email/smtpEmailRegister\"\n\nexport { FeatureFileStorageProps, FeatureFileStorageOptions, FeatureFileStorageConfiguration, FeatureFileStorageLocalOptions, FeatureFileStorageGoogleCloudOptions, FeatureFileStorageStartUploadProps, FeatureFileStorageSuccessUploadProps } from './file_storage/fileStorageType'\nexport { FileStorageHook } from \"./file_storage/fileStorageRegistry\"\nexport { registerFileStorageHook } from \"./file_storage/fileStorageRegister\""]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/features/index.ts"],"names":[],"mappings":";;;AACA,uEAAiE;AAAxD,oHAAA,cAAc,OAAA;AACvB,uEAAyE;AAAhE,4HAAA,sBAAsB,OAAA;AAG/B,oEAA8D;AAArD,kHAAA,aAAa,OAAA;AACtB,oEAAsE;AAA7D,0HAAA,qBAAqB,OAAA;AAG9B,gFAA0E;AAAjE,0HAAA,iBAAiB,OAAA;AAC1B,gFAAkF;AAAzE,kIAAA,yBAAyB,OAAA;AAGlC,oEAA8D;AAArD,kHAAA,aAAa,OAAA;AACtB,oEAAsE;AAA7D,0HAAA,qBAAqB,OAAA;AAG9B,0EAAoE;AAA3D,sHAAA,eAAe,OAAA;AACxB,0EAA4E;AAAnE,8HAAA,uBAAuB,OAAA;AAGhC,2DAAqD;AAA5C,4GAAA,UAAU,OAAA;AACnB,2DAA6D;AAApD,oHAAA,kBAAkB,OAAA","sourcesContent":["export { FeatureCoreConfigProps, FeatureCoreConfigOptions } from './core_config/coreConfigType'\nexport { CoreConfigHook } from \"./core_config/coreConfigRegistry\"\nexport { registerCoreConfigHook } from \"./core_config/coreConfigRegister\"\n\nexport { FeatureAuthTokenProps, FeatureAuthTokenSuccessAuthenticateProps } from './auth_token/authTokenType'\nexport { AuthTokenHook } from \"./auth_token/authTokenRegistry\"\nexport { registerAuthTokenHook } from \"./auth_token/authTokenRegister\"\n\nexport { FeatureResetPasswordProps, FeatureResetPasswordSuccessProps, FeatureResetPasswordRequestProps } from './reset_password/resetPasswordType'\nexport { ResetPasswordHook } from \"./reset_password/resetPasswordRegistry\"\nexport { registerResetPasswordHook } from \"./reset_password/resetPasswordRegister\"\n\nexport { FeatureSmtpEmailProps, FeatureSmtpEmailOptions, FeatureSmtpEmailHbsOptions, FeatureSmtpEmailStartSendProps, FeatureSmtpEmailSuccessSendProps } from './smtp_email/smtpEmailType'\nexport { SmtpEmailHook } from \"./smtp_email/smtpEmailRegistry\"\nexport { registerSmtpEmailHook } from \"./smtp_email/smtpEmailRegister\"\n\nexport { FeatureFileStorageProps, FeatureFileStorageOptions, FeatureFileStorageConfiguration, FeatureFileStorageLocalOptions, FeatureFileStorageGoogleCloudOptions, FeatureFileStorageStartUploadProps, FeatureFileStorageSuccessUploadProps } from './file_storage/fileStorageType'\nexport { FileStorageHook } from \"./file_storage/fileStorageRegistry\"\nexport { registerFileStorageHook } from \"./file_storage/fileStorageRegister\"\n\nexport { FeatureUserMeProps, FeatureUserMeSuccessUpdateProps, FeatureUserMeSuccessChangePasswordProps, FeatureUserMeSuccessRemoveProps } from './user_me/userMeType'\nexport { UserMeHook } from \"./user_me/userMeRegistry\"\nexport { registerUserMeHook } from \"./user_me/userMeRegister\""]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { OneTimeCodeType, ResetPasswordMethod } from "../../services";
|
|
2
|
-
|
|
2
|
+
import { FeatureCallbackProps } from "../../utils";
|
|
3
|
+
export type FeatureResetPasswordRequestProps = FeatureCallbackProps<{
|
|
3
4
|
userId: number;
|
|
4
5
|
userType: string;
|
|
5
6
|
resetPasswordMethod: ResetPasswordMethod;
|
|
@@ -7,19 +8,19 @@ export type FeatureResetPasswordRequestProps = {
|
|
|
7
8
|
mobileNumber: string;
|
|
8
9
|
oneTimeCode: string;
|
|
9
10
|
user: any;
|
|
10
|
-
}
|
|
11
|
-
export type FeatureResetPasswordSuccessProps = {
|
|
11
|
+
}>;
|
|
12
|
+
export type FeatureResetPasswordSuccessProps = FeatureCallbackProps<{
|
|
12
13
|
userId: number;
|
|
13
14
|
userType: string;
|
|
14
15
|
resetPasswordMethod: ResetPasswordMethod;
|
|
15
16
|
oneTimeCode: string;
|
|
16
17
|
user: any;
|
|
17
|
-
}
|
|
18
|
+
}>;
|
|
18
19
|
export type FeatureResetPasswordProps = {
|
|
19
20
|
onSetup: () => {
|
|
20
21
|
oneTimeCodeType: OneTimeCodeType;
|
|
21
22
|
resetPasswordMethod: ResetPasswordMethod;
|
|
22
23
|
};
|
|
23
|
-
onRequest: (
|
|
24
|
-
onSuccess: (
|
|
24
|
+
onRequest: (props: FeatureResetPasswordRequestProps) => Promise<any>;
|
|
25
|
+
onSuccess: (props: FeatureResetPasswordSuccessProps) => Promise<any>;
|
|
25
26
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resetPasswordType.js","sourceRoot":"","sources":["../../../src/features/reset_password/resetPasswordType.ts"],"names":[],"mappings":"","sourcesContent":["import { OneTimeCodeType, ResetPasswordMethod } from \"../../services\";\n\nexport type FeatureResetPasswordRequestProps = {\n userId: number\n userType: string\n resetPasswordMethod: ResetPasswordMethod,\n emailAddress: string\n mobileNumber: string\n oneTimeCode: string\n user: any\n}
|
|
1
|
+
{"version":3,"file":"resetPasswordType.js","sourceRoot":"","sources":["../../../src/features/reset_password/resetPasswordType.ts"],"names":[],"mappings":"","sourcesContent":["import { OneTimeCodeType, ResetPasswordMethod } from \"../../services\";\n\nimport { FeatureCallbackProps } from \"@/utils\"\n\nexport type FeatureResetPasswordRequestProps = FeatureCallbackProps<{\n userId: number\n userType: string\n resetPasswordMethod: ResetPasswordMethod,\n emailAddress: string\n mobileNumber: string\n oneTimeCode: string\n user: any\n}>\n\nexport type FeatureResetPasswordSuccessProps = FeatureCallbackProps<{\n userId: number\n userType: string\n resetPasswordMethod: ResetPasswordMethod\n oneTimeCode: string\n user: any\n}>\n\nexport type FeatureResetPasswordProps = {\n onSetup: () => {\n oneTimeCodeType: OneTimeCodeType;\n resetPasswordMethod: ResetPasswordMethod;\n },\n onRequest: (props: FeatureResetPasswordRequestProps) => Promise<any>\n onSuccess: (props: FeatureResetPasswordSuccessProps) => Promise<any>\n}"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SmtpEmailTransporterOptions } from "../../services";
|
|
2
|
+
import { FeatureCallbackProps } from "../../utils";
|
|
2
3
|
export type FeatureSmtpEmailHbsOptions = {
|
|
3
4
|
viewPath: string;
|
|
4
5
|
extName: ".hbs";
|
|
@@ -20,18 +21,18 @@ export type FeatureSmtpEmailOptions = {
|
|
|
20
21
|
connectionTimeout: number;
|
|
21
22
|
hbsOptions: FeatureSmtpEmailHbsOptions;
|
|
22
23
|
};
|
|
23
|
-
export type FeatureSmtpEmailStartSendProps = {
|
|
24
|
+
export type FeatureSmtpEmailStartSendProps = FeatureCallbackProps<{
|
|
24
25
|
smtpEmailOptions: FeatureSmtpEmailOptions;
|
|
25
26
|
transporterOptions: SmtpEmailTransporterOptions;
|
|
26
|
-
}
|
|
27
|
-
export type FeatureSmtpEmailSuccessSendProps = {
|
|
27
|
+
}>;
|
|
28
|
+
export type FeatureSmtpEmailSuccessSendProps = FeatureCallbackProps<{
|
|
28
29
|
smtpEmailOptions: FeatureSmtpEmailOptions;
|
|
29
30
|
transporterOptions: SmtpEmailTransporterOptions;
|
|
30
31
|
previewMessageUrl: string | false;
|
|
31
32
|
gatewayDetails: any;
|
|
32
|
-
}
|
|
33
|
+
}>;
|
|
33
34
|
export type FeatureSmtpEmailProps = {
|
|
34
35
|
onSetup: () => Promise<FeatureSmtpEmailOptions>;
|
|
35
|
-
onStartSend: (
|
|
36
|
-
onSuccessSend: (
|
|
36
|
+
onStartSend: (props: FeatureSmtpEmailStartSendProps) => Promise<any>;
|
|
37
|
+
onSuccessSend: (props: FeatureSmtpEmailSuccessSendProps) => Promise<any>;
|
|
37
38
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"smtpEmailType.js","sourceRoot":"","sources":["../../../src/features/smtp_email/smtpEmailType.ts"],"names":[],"mappings":"","sourcesContent":["import { SmtpEmailTransporterOptions } from \"../../services\"\n\nexport type FeatureSmtpEmailHbsOptions = {\n viewPath: string // path to templates folder\n extName: \".hbs\" // extension for templates, e.g., \".hbs\"\n viewEngine: {\n extname: \".hbs\", // file extension of templates\n layoutsDir: string // folder for layout files\n partialsDir: string // folder for partial templates\n defaultLayout: string | false // default layout name or false\n // helpers?: Record<string, (...args: any[]) => any>\n }\n}\n\nexport type FeatureSmtpEmailOptions = {\n smtpHost: string\n smtpPort: number\n smtpSecure: boolean\n smtpCredential: {\n username: string\n password: string\n },\n connectionTimeout: number\n hbsOptions: FeatureSmtpEmailHbsOptions\n}\n\nexport type FeatureSmtpEmailStartSendProps = {\n smtpEmailOptions: FeatureSmtpEmailOptions\n transporterOptions: SmtpEmailTransporterOptions\n}
|
|
1
|
+
{"version":3,"file":"smtpEmailType.js","sourceRoot":"","sources":["../../../src/features/smtp_email/smtpEmailType.ts"],"names":[],"mappings":"","sourcesContent":["import { SmtpEmailTransporterOptions } from \"../../services\"\n\nimport { FeatureCallbackProps } from \"@/utils\"\n\nexport type FeatureSmtpEmailHbsOptions = {\n viewPath: string // path to templates folder\n extName: \".hbs\" // extension for templates, e.g., \".hbs\"\n viewEngine: {\n extname: \".hbs\", // file extension of templates\n layoutsDir: string // folder for layout files\n partialsDir: string // folder for partial templates\n defaultLayout: string | false // default layout name or false\n // helpers?: Record<string, (...args: any[]) => any>\n }\n}\n\nexport type FeatureSmtpEmailOptions = {\n smtpHost: string\n smtpPort: number\n smtpSecure: boolean\n smtpCredential: {\n username: string\n password: string\n },\n connectionTimeout: number\n hbsOptions: FeatureSmtpEmailHbsOptions\n}\n\nexport type FeatureSmtpEmailStartSendProps = FeatureCallbackProps<{\n smtpEmailOptions: FeatureSmtpEmailOptions\n transporterOptions: SmtpEmailTransporterOptions\n}>\n\nexport type FeatureSmtpEmailSuccessSendProps = FeatureCallbackProps<{\n smtpEmailOptions: FeatureSmtpEmailOptions\n transporterOptions: SmtpEmailTransporterOptions\n previewMessageUrl: string | false\n gatewayDetails: any\n}>\n\nexport type FeatureSmtpEmailProps = {\n onSetup: () => Promise<FeatureSmtpEmailOptions>,\n onStartSend: (props: FeatureSmtpEmailStartSendProps) => Promise<any>\n onSuccessSend: (props: FeatureSmtpEmailSuccessSendProps) => Promise<any>\n}"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerUserMeHook = registerUserMeHook;
|
|
4
|
+
const userMeRegistry_1 = require("./userMeRegistry");
|
|
5
|
+
/**
|
|
6
|
+
* Register consumer-provided hooks for user/me
|
|
7
|
+
*/
|
|
8
|
+
function registerUserMeHook(hooks) {
|
|
9
|
+
Object.assign(userMeRegistry_1.UserMeHook, hooks);
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=userMeRegister.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"userMeRegister.js","sourceRoot":"","sources":["../../../src/features/user_me/userMeRegister.ts"],"names":[],"mappings":";;AAMA,gDAEC;AAPD,qDAA6C;AAE7C;;GAEG;AACH,SAAgB,kBAAkB,CAAC,KAAyB;IACxD,MAAM,CAAC,MAAM,CAAC,2BAAU,EAAE,KAAK,CAAC,CAAA;AACpC,CAAC","sourcesContent":["import { FeatureUserMeProps } from './userMeType'\nimport { UserMeHook } from './userMeRegistry'\n\n/**\n * Register consumer-provided hooks for user/me\n */\nexport function registerUserMeHook(hooks: FeatureUserMeProps) {\n Object.assign(UserMeHook, hooks)\n}"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.UserMeHook = void 0;
|
|
4
|
+
// import { throwError } from '../../utils'
|
|
5
|
+
// Runtime for injected hook
|
|
6
|
+
exports.UserMeHook = {
|
|
7
|
+
onSuccessUpdateMe: async (props) => {
|
|
8
|
+
},
|
|
9
|
+
onSuccessChangePasswordMe: async (props) => {
|
|
10
|
+
},
|
|
11
|
+
onSuccessRemoveMe: async (props) => {
|
|
12
|
+
},
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=userMeRegistry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"userMeRegistry.js","sourceRoot":"","sources":["../../../src/features/user_me/userMeRegistry.ts"],"names":[],"mappings":";;;AAEA,uCAAuC;AAEvC,4BAA4B;AACf,QAAA,UAAU,GAAuB;IAC1C,iBAAiB,EAAE,KAAK,EAAE,KAAsC,EAAE,EAAE;IACpE,CAAC;IACD,yBAAyB,EAAE,KAAK,EAAE,KAA8C,EAAE,EAAE;IACpF,CAAC;IACD,iBAAiB,EAAE,KAAK,EAAE,KAAsC,EAAE,EAAE;IACpE,CAAC;CACJ,CAAA","sourcesContent":["import { FeatureUserMeProps, FeatureUserMeSuccessUpdateProps, FeatureUserMeSuccessChangePasswordProps, FeatureUserMeSuccessRemoveProps } from './userMeType'\n\n// import { throwError } from '@/utils'\n\n// Runtime for injected hook\nexport const UserMeHook: FeatureUserMeProps = {\n onSuccessUpdateMe: async (props: FeatureUserMeSuccessUpdateProps) => {\n },\n onSuccessChangePasswordMe: async (props: FeatureUserMeSuccessChangePasswordProps) => {\n },\n onSuccessRemoveMe: async (props: FeatureUserMeSuccessRemoveProps) => {\n },\n}"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { FeatureCallbackProps } from "../../utils";
|
|
2
|
+
export type FeatureUserMeSuccessUpdateProps = FeatureCallbackProps<{}>;
|
|
3
|
+
export type FeatureUserMeSuccessChangePasswordProps = FeatureCallbackProps<{}>;
|
|
4
|
+
export type FeatureUserMeSuccessRemoveProps = FeatureCallbackProps<{}>;
|
|
5
|
+
export type FeatureUserMeProps = {
|
|
6
|
+
onSuccessUpdateMe?: (payload: FeatureUserMeSuccessUpdateProps) => Promise<any>;
|
|
7
|
+
onSuccessChangePasswordMe?: (payload: FeatureUserMeSuccessChangePasswordProps) => Promise<any>;
|
|
8
|
+
onSuccessRemoveMe?: (payload: FeatureUserMeSuccessRemoveProps) => Promise<any>;
|
|
9
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"userMeType.js","sourceRoot":"","sources":["../../../src/features/user_me/userMeType.ts"],"names":[],"mappings":"","sourcesContent":["import { FeatureCallbackProps } from \"@/utils\"\n\nexport type FeatureUserMeSuccessUpdateProps = FeatureCallbackProps<{\n}>\n\nexport type FeatureUserMeSuccessChangePasswordProps = FeatureCallbackProps<{\n}>\n\nexport type FeatureUserMeSuccessRemoveProps = FeatureCallbackProps<{\n}>\n\nexport type FeatureUserMeProps = {\n onSuccessUpdateMe?: (payload: FeatureUserMeSuccessUpdateProps) => Promise<any>\n onSuccessChangePasswordMe?: (payload: FeatureUserMeSuccessChangePasswordProps) => Promise<any>\n onSuccessRemoveMe?: (payload: FeatureUserMeSuccessRemoveProps) => Promise<any>\n}"]}
|
|
@@ -15,8 +15,8 @@ const AccessControlService = (props) => {
|
|
|
15
15
|
const coreConfig = features_1.CoreConfigHook.onSetup();
|
|
16
16
|
// If extendAccessControl exists and now returns maps
|
|
17
17
|
let maps = {};
|
|
18
|
-
if (coreConfig
|
|
19
|
-
maps = coreConfig
|
|
18
|
+
if (coreConfig?.extendAccessControl) {
|
|
19
|
+
maps = coreConfig?.extendAccessControl(access_control_1.userTypePolicies); // merge policies + get maps
|
|
20
20
|
}
|
|
21
21
|
// coreConfig.extendAccessControl?.(userTypePolicies);
|
|
22
22
|
isExtended = true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AccessControlService.js","sourceRoot":"","sources":["../../../src/services/access_control/AccessControlService.ts"],"names":[],"mappings":";;;AAEA,yCAA4C;AAE5C,qDAW0B;AAI1B,mCAAqC;AAiB9B,MAAM,oBAAoB,GAAG,CAIlC,KAAgC,EAAE,EAAE;IAElC,IAAI,UAAU,GAAG,KAAK,CAAC;IAEvB,yDAAyD;IACzD,IAAI,mBAAgF,CAAC;IACrF,IAAI,cAA+C,CAAC;IAEpD,MAAM,eAAe,GAAG,CAAC,QAAkB,EAAE,EAAE;QAC3C,kCAAkC;QAClC,IAAI,CAAC,UAAU,EAAE,CAAC;YACd,MAAM,UAAU,GAAG,yBAAc,CAAC,OAAO,EAAE,CAAC;YAE5C,qDAAqD;YACrD,IAAI,IAAI,GAGJ,EAAE,CAAC;YAEP,IAAI,UAAU,CAAC,mBAAmB,EAAE,CAAC;gBACjC,IAAI,GAAG,UAAU,CAAC,mBAAmB,CAAC,iCAAuB,CAAC,CAAC,CAAC,4BAA4B;YAChG,CAAC;YAED,s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E;QAEnF,qBAAqB;QACrB,MAAM,KAAK,GAAG,QAAQ,IAAK,KAAK,CAAC,cAA2B,CAAC;QAE7D,IAAI,CAAC,KAAK;YAAE,IAAA,kBAAU,EAAC,mBAAmB,CAAC,CAAC;QAE5C,oDAAoD;QACpD,MAAM,EAAE,MAAM,EAAE,mBAAmB,EAAE,cAAc,EAAE,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QAE/E,MAAM,UAAU,GAAG,cAAc,CAAC,MAAM,EAAE,mBAAmB,EAAE,cAAc,CAAC,CAAC;QAE/E,OAAO;YACH,OAAO,EAAE,UAAU;SACtB,CAAC;IACN,CAAC,CAAC;IAIF,kCAAkC;IAClC,wDAAwD;IACxD,kFAAkF;IAClF,4EAA4E;IAC5E,KAAK;IACL,gBAAgB;IAChB,iBAAiB;IACjB,gBAAgB;IAChB,kBAAkB;IAClB,4CAA4C;IAE5C,yDAAyD;IAEzD,+FAA+F;IAE/F,sFAAsF;IACtF,mEAAmE;IACnE,KAAK;IAEL,kDAAkD;IAClD,4CAA4C;IAC5C,wDAAwD;IACxD,kFAAkF;IAClF,4EAA4E;IAC5E,KAAK;IACL,gBAAgB;IAChB,iBAAiB;IACjB,gBAAgB;IAChB,SAAS;IACT,+DAA+D;IAC/D,6CAA6C;IAC7C,0FAA0F;IAC1F,gEAAgE;IAChE,kBAAkB;IAClB,SAAS;IACT,KAAK;IAEL,OAAO;QACH,eAAe;QACf,eAAe;QACf,WAAW;QACX,qBAAqB;QACrB,8BAA8B;QAC9B,kCAAkC;KACrC,CAAC;AACN,CAAC,CAAC;AA5PW,QAAA,oBAAoB,wBA4P/B","sourcesContent":["import { NextFunction, Request } from \"express\";\nimport { UserType } from \"@/services\";\nimport { CoreConfigHook } from \"@/features\";\n\nimport {\n AccessPolicyWithExtra,\n AccessControlScope,\n AccessControlModuleOf,\n AccessControlAction,\n\n accessControlScopesMap,\n accessControlModulesMap,\n accessControlActionsMap,\n\n userTypePolicies\n} from \"@/access_control\";\n\nimport { DefaultServiceProps, getDefaultServiceProps } from \"@/utils\";\n\nimport { throwError } from \"@/utils\";\n\n// Intersection type for requests\ntype AuthRequest = Request & { actionUserType?: UserType };\n\n// Helper type: core scopes + extra scopes if provided\nexport type AccessControlScopeOrExtra<ExtraScopes extends string> =\n [ExtraScopes] extends [never] ? AccessControlScope : AccessControlScope | ExtraScopes;\n\nexport type AccessControlServiceProps = DefaultServiceProps & {\n // userType: UserType\n};\n\nexport type AccessControlListOptionsProps = {\n userType?: UserType\n};\n\nexport const AccessControlService = <\n ExtraScopes extends string = never,\n ExtraModules extends Record<ExtraScopes, string> = Record<ExtraScopes, string>,\n ExtraActions extends Record<ExtraScopes, Record<string, string>> = Record<ExtraScopes, Record<string, string>>\n>(props: AccessControlServiceProps) => {\n\n let isExtended = false;\n\n // 🟢 Service-level variables to store maps from consumer\n let extraScopeModuleMap: Map<string, { value: string; label: string }[]> | undefined;\n let extraActionMap: Map<string, string> | undefined;\n\n const getAccessPolicy = (userType: UserType) => {\n // Apply consumer extras only once\n if (!isExtended) {\n const coreConfig = CoreConfigHook.onSetup();\n\n // If extendAccessControl exists and now returns maps\n let maps: {\n extraScopeModuleMap?: Map<string, { value: string; label: string }[]>;\n extraActionMap?: Map<string, string>;\n } = {};\n\n if (coreConfig.extendAccessControl) {\n maps = coreConfig.extendAccessControl(userTypePolicies as any); // merge policies + get maps\n }\n\n // coreConfig.extendAccessControl?.(userTypePolicies);\n\n isExtended = true;\n\n // Store maps in service-level variables so we can reuse\n extraScopeModuleMap = maps.extraScopeModuleMap;\n extraActionMap = maps.extraActionMap;\n }\n\n // console.log('userTypePolicies', userTypePolicies)\n\n const policy = userTypePolicies[userType] as AccessPolicyWithExtra<ExtraScopes>;\n if (!policy || Object.keys(policy).length <= 0) throwError(`Empty access control policy for user type: ${userType}`);\n\n // Return policy + maps\n return {\n policy,\n extraScopeModuleMap,\n extraActionMap,\n };\n\n };\n\n const getUserType = (req: AuthRequest) => {\n const userType = req?.actionUserType ?? \"\";\n if (!userType) throwError(\"Invalid user type in request for access control\");\n return userType;\n };\n\n const isActionAllowed = <\n S extends AccessControlScope | ExtraScopes\n >(\n policy: AccessPolicyWithExtra<ExtraScopes>,\n scope: S,\n module: S extends AccessControlScope ? AccessControlModuleOf<S> : string,\n action: S extends AccessControlScope ? AccessControlAction : string\n ): boolean => {\n const scopePolicy = policy[scope as keyof typeof policy] as\n | Record<string, Record<string, boolean>>\n | undefined;\n if (!scopePolicy) return false;\n\n const modulePolicy = scopePolicy[module];\n if (!modulePolicy) return false;\n\n return modulePolicy[action as string] ?? false;\n };\n\n const checkAccess = <\n S extends AccessControlScope | ExtraScopes,\n M extends S extends AccessControlScope ? AccessControlModuleOf<S> : string,\n A extends S extends AccessControlScope ? AccessControlAction : string\n >(\n userType: UserType,\n policy: AccessPolicyWithExtra<ExtraScopes>,\n scope: S,\n module: M,\n action: A\n ): boolean => {\n // TS infers ExtraScopes, S, M, A automatically\n const allowed = isActionAllowed(policy, scope, module, action);\n\n if (!allowed) throwError(`Access denied: ${scope}.${module}.${action} (${userType})`);\n return allowed;\n };\n\n // ------------------\n // Programmatic validator\n // ------------------\n const validateAccessControl = <\n S extends AccessControlScopeOrExtra<ExtraScopes>,\n M extends S extends AccessControlScope\n ? AccessControlModuleOf<S>\n : ExtraModules[S & keyof ExtraModules],\n A extends S extends AccessControlScope\n ? AccessControlAction\n : ExtraActions[S & keyof ExtraActions][M & keyof ExtraActions[S & keyof ExtraActions]]\n >(\n req: Request,\n scope: S,\n module: M,\n action: A\n ): boolean => {\n\n const userType = getUserType(req);\n\n if (!userType) throwError(\"Invalid user type\");\n\n const { policy } = getAccessPolicy(userType)\n\n return checkAccess(userType, policy, scope, module, action);\n };\n\n /** for listAccessControlPolicyOptions */\n const buildScopeTree = <\n T extends AccessPolicyWithExtra<any, any, any>\n >(\n policy: T,\n extraScopeModuleMap?: Map<string, { value: string; label: string }[]>,\n extraActionMap?: Map<string, string>\n ) => {\n const scopes: {\n key: string;\n label: string;\n modules: {\n key: string;\n label: string;\n actions: { key: string; label: string }[];\n }[];\n }[] = [];\n\n // Loop through each scope in the policy\n Object.entries(policy).forEach(([scopeKey, modules]) => {\n // Build modules array for this scope\n const modulesArr: {\n key: string;\n label: string;\n actions: { key: string; label: string }[];\n }[] = [];\n\n Object.entries(modules as Record<string, Record<string, boolean>>).forEach(\n ([moduleKey, actions]) => {\n const actionArr = Object.entries(actions)\n .filter(([_, allowed]) => allowed) // Only include true actions\n .map(([actionKey]) => ({\n key: actionKey,\n permission_key: `${scopeKey}.${moduleKey}.${actionKey}`,\n label:\n accessControlActionsMap.get(actionKey as AccessControlAction) ||\n extraActionMap?.get(actionKey) ||\n actionKey,\n }));\n\n if (actionArr.length > 0) {\n modulesArr.push({\n key: moduleKey,\n label:\n accessControlModulesMap.get(scopeKey as AccessControlScope)?.find(\n (m) => m.value === moduleKey\n )?.label || extraScopeModuleMap?.get(scopeKey)?.find((m) => m.value === moduleKey)?.label || moduleKey,\n actions: actionArr,\n });\n }\n }\n );\n\n if (modulesArr.length > 0) {\n scopes.push({\n key: scopeKey,\n label:\n accessControlScopesMap.get(scopeKey as AccessControlScope) ||\n extraScopeModuleMap?.get(scopeKey)?.[0]?.label ||\n scopeKey,\n modules: modulesArr,\n });\n }\n });\n\n return { scopes };\n };\n\n const listAccessControlPolicyOptions = ({ userType }: AccessControlListOptionsProps) => {\n\n // Determine userType\n const uType = userType || (props.actionUserType as UserType);\n\n if (!uType) throwError(\"Invalid user type\");\n\n // Get full policy (core + extra) for this user type\n const { policy, extraScopeModuleMap, extraActionMap } = getAccessPolicy(uType);\n\n const policyTree = buildScopeTree(policy, extraScopeModuleMap, extraActionMap);\n\n return {\n options: policyTree\n };\n };\n\n\n\n // const validateAccessControl = <\n // S extends AccessControlScopeOrExtra<ExtraScopes>,\n // M extends S extends AccessControlScope ? AccessControlModuleOf<S> : string,\n // A extends S extends AccessControlScope ? AccessControlAction : string\n // >(\n // scope: S,\n // module: M,\n // action: A\n // ): boolean => {\n // // const userType = getUserType(req);\n\n // const userType = props?.actionUserType as UserType\n\n // if (!userType) throwError(\"Invalid user type in request for access control middleware\");\n\n // const policy = getAccessPolicy(userType) as AccessPolicyWithExtra<ExtraScopes>;\n // return checkAccess(userType, policy, scope, module, action);\n // };\n\n // --- Middleware version (Express compatible) ---\n // const validateAccessControlMiddleware = <\n // S extends AccessControlScopeOrExtra<ExtraScopes>,\n // M extends S extends AccessControlScope ? AccessControlModuleOf<S> : string,\n // A extends S extends AccessControlScope ? AccessControlAction : string\n // >(\n // scope: S,\n // module: M,\n // action: A\n // ) => {\n // return (req: AuthRequest, res: any, next: Function) => {\n // const userType = getUserType(req);\n // const policy = getAccessPolicy(userType) as AccessPolicyWithExtra<ExtraScopes>;\n // checkAccess(userType, policy, scope, module, action);\n // next();\n // };\n // };\n\n return {\n getAccessPolicy,\n // getUserType,\n checkAccess,\n validateAccessControl,\n listAccessControlPolicyOptions,\n // validateAccessControlMiddleware\n };\n};"]}
|
|
1
|
+
{"version":3,"file":"AccessControlService.js","sourceRoot":"","sources":["../../../src/services/access_control/AccessControlService.ts"],"names":[],"mappings":";;;AAEA,yCAA4C;AAE5C,qDAW0B;AAI1B,mCAAqC;AAiB9B,MAAM,oBAAoB,GAAG,CAIlC,KAAgC,EAAE,EAAE;IAElC,IAAI,UAAU,GAAG,KAAK,CAAC;IAEvB,yDAAyD;IACzD,IAAI,mBAAgF,CAAC;IACrF,IAAI,cAA+C,CAAC;IAEpD,MAAM,eAAe,GAAG,CAAC,QAAkB,EAAE,EAAE;QAC3C,kCAAkC;QAClC,IAAI,CAAC,UAAU,EAAE,CAAC;YACd,MAAM,UAAU,GAAG,yBAAc,CAAC,OAAO,EAAE,CAAC;YAE5C,qDAAqD;YACrD,IAAI,IAAI,GAGJ,EAAE,CAAC;YAEP,IAAI,UAAU,EAAE,mBAAmB,EAAE,CAAC;gBAClC,IAAI,GAAG,UAAU,EAAE,mBAAmB,CAAC,iCAAuB,CAAC,CAAC,CAAC,4BAA4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Q,EAAiC,EAAE,EAAE;QAEnF,qBAAqB;QACrB,MAAM,KAAK,GAAG,QAAQ,IAAK,KAAK,CAAC,cAA2B,CAAC;QAE7D,IAAI,CAAC,KAAK;YAAE,IAAA,kBAAU,EAAC,mBAAmB,CAAC,CAAC;QAE5C,oDAAoD;QACpD,MAAM,EAAE,MAAM,EAAE,mBAAmB,EAAE,cAAc,EAAE,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QAE/E,MAAM,UAAU,GAAG,cAAc,CAAC,MAAM,EAAE,mBAAmB,EAAE,cAAc,CAAC,CAAC;QAE/E,OAAO;YACH,OAAO,EAAE,UAAU;SACtB,CAAC;IACN,CAAC,CAAC;IAIF,kCAAkC;IAClC,wDAAwD;IACxD,kFAAkF;IAClF,4EAA4E;IAC5E,KAAK;IACL,gBAAgB;IAChB,iBAAiB;IACjB,gBAAgB;IAChB,kBAAkB;IAClB,4CAA4C;IAE5C,yDAAyD;IAEzD,+FAA+F;IAE/F,sFAAsF;IACtF,mEAAmE;IACnE,KAAK;IAEL,kDAAkD;IAClD,4CAA4C;IAC5C,wDAAwD;IACxD,kFAAkF;IAClF,4EAA4E;IAC5E,KAAK;IACL,gBAAgB;IAChB,iBAAiB;IACjB,gBAAgB;IAChB,SAAS;IACT,+DAA+D;IAC/D,6CAA6C;IAC7C,0FAA0F;IAC1F,gEAAgE;IAChE,kBAAkB;IAClB,SAAS;IACT,KAAK;IAEL,OAAO;QACH,eAAe;QACf,eAAe;QACf,WAAW;QACX,qBAAqB;QACrB,8BAA8B;QAC9B,kCAAkC;KACrC,CAAC;AACN,CAAC,CAAC;AA5PW,QAAA,oBAAoB,wBA4P/B","sourcesContent":["import { NextFunction, Request } from \"express\";\nimport { UserType } from \"@/services\";\nimport { CoreConfigHook } from \"@/features\";\n\nimport {\n AccessPolicyWithExtra,\n AccessControlScope,\n AccessControlModuleOf,\n AccessControlAction,\n\n accessControlScopesMap,\n accessControlModulesMap,\n accessControlActionsMap,\n\n userTypePolicies\n} from \"@/access_control\";\n\nimport { DefaultServiceProps, getDefaultServiceProps } from \"@/utils\";\n\nimport { throwError } from \"@/utils\";\n\n// Intersection type for requests\ntype AuthRequest = Request & { actionUserType?: UserType };\n\n// Helper type: core scopes + extra scopes if provided\nexport type AccessControlScopeOrExtra<ExtraScopes extends string> =\n [ExtraScopes] extends [never] ? AccessControlScope : AccessControlScope | ExtraScopes;\n\nexport type AccessControlServiceProps = DefaultServiceProps & {\n // userType: UserType\n};\n\nexport type AccessControlListOptionsProps = {\n userType?: UserType\n};\n\nexport const AccessControlService = <\n ExtraScopes extends string = never,\n ExtraModules extends Record<ExtraScopes, string> = Record<ExtraScopes, string>,\n ExtraActions extends Record<ExtraScopes, Record<string, string>> = Record<ExtraScopes, Record<string, string>>\n>(props: AccessControlServiceProps) => {\n\n let isExtended = false;\n\n // 🟢 Service-level variables to store maps from consumer\n let extraScopeModuleMap: Map<string, { value: string; label: string }[]> | undefined;\n let extraActionMap: Map<string, string> | undefined;\n\n const getAccessPolicy = (userType: UserType) => {\n // Apply consumer extras only once\n if (!isExtended) {\n const coreConfig = CoreConfigHook.onSetup();\n\n // If extendAccessControl exists and now returns maps\n let maps: {\n extraScopeModuleMap?: Map<string, { value: string; label: string }[]>;\n extraActionMap?: Map<string, string>;\n } = {};\n\n if (coreConfig?.extendAccessControl) {\n maps = coreConfig?.extendAccessControl(userTypePolicies as any); // merge policies + get maps\n }\n\n // coreConfig.extendAccessControl?.(userTypePolicies);\n\n isExtended = true;\n\n // Store maps in service-level variables so we can reuse\n extraScopeModuleMap = maps.extraScopeModuleMap;\n extraActionMap = maps.extraActionMap;\n }\n\n // console.log('userTypePolicies', userTypePolicies)\n\n const policy = userTypePolicies[userType] as AccessPolicyWithExtra<ExtraScopes>;\n if (!policy || Object.keys(policy).length <= 0) throwError(`Empty access control policy for user type: ${userType}`);\n\n // Return policy + maps\n return {\n policy,\n extraScopeModuleMap,\n extraActionMap,\n };\n\n };\n\n const getUserType = (req: AuthRequest) => {\n const userType = req?.actionUserType ?? \"\";\n if (!userType) throwError(\"Invalid user type in request for access control\");\n return userType;\n };\n\n const isActionAllowed = <\n S extends AccessControlScope | ExtraScopes\n >(\n policy: AccessPolicyWithExtra<ExtraScopes>,\n scope: S,\n module: S extends AccessControlScope ? AccessControlModuleOf<S> : string,\n action: S extends AccessControlScope ? AccessControlAction : string\n ): boolean => {\n const scopePolicy = policy[scope as keyof typeof policy] as\n | Record<string, Record<string, boolean>>\n | undefined;\n if (!scopePolicy) return false;\n\n const modulePolicy = scopePolicy[module];\n if (!modulePolicy) return false;\n\n return modulePolicy[action as string] ?? false;\n };\n\n const checkAccess = <\n S extends AccessControlScope | ExtraScopes,\n M extends S extends AccessControlScope ? AccessControlModuleOf<S> : string,\n A extends S extends AccessControlScope ? AccessControlAction : string\n >(\n userType: UserType,\n policy: AccessPolicyWithExtra<ExtraScopes>,\n scope: S,\n module: M,\n action: A\n ): boolean => {\n // TS infers ExtraScopes, S, M, A automatically\n const allowed = isActionAllowed(policy, scope, module, action);\n\n if (!allowed) throwError(`Access denied: ${scope}.${module}.${action} (${userType})`);\n return allowed;\n };\n\n // ------------------\n // Programmatic validator\n // ------------------\n const validateAccessControl = <\n S extends AccessControlScopeOrExtra<ExtraScopes>,\n M extends S extends AccessControlScope\n ? AccessControlModuleOf<S>\n : ExtraModules[S & keyof ExtraModules],\n A extends S extends AccessControlScope\n ? AccessControlAction\n : ExtraActions[S & keyof ExtraActions][M & keyof ExtraActions[S & keyof ExtraActions]]\n >(\n req: Request,\n scope: S,\n module: M,\n action: A\n ): boolean => {\n\n const userType = getUserType(req);\n\n if (!userType) throwError(\"Invalid user type\");\n\n const { policy } = getAccessPolicy(userType)\n\n return checkAccess(userType, policy, scope, module, action);\n };\n\n /** for listAccessControlPolicyOptions */\n const buildScopeTree = <\n T extends AccessPolicyWithExtra<any, any, any>\n >(\n policy: T,\n extraScopeModuleMap?: Map<string, { value: string; label: string }[]>,\n extraActionMap?: Map<string, string>\n ) => {\n const scopes: {\n key: string;\n label: string;\n modules: {\n key: string;\n label: string;\n actions: { key: string; label: string }[];\n }[];\n }[] = [];\n\n // Loop through each scope in the policy\n Object.entries(policy).forEach(([scopeKey, modules]) => {\n // Build modules array for this scope\n const modulesArr: {\n key: string;\n label: string;\n actions: { key: string; label: string }[];\n }[] = [];\n\n Object.entries(modules as Record<string, Record<string, boolean>>).forEach(\n ([moduleKey, actions]) => {\n const actionArr = Object.entries(actions)\n .filter(([_, allowed]) => allowed) // Only include true actions\n .map(([actionKey]) => ({\n key: actionKey,\n permission_key: `${scopeKey}.${moduleKey}.${actionKey}`,\n label:\n accessControlActionsMap.get(actionKey as AccessControlAction) ||\n extraActionMap?.get(actionKey) ||\n actionKey,\n }));\n\n if (actionArr.length > 0) {\n modulesArr.push({\n key: moduleKey,\n label:\n accessControlModulesMap.get(scopeKey as AccessControlScope)?.find(\n (m) => m.value === moduleKey\n )?.label || extraScopeModuleMap?.get(scopeKey)?.find((m) => m.value === moduleKey)?.label || moduleKey,\n actions: actionArr,\n });\n }\n }\n );\n\n if (modulesArr.length > 0) {\n scopes.push({\n key: scopeKey,\n label:\n accessControlScopesMap.get(scopeKey as AccessControlScope) ||\n extraScopeModuleMap?.get(scopeKey)?.[0]?.label ||\n scopeKey,\n modules: modulesArr,\n });\n }\n });\n\n return { scopes };\n };\n\n const listAccessControlPolicyOptions = ({ userType }: AccessControlListOptionsProps) => {\n\n // Determine userType\n const uType = userType || (props.actionUserType as UserType);\n\n if (!uType) throwError(\"Invalid user type\");\n\n // Get full policy (core + extra) for this user type\n const { policy, extraScopeModuleMap, extraActionMap } = getAccessPolicy(uType);\n\n const policyTree = buildScopeTree(policy, extraScopeModuleMap, extraActionMap);\n\n return {\n options: policyTree\n };\n };\n\n\n\n // const validateAccessControl = <\n // S extends AccessControlScopeOrExtra<ExtraScopes>,\n // M extends S extends AccessControlScope ? AccessControlModuleOf<S> : string,\n // A extends S extends AccessControlScope ? AccessControlAction : string\n // >(\n // scope: S,\n // module: M,\n // action: A\n // ): boolean => {\n // // const userType = getUserType(req);\n\n // const userType = props?.actionUserType as UserType\n\n // if (!userType) throwError(\"Invalid user type in request for access control middleware\");\n\n // const policy = getAccessPolicy(userType) as AccessPolicyWithExtra<ExtraScopes>;\n // return checkAccess(userType, policy, scope, module, action);\n // };\n\n // --- Middleware version (Express compatible) ---\n // const validateAccessControlMiddleware = <\n // S extends AccessControlScopeOrExtra<ExtraScopes>,\n // M extends S extends AccessControlScope ? AccessControlModuleOf<S> : string,\n // A extends S extends AccessControlScope ? AccessControlAction : string\n // >(\n // scope: S,\n // module: M,\n // action: A\n // ) => {\n // return (req: AuthRequest, res: any, next: Function) => {\n // const userType = getUserType(req);\n // const policy = getAccessPolicy(userType) as AccessPolicyWithExtra<ExtraScopes>;\n // checkAccess(userType, policy, scope, module, action);\n // next();\n // };\n // };\n\n return {\n getAccessPolicy,\n // getUserType,\n checkAccess,\n validateAccessControl,\n listAccessControlPolicyOptions,\n // validateAccessControlMiddleware\n };\n};"]}
|
|
@@ -16,7 +16,7 @@ exports.authTypes = {
|
|
|
16
16
|
};
|
|
17
17
|
const AuthService = (props) => {
|
|
18
18
|
const { secretKey, authType = "administrator", ...rest } = props;
|
|
19
|
-
let hookSetup = null
|
|
19
|
+
// let hookSetup: FeatureAuthTokenSuccessAuthenticateProps | null = null
|
|
20
20
|
const getUserInjectionFieldName = (authType) => {
|
|
21
21
|
if (authType === "administrator")
|
|
22
22
|
return ["administrator_injection_fields"];
|
|
@@ -194,8 +194,23 @@ const AuthService = (props) => {
|
|
|
194
194
|
is_owner: Boolean(user?.is_owner),
|
|
195
195
|
// owner_id: 0
|
|
196
196
|
};
|
|
197
|
+
let newResult;
|
|
197
198
|
// Call the consumer hook, if registered
|
|
198
|
-
|
|
199
|
+
if (features_1.AuthTokenHook?.onSuccessAuthenticate) {
|
|
200
|
+
const userType = user?.user_type ?? "administrator";
|
|
201
|
+
newResult = await features_1.AuthTokenHook.onSuccessAuthenticate({
|
|
202
|
+
defaultServiceProps: {
|
|
203
|
+
accountId: Number(account?.account_id),
|
|
204
|
+
actionUserId: Number(user?.user_id),
|
|
205
|
+
actionUserType: user?.user_type ?? "",
|
|
206
|
+
authToken: authToken,
|
|
207
|
+
isOperator: Boolean(userType === "operator"),
|
|
208
|
+
accessKey: "",
|
|
209
|
+
accessKeyId: ""
|
|
210
|
+
},
|
|
211
|
+
callbackParams: result
|
|
212
|
+
});
|
|
213
|
+
}
|
|
199
214
|
return newResult ? newResult : result;
|
|
200
215
|
};
|
|
201
216
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthService.js","sourceRoot":"","sources":["../../../src/services/auth/AuthService.ts"],"names":[],"mappings":";;;AAAA,yDAAyD;AACzD,mCAA0D;AAC1D,yCASoB;AAIpB,mCAA0F;AAC1F,qCAA0E;AAE1E,yCAAoF;AAEvE,QAAA,SAAS,GAAG;IACrB,QAAQ,EAAE,UAAU;IACpB,aAAa,EAAE,eAAe;IAC9B,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;CACV,CAAA;AAkCH,MAAM,WAAW,GAAG,CAAC,KAAuB,EAAE,EAAE;IAEnD,MAAM,EACF,SAAS,EACT,QAAQ,GAAG,eAAe,EAC1B,GAAG,IAAI,EACV,GAAG,KAAK,CAAA;IAET,IAAI,SAAS,GAAoD,IAAI,CAAA;IAErE,MAAM,yBAAyB,GAAG,CAAC,QAAkB,EAAE,EAAE;QAErD,IAAI,QAAQ,KAAK,eAAe;YAAE,OAAO,CAAC,gCAAgC,CAAC,CAAA;QAC3E,IAAI,QAAQ,KAAK,UAAU;YAAE,OAAO,CAAC,2BAA2B,CAAC,CAAA;QACjE,IAAI,QAAQ,KAAK,QAAQ;YAAE,OAAO,CAAC,yBAAyB,CAAC,CAAA;QAE7D,OAAO,EAAE,CAAA;IACb,CAAC,CAAA;IAED,MAAM,mBAAmB,GAAG,KAAK,EAAE,WAAmB,EAAE,EA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E,aAAa;gBACxB,SAAS,EAAE,KAAK;gBAChB,OAAO,EAAE,CAAC;wBACN,KAAK,EAAE,aAAa;wBACpB,QAAQ,EAAE,UAAU;wBACpB,KAAK,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;qBAChD,CAAC;gBACF,SAAS,EAAE,EAAE;aAChB,CAAA;YAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,eAAe,CAAC,aAAa,CAAC,WAAW,CAAC,CAAA;YACjE,SAAS,GAAG,IAAI,CAAA;QACpB,CAAC;QAED,MAAM,MAAM,GAAoB;YAC5B,KAAK,EAAE,SAAS;YAChB,OAAO;YACP,IAAI;YACJ,cAAc,EAAE,SAAS;YACzB,qBAAqB;YACrB,WAAW;YACX,IAAI;YACJ,cAAc;YACd,uBAAuB;YACvB,IAAI;YACJ,KAAK;YACL,mBAAmB;YACnB,QAAQ,EAAE,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;YACjC,cAAc;SACjB,CAAA;QAED,wCAAwC;QACxC,MAAM,SAAS,GAAG,MAAM,wBAAa,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAA;QAEnE,OAAO,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAA;IACzC,CAAC,CAAC;IAEF,OAAO;QACH,YAAY;QACZ,eAAe,EAAf,uBAAe;KAClB,CAAA;AAEL,CAAC,CAAA;AA9PY,QAAA,WAAW,eA8PvB","sourcesContent":["// import { QueryList, QueryGet } from \"@/schema/common\";\nimport { DefaultServiceProps, throwError } from \"@/utils\";\nimport {\n UserService,\n // UserGetProps,\n UserType,\n UserListProps,\n // userTypes,\n AccountService,\n LocationService,\n LocationListProps\n} from \"@/services\";\n\nimport jwt, { JwtPayload } from \"jsonwebtoken\";\n\nimport { generateAuthToken, verifyPassword, verifyAuthToken, hashPassword } from \"@/utils\"\nimport { ModelAccountFields, ModelUserFields, UserModel } from \"@/models\";\n\nimport { AuthTokenHook, FeatureAuthTokenSuccessAuthenticateProps } from \"@/features\"\n\nexport const authTypes = {\n operator: \"operator\",\n administrator: \"administrator\",\n worker: \"worker\",\n customer: \"customer\",\n member: \"member\",\n} as const\n\nexport type AuthType = typeof authTypes[keyof typeof authTypes]\n\nexport type AuthTokenResult = {\n token: string\n account: any\n user: any\n user_locations: any[]\n is_owner: boolean\n}\n\nexport type AuthJwtToken = JwtPayload & {\n user?: { id: number, user_id: number, user_type: AuthType };\n account?: { id: number, account_id: number };\n};\n\nexport type AuthServiceProps = DefaultServiceProps & {\n secretKey: string,\n authType: AuthType\n};\n\nexport type AuthGetTokenProps = {\n authType: AuthType,\n // accountId?: number,\n accountCode?: string,\n data:\n // get token\n {\n username: string,\n password: string\n }\n};\n\nexport const AuthService = (props: AuthServiceProps) => {\n\n const {\n secretKey,\n authType = \"administrator\",\n ...rest\n } = props\n\n let hookSetup: FeatureAuthTokenSuccessAuthenticateProps | null = null\n\n const getUserInjectionFieldName = (authType: AuthType) => {\n\n if (authType === \"administrator\") return [\"administrator_injection_fields\"]\n if (authType === \"customer\") return [\"customer_injection_fields\"]\n if (authType === \"worker\") return [\"worker_injection_fields\"]\n\n return []\n }\n\n const validateAuthAccount = async (accountCode: string) => {\n\n if (accountCode === \"\") {\n return 0\n }\n\n // check if the accountId & accountCode is not empty\n // if (!accountId && !accountCode) throwError(`accountId or accountCode is required`)\n\n let selectAccountId = 0\n\n // check account id is choose \n // if (selectAccountId === 0) {\n\n const globalAccountService = AccountService({ ...rest, isOperator: true })\n\n // use account code to find the account id\n if (accountCode) {\n\n let { data: responseAcc } = await globalAccountService.listAccounts({\n limit: 1,\n offset: 0,\n sortfield: `${ModelAccountFields.account_id}`,\n sortorder: `ASC`,\n filters: [{\n field: `${ModelAccountFields.account_code}`,\n operator: `=`,\n value: `${accountCode}`,\n }],\n datatypes: []\n })\n\n selectAccountId = responseAcc.length > 0 ? responseAcc[0].account_id : \"\"\n let selectAccountStatus = responseAcc.length > 0 ? responseAcc[0].account_status : \"\"\n\n if (selectAccountStatus !== true) throwError(`Inactive account: ${accountCode}`)\n\n }\n\n if (!selectAccountId) {\n throwError(`Invalid account code: ${accountCode}`)\n }\n\n // }\n\n return Number(selectAccountId ?? 0)\n\n }\n\n const getAuthToken = async ({ authType, data, accountCode = \"\" }: AuthGetTokenProps) => {\n\n let _rest = rest\n let _accountId = 0\n\n if (authType !== \"operator\") {\n _accountId = await validateAuthAccount(accountCode)\n }\n\n // _rest.accountId = accountId\n _rest.accountId = _accountId\n\n // check the option pass in using account id or account code\n // if (authType !== \"operator\") {\n // _rest.accountId = accountId\n\n // // check if the accountId & accountCode is not empty\n // if (!accountId && !accountCode) throwError(`accountId or accountCode is required`)\n\n // let selectAccountId = `${accountId}`\n\n // // check account id is choose \n // if (selectAccountId === \"0\") {\n\n // const globalAccountService = AccountService({ ...rest, isOperator: true })\n\n // // use account code to find the account id\n // if (accountCode) {\n\n // let { data: responseAcc } = await globalAccountService.listAccounts({\n // limit: 1,\n // offset: 0,\n // sortfield: `${ModelAccountFields.account_id}`,\n // sortorder: `ASC`,\n // filters: [{\n // field: `${ModelAccountFields.account_code}`,\n // operator: `=`,\n // value: `${accountCode}`,\n // }],\n // datatypes: []\n // })\n\n // selectAccountId = responseAcc.length > 0 ? responseAcc[0].account_id : \"\"\n // let selectAccountStatus = responseAcc.length > 0 ? responseAcc[0].account_status : \"\"\n\n // if (selectAccountStatus !== true) throwError(`Inactive account: ${accountCode}`)\n\n // }\n\n // if (!selectAccountId) {\n // throwError(`Invalid account code: ${accountCode}`)\n // }\n\n // }\n\n // _rest.accountId = Number(selectAccountId)\n\n // } else {\n // _rest.accountId = accountId\n // }\n\n const userService = UserService({ userType: authType as UserType, ...rest })\n const accountService = AccountService({ ...rest, isOperator: true })\n const locationService = LocationService({ ...rest, locationType: \"location\" })\n\n let foundUser: any = {}\n\n // only for operator & administrator\n if (authType === \"operator\" || authType === \"administrator\") {\n\n // const operatorService = UserService({ ...rest })\n\n const _user = await userService.getUserByUsername({\n username: `${data[\"username\"]}`,\n includePassword: true,\n datatypes: getUserInjectionFieldName(authType) as any\n })\n\n foundUser = _user\n\n } else { // other user type\n\n let payload: UserListProps = {\n includePassword: true,\n limit: 1,\n offset: 0,\n sortfield: \"user_id\",\n sortorder: \"DESC\",\n filters: [\n { field: \"username\", operator: \"=\", value: `${data[\"username\"]}` },\n { field: \"user_type\", operator: \"=\", value: `${authType}` }\n ],\n datatypes: getUserInjectionFieldName(authType)\n }\n\n const { data: foundOtherUser } = await userService.listUsers(payload)\n\n foundUser = foundOtherUser.length > 0 ? foundOtherUser[0] : {}\n\n }\n\n if (!foundUser?.user_id) {\n throw Error(`Invalid username: ${data.username}`)\n }\n\n if (foundUser?.status !== true) {\n throw new Error(`User is inactive: ${data.username}`);\n }\n\n let user = foundUser\n // foundUser.length > 0 ? foundUser[0] : {}\n\n let decryptedPass: boolean\n\n try {\n decryptedPass = await verifyPassword(data.password, user.password)\n } catch (error) {\n throw error\n }\n\n if (decryptedPass === false) {\n throw Error(`Invalid credential: ${data[\"username\"]}`)\n }\n\n // dont show out to result\n delete user.password\n\n let account: any = {}\n\n // if (_rest.accountId && authType !== \"operator\") {\n account = await accountService.getAccount({ id: Number(_rest.accountId), datatypes: [] })\n // }\n\n const authToken = generateAuthToken(user, account, secretKey)\n\n // get the locations for user\n const locationIds = user?.location_id ? user.location_id.split(\", \") : []\n\n let locations: any[] = []\n\n if (locationIds.length > 0) {\n const listPayload: LocationListProps = {\n limit: 100,\n offset: 0,\n sortfield: \"location_id\",\n sortorder: \"ASC\",\n filters: [{\n field: \"location_id\",\n operator: \"where_in\",\n value: locationIds.map((i: any) => Number(i))\n }],\n datatypes: []\n }\n\n const { data } = await locationService.listLocations(listPayload)\n locations = data\n }\n\n const result: AuthTokenResult = {\n token: authToken,\n account,\n user,\n user_locations: locations,\n // parent_user_id: 0,\n // roles: [\n // {\n // id: 23,\n // role_name: \"123\"\n // }\n // ],\n // permissions: [],\n is_owner: Boolean(user?.is_owner),\n // owner_id: 0\n }\n\n // Call the consumer hook, if registered\n const newResult = await AuthTokenHook.onSuccessAuthenticate(result)\n\n return newResult ? newResult : result\n };\n\n return {\n getAuthToken,\n verifyAuthToken,\n }\n\n}\n\n"]}
|
|
1
|
+
{"version":3,"file":"AuthService.js","sourceRoot":"","sources":["../../../src/services/auth/AuthService.ts"],"names":[],"mappings":";;;AAAA,yDAAyD;AACzD,mCAA0D;AAC1D,yCASoB;AAIpB,mCAA0F;AAC1F,qCAA0E;AAE1E,yCAAoF;AAEvE,QAAA,SAAS,GAAG;IACrB,QAAQ,EAAE,UAAU;IACpB,aAAa,EAAE,eAAe;IAC9B,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;CACV,CAAA;AAkCH,MAAM,WAAW,GAAG,CAAC,KAAuB,EAAE,EAAE;IAEnD,MAAM,EACF,SAAS,EACT,QAAQ,GAAG,eAAe,EAC1B,GAAG,IAAI,EACV,GAAG,KAAK,CAAA;IAET,wEAAwE;IAExE,MAAM,yBAAyB,GAAG,CAAC,QAAkB,EAAE,EAAE;QAErD,IAAI,QAAQ,KAAK,eAAe;YAAE,OAAO,CAAC,gCAAgC,CAAC,CAAA;QAC3E,IAAI,QAAQ,KAAK,UAAU;YAAE,OAAO,CAAC,2BAA2B,CAAC,CAAA;QACjE,IAAI,QAAQ,KAAK,QAAQ;YAAE,OAAO,CAAC,yBAAyB,CAAC,CAAA;QAE7D,OAAO,EAAE,CAAA;IACb,CAAC,CAAA;IAED,MAAM,mBAAmB,GAAG,KAAK,EAAE,WAAmB,EAAE,EAAE;QAEtD,IAAI,WAAW,KAAK,EAAE,EAAE,CAAC;YACrB,OAAO,CAAC,CAAA;QACZ,CAAC;QAED,oDAAoD;QACpD,qFAAqF;QAErF,IAAI,eAAe,GAAG,CAAC,CAAA;QAEvB,8BAA8B;QAC9B,+BAA+B;QAE/B,MAAM,oBAAo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B","sourcesContent":["// import { QueryList, QueryGet } from \"@/schema/common\";\nimport { DefaultServiceProps, throwError } from \"@/utils\";\nimport {\n UserService,\n // UserGetProps,\n UserType,\n UserListProps,\n // userTypes,\n AccountService,\n LocationService,\n LocationListProps\n} from \"@/services\";\n\nimport jwt, { JwtPayload } from \"jsonwebtoken\";\n\nimport { generateAuthToken, verifyPassword, verifyAuthToken, hashPassword } from \"@/utils\"\nimport { ModelAccountFields, ModelUserFields, UserModel } from \"@/models\";\n\nimport { AuthTokenHook, FeatureAuthTokenSuccessAuthenticateProps } from \"@/features\"\n\nexport const authTypes = {\n operator: \"operator\",\n administrator: \"administrator\",\n worker: \"worker\",\n customer: \"customer\",\n member: \"member\",\n} as const\n\nexport type AuthType = typeof authTypes[keyof typeof authTypes]\n\nexport type AuthTokenResult = {\n token: string\n account: any\n user: any\n user_locations: any[]\n is_owner: boolean\n}\n\nexport type AuthJwtToken = JwtPayload & {\n user?: { id: number, user_id: number, user_type: AuthType };\n account?: { id: number, account_id: number };\n};\n\nexport type AuthServiceProps = DefaultServiceProps & {\n secretKey: string,\n authType: AuthType\n};\n\nexport type AuthGetTokenProps = {\n authType: AuthType,\n // accountId?: number,\n accountCode?: string,\n data:\n // get token\n {\n username: string,\n password: string\n }\n};\n\nexport const AuthService = (props: AuthServiceProps) => {\n\n const {\n secretKey,\n authType = \"administrator\",\n ...rest\n } = props\n\n // let hookSetup: FeatureAuthTokenSuccessAuthenticateProps | null = null\n\n const getUserInjectionFieldName = (authType: AuthType) => {\n\n if (authType === \"administrator\") return [\"administrator_injection_fields\"]\n if (authType === \"customer\") return [\"customer_injection_fields\"]\n if (authType === \"worker\") return [\"worker_injection_fields\"]\n\n return []\n }\n\n const validateAuthAccount = async (accountCode: string) => {\n\n if (accountCode === \"\") {\n return 0\n }\n\n // check if the accountId & accountCode is not empty\n // if (!accountId && !accountCode) throwError(`accountId or accountCode is required`)\n\n let selectAccountId = 0\n\n // check account id is choose \n // if (selectAccountId === 0) {\n\n const globalAccountService = AccountService({ ...rest, isOperator: true })\n\n // use account code to find the account id\n if (accountCode) {\n\n let { data: responseAcc } = await globalAccountService.listAccounts({\n limit: 1,\n offset: 0,\n sortfield: `${ModelAccountFields.account_id}`,\n sortorder: `ASC`,\n filters: [{\n field: `${ModelAccountFields.account_code}`,\n operator: `=`,\n value: `${accountCode}`,\n }],\n datatypes: []\n })\n\n selectAccountId = responseAcc.length > 0 ? responseAcc[0].account_id : \"\"\n let selectAccountStatus = responseAcc.length > 0 ? responseAcc[0].account_status : \"\"\n\n if (selectAccountStatus !== true) throwError(`Inactive account: ${accountCode}`)\n\n }\n\n if (!selectAccountId) {\n throwError(`Invalid account code: ${accountCode}`)\n }\n\n // }\n\n return Number(selectAccountId ?? 0)\n\n }\n\n const getAuthToken = async ({ authType, data, accountCode = \"\" }: AuthGetTokenProps) => {\n\n let _rest = rest\n let _accountId = 0\n\n if (authType !== \"operator\") {\n _accountId = await validateAuthAccount(accountCode)\n }\n\n // _rest.accountId = accountId\n _rest.accountId = _accountId\n\n // check the option pass in using account id or account code\n // if (authType !== \"operator\") {\n // _rest.accountId = accountId\n\n // // check if the accountId & accountCode is not empty\n // if (!accountId && !accountCode) throwError(`accountId or accountCode is required`)\n\n // let selectAccountId = `${accountId}`\n\n // // check account id is choose \n // if (selectAccountId === \"0\") {\n\n // const globalAccountService = AccountService({ ...rest, isOperator: true })\n\n // // use account code to find the account id\n // if (accountCode) {\n\n // let { data: responseAcc } = await globalAccountService.listAccounts({\n // limit: 1,\n // offset: 0,\n // sortfield: `${ModelAccountFields.account_id}`,\n // sortorder: `ASC`,\n // filters: [{\n // field: `${ModelAccountFields.account_code}`,\n // operator: `=`,\n // value: `${accountCode}`,\n // }],\n // datatypes: []\n // })\n\n // selectAccountId = responseAcc.length > 0 ? responseAcc[0].account_id : \"\"\n // let selectAccountStatus = responseAcc.length > 0 ? responseAcc[0].account_status : \"\"\n\n // if (selectAccountStatus !== true) throwError(`Inactive account: ${accountCode}`)\n\n // }\n\n // if (!selectAccountId) {\n // throwError(`Invalid account code: ${accountCode}`)\n // }\n\n // }\n\n // _rest.accountId = Number(selectAccountId)\n\n // } else {\n // _rest.accountId = accountId\n // }\n\n const userService = UserService({ userType: authType as UserType, ...rest })\n const accountService = AccountService({ ...rest, isOperator: true })\n const locationService = LocationService({ ...rest, locationType: \"location\" })\n\n let foundUser: any = {}\n\n // only for operator & administrator\n if (authType === \"operator\" || authType === \"administrator\") {\n\n // const operatorService = UserService({ ...rest })\n\n const _user = await userService.getUserByUsername({\n username: `${data[\"username\"]}`,\n includePassword: true,\n datatypes: getUserInjectionFieldName(authType) as any\n })\n\n foundUser = _user\n\n } else { // other user type\n\n let payload: UserListProps = {\n includePassword: true,\n limit: 1,\n offset: 0,\n sortfield: \"user_id\",\n sortorder: \"DESC\",\n filters: [\n { field: \"username\", operator: \"=\", value: `${data[\"username\"]}` },\n { field: \"user_type\", operator: \"=\", value: `${authType}` }\n ],\n datatypes: getUserInjectionFieldName(authType)\n }\n\n const { data: foundOtherUser } = await userService.listUsers(payload)\n\n foundUser = foundOtherUser.length > 0 ? foundOtherUser[0] : {}\n\n }\n\n if (!foundUser?.user_id) {\n throw Error(`Invalid username: ${data.username}`)\n }\n\n if (foundUser?.status !== true) {\n throw new Error(`User is inactive: ${data.username}`);\n }\n\n let user = foundUser\n // foundUser.length > 0 ? foundUser[0] : {}\n\n let decryptedPass: boolean\n\n try {\n decryptedPass = await verifyPassword(data.password, user.password)\n } catch (error) {\n throw error\n }\n\n if (decryptedPass === false) {\n throw Error(`Invalid credential: ${data[\"username\"]}`)\n }\n\n // dont show out to result\n delete user.password\n\n let account: any = {}\n\n // if (_rest.accountId && authType !== \"operator\") {\n account = await accountService.getAccount({ id: Number(_rest.accountId), datatypes: [] })\n // }\n\n const authToken = generateAuthToken(user, account, secretKey)\n\n // get the locations for user\n const locationIds = user?.location_id ? user.location_id.split(\", \") : []\n\n let locations: any[] = []\n\n if (locationIds.length > 0) {\n const listPayload: LocationListProps = {\n limit: 100,\n offset: 0,\n sortfield: \"location_id\",\n sortorder: \"ASC\",\n filters: [{\n field: \"location_id\",\n operator: \"where_in\",\n value: locationIds.map((i: any) => Number(i))\n }],\n datatypes: []\n }\n\n const { data } = await locationService.listLocations(listPayload)\n locations = data\n }\n\n const result: AuthTokenResult = {\n token: authToken,\n account,\n user,\n user_locations: locations,\n // parent_user_id: 0,\n // roles: [\n // {\n // id: 23,\n // role_name: \"123\"\n // }\n // ],\n // permissions: [],\n is_owner: Boolean(user?.is_owner),\n // owner_id: 0\n }\n\n let newResult: any\n\n // Call the consumer hook, if registered\n if (AuthTokenHook?.onSuccessAuthenticate) {\n\n const userType: UserType = user?.user_type ?? \"administrator\"\n\n newResult = await AuthTokenHook.onSuccessAuthenticate({\n defaultServiceProps: {\n accountId: Number(account?.account_id),\n actionUserId: Number(user?.user_id),\n actionUserType: user?.user_type ?? \"\",\n authToken: authToken,\n isOperator: Boolean(userType === \"operator\"),\n accessKey: \"\",\n accessKeyId: \"\"\n },\n callbackParams: result\n })\n }\n\n return newResult ? newResult : result\n };\n\n return {\n getAuthToken,\n verifyAuthToken,\n }\n\n}\n\n"]}
|