storemw-core-api 1.0.145 → 1.0.146
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/authTokenType.d.ts +1 -1
- package/dist/features/auth_token/authTokenType.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/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 +32 -0
- package/dist/features/user_me/userMeRegistry.js.map +1 -0
- package/dist/features/user_me/userMeType.d.ts +8 -0
- package/dist/features/user_me/userMeType.js +3 -0
- package/dist/features/user_me/userMeType.js.map +1 -0
- package/dist/services/auth/AuthService.js +4 -1
- package/dist/services/auth/AuthService.js.map +1 -1
- package/dist/services/user/UserMeService.js +24 -211
- package/dist/services/user/UserMeService.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AuthTokenResult } from "../../services";
|
|
2
2
|
export type FeatureAuthTokenSuccessAuthenticateProps = AuthTokenResult & {};
|
|
3
3
|
export type FeatureAuthTokenProps = {
|
|
4
|
-
onSuccessAuthenticate
|
|
4
|
+
onSuccessAuthenticate?: (payload: FeatureAuthTokenSuccessAuthenticateProps) => Promise<any>;
|
|
5
5
|
};
|
|
@@ -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\"\n\nexport type FeatureAuthTokenSuccessAuthenticateProps = AuthTokenResult & {\n}\n\nexport type FeatureAuthTokenProps = {\n onSuccessAuthenticate?: (payload: FeatureAuthTokenSuccessAuthenticateProps) => 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\""]}
|
|
@@ -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,32 @@
|
|
|
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
|
+
// console.log('authTokenResult', authTokenResult)
|
|
9
|
+
// example to add custom props into return auth token result
|
|
10
|
+
// return {
|
|
11
|
+
// ...authTokenResult,
|
|
12
|
+
// workerId: 1000
|
|
13
|
+
// }
|
|
14
|
+
},
|
|
15
|
+
onSuccessChangePasswordMe: async (props) => {
|
|
16
|
+
// console.log('authTokenResult', authTokenResult)
|
|
17
|
+
// example to add custom props into return auth token result
|
|
18
|
+
// return {
|
|
19
|
+
// ...authTokenResult,
|
|
20
|
+
// workerId: 1000
|
|
21
|
+
// }
|
|
22
|
+
},
|
|
23
|
+
onSuccessRemoveMe: async (props) => {
|
|
24
|
+
// console.log('authTokenResult', authTokenResult)
|
|
25
|
+
// example to add custom props into return auth token result
|
|
26
|
+
// return {
|
|
27
|
+
// ...authTokenResult,
|
|
28
|
+
// workerId: 1000
|
|
29
|
+
// }
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
//# 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;QAEhE,kDAAkD;QAElD,4DAA4D;QAE5D,WAAW;QACX,0BAA0B;QAC1B,qBAAqB;QACrB,IAAI;IAGR,CAAC;IACD,yBAAyB,EAAE,KAAK,EAAE,KAA8C,EAAE,EAAE;QAEhF,kDAAkD;QAElD,4DAA4D;QAE5D,WAAW;QACX,0BAA0B;QAC1B,qBAAqB;QACrB,IAAI;IAGR,CAAC;IACD,iBAAiB,EAAE,KAAK,EAAE,KAAsC,EAAE,EAAE;QAEhE,kDAAkD;QAElD,4DAA4D;QAE5D,WAAW;QACX,0BAA0B;QAC1B,qBAAqB;QACrB,IAAI;IAGR,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 // 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 onSuccessChangePasswordMe: async (props: FeatureUserMeSuccessChangePasswordProps) => {\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 onSuccessRemoveMe: async (props: FeatureUserMeSuccessRemoveProps) => {\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}"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type FeatureUserMeSuccessUpdateProps = {};
|
|
2
|
+
export type FeatureUserMeSuccessChangePasswordProps = {};
|
|
3
|
+
export type FeatureUserMeSuccessRemoveProps = {};
|
|
4
|
+
export type FeatureUserMeProps = {
|
|
5
|
+
onSuccessUpdateMe?: (payload: FeatureUserMeSuccessUpdateProps) => Promise<any>;
|
|
6
|
+
onSuccessChangePasswordMe?: (payload: FeatureUserMeSuccessChangePasswordProps) => Promise<any>;
|
|
7
|
+
onSuccessRemoveMe?: (payload: FeatureUserMeSuccessRemoveProps) => Promise<any>;
|
|
8
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"userMeType.js","sourceRoot":"","sources":["../../../src/features/user_me/userMeType.ts"],"names":[],"mappings":"","sourcesContent":["export type FeatureUserMeSuccessUpdateProps = {\n}\n\nexport type FeatureUserMeSuccessChangePasswordProps = {\n}\n\nexport type FeatureUserMeSuccessRemoveProps = {\n}\n\nexport type FeatureUserMeProps = {\n onSuccessUpdateMe?: (payload: FeatureUserMeSuccessUpdateProps) => Promise<any>\n onSuccessChangePasswordMe?: (payload: FeatureUserMeSuccessChangePasswordProps) => Promise<any>\n onSuccessRemoveMe?: (payload: FeatureUserMeSuccessRemoveProps) => Promise<any>\n}"]}
|
|
@@ -194,8 +194,11 @@ 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
|
+
newResult = await features_1.AuthTokenHook.onSuccessAuthenticate(result);
|
|
201
|
+
}
|
|
199
202
|
return newResult ? newResult : result;
|
|
200
203
|
};
|
|
201
204
|
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,C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W,GAAsB;gBACnC,KAAK,EAAE,GAAG;gBACV,MAAM,EAAE,CAAC;gBACT,SAAS,EAAE,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,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,EAAE;QAEtD,IAAI,WAAW,KAAK,EAAE,EAAE,CAAC;YACrB,OAAO,CAAC,CAAA;QACZ,CAAC;QAED,oDAAoD;QACp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AE,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,IAAI,SAAc,CAAA;QAElB,wCAAwC;QACxC,IAAI,wBAAa,EAAE,qBAAqB,EAAE,CAAC;YACvC,SAAS,GAAG,MAAM,wBAAa,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAA;QACjE,CAAC;QAED,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;AAlQY,QAAA,WAAW,eAkQvB","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 newResult = await AuthTokenHook.onSuccessAuthenticate(result)\n }\n\n return newResult ? newResult : result\n };\n\n return {\n getAuthToken,\n verifyAuthToken,\n }\n\n}\n\n"]}
|
|
@@ -2,11 +2,10 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.UserMeService = exports.userTypes = void 0;
|
|
4
4
|
const models_1 = require("../../models");
|
|
5
|
-
// import { buildSqlRelation, buildSqlRawSelect, buildSqlWhere, buildSqlSelect, buildSqlLimitOffset, buildSqlOrderBy, buildInjectionFieldsSqlSelect } from "../../lib";
|
|
6
5
|
const utils_1 = require("../../utils");
|
|
7
|
-
// import { hashPassword } from "../../utils";
|
|
8
6
|
const lib_1 = require("../../lib");
|
|
9
7
|
const services_1 = require("../../services");
|
|
8
|
+
const features_1 = require("../../features");
|
|
10
9
|
exports.userTypes = {
|
|
11
10
|
operator: "operator",
|
|
12
11
|
administrator: "administrator",
|
|
@@ -49,214 +48,6 @@ const UserMeService = (props) => {
|
|
|
49
48
|
const userId = rest.actionUserId;
|
|
50
49
|
const userService = (0, services_1.UserService)({ ...rest, userType });
|
|
51
50
|
const userModel = (0, models_1.UserModel)({ ...rest });
|
|
52
|
-
// const userModel = UserModel({ ...rest })
|
|
53
|
-
// const userPropService = UserPropService({ ...rest, userPropType: "LOCATION_ID" })
|
|
54
|
-
// const customerService = CustomerService({ ...rest })
|
|
55
|
-
// const administratorService = AdministratorService({ ...rest })
|
|
56
|
-
// const operatorService = OperatorService({ ...rest })
|
|
57
|
-
// const workerService = WorkerService({ ...rest })
|
|
58
|
-
// const driverService = DriverService({ ...rest })
|
|
59
|
-
// const retailerService = RetailerService({ ...rest })
|
|
60
|
-
// const memberService = MemberService({ ...rest })
|
|
61
|
-
// const agentService = AgentService({ ...rest })
|
|
62
|
-
// const validateAuthToken = (token: string) => {
|
|
63
|
-
// // retrive core configuration
|
|
64
|
-
// const coreConfig = getCoreConfiguration()
|
|
65
|
-
// // const authSecretKey = config.AUTH_SECRET_KEY
|
|
66
|
-
// const authSecretKey = coreConfig.authSecretKey
|
|
67
|
-
// // const jwtData = jwt.verify(token, authSecretKey) as AuthJwtToken; // Verify JWT token
|
|
68
|
-
// const jwtData = verifyAuthToken(token, authSecretKey); // Verify JWT token
|
|
69
|
-
// }
|
|
70
|
-
// const validateAuthAccessKey = async (accessKey: string) => {
|
|
71
|
-
// const accessKeyUtilService = AccessKeyUtilService({
|
|
72
|
-
// accessKeyUserType: "administrator",
|
|
73
|
-
// accountId: 0,
|
|
74
|
-
// actionUserId: 0,
|
|
75
|
-
// actionUserType: "",
|
|
76
|
-
// authToken: "",
|
|
77
|
-
// isOperator: true,
|
|
78
|
-
// })
|
|
79
|
-
// const accessKeyData = await accessKeyUtilService.validateAccessKey({ data: { accessKey } });
|
|
80
|
-
// }
|
|
81
|
-
// const updateMe = async ({ id, data, userType: overrideUserType }: UserMeUpdateProps) => {
|
|
82
|
-
// const _userType = overrideUserType || userType
|
|
83
|
-
// // validate the credential contact no
|
|
84
|
-
// const userLoginUsername = data.user.loginUsername
|
|
85
|
-
// const userLoginPassword = data.user?.loginPassword ?? ""
|
|
86
|
-
// const userContactCountryCode = data.user.contact.countryCode
|
|
87
|
-
// const userContactPhoneNumber = data.user.contact.phoneNumber
|
|
88
|
-
// // validate the contact no only can be digit in text only
|
|
89
|
-
// // validate the country code in prefix
|
|
90
|
-
// // await validateUserContact(userContactCountryCode, userContactPhoneNumber)
|
|
91
|
-
// // validate login username
|
|
92
|
-
// // validateLoginUsernameFormat(userLoginUsername)
|
|
93
|
-
// // validate login password
|
|
94
|
-
// // if (userLoginPassword) {
|
|
95
|
-
// // validateLoginPasswordFormat(userLoginPassword)
|
|
96
|
-
// // }
|
|
97
|
-
// // check the username duplicated?
|
|
98
|
-
// const checkUsername = await userModel.list({
|
|
99
|
-
// limit: 1,
|
|
100
|
-
// offset: 0,
|
|
101
|
-
// orderBy: {
|
|
102
|
-
// [`${ModelUserFields.user_id}`]: "asc"
|
|
103
|
-
// },
|
|
104
|
-
// include: [],
|
|
105
|
-
// where: {
|
|
106
|
-
// [`${ModelUserFields.login_username}`]: data.user.loginUsername,
|
|
107
|
-
// [`${ModelUserFields.isdelete}`]: false,
|
|
108
|
-
// [`${ModelUserFields.istrash}`]: false,
|
|
109
|
-
// [`${ModelUserFields.accountid}`]: rest.accountId,
|
|
110
|
-
// },
|
|
111
|
-
// })
|
|
112
|
-
// // console.log('ch', checkUsername)
|
|
113
|
-
// if (checkUsername.length > 0) {
|
|
114
|
-
// if (Number(checkUsername[0]?.user_id) !== Number(id)) { // if not self user id
|
|
115
|
-
// throwError(`Duplicated username: ${data.user.loginUsername}(${checkUsername[0]?.user_type})`)
|
|
116
|
-
// }
|
|
117
|
-
// }
|
|
118
|
-
// // validation before insertion
|
|
119
|
-
// // if (_userType === "member" && "member" in data) {
|
|
120
|
-
// // }
|
|
121
|
-
// const _data = await getUpdatePayload(
|
|
122
|
-
// _userType,
|
|
123
|
-
// data,
|
|
124
|
-
// {
|
|
125
|
-
// countryCode: userContactCountryCode,
|
|
126
|
-
// phoneNumber: userContactPhoneNumber
|
|
127
|
-
// }
|
|
128
|
-
// )
|
|
129
|
-
// if (!_data) {
|
|
130
|
-
// throw new Error(`Invalid update payload: ${JSON.stringify(_data)}`);
|
|
131
|
-
// }
|
|
132
|
-
// // update user
|
|
133
|
-
// let responseUser = await userModel.update({ id, data: _data })
|
|
134
|
-
// let updateUserId = responseUser.user_id
|
|
135
|
-
// let response: any = {}
|
|
136
|
-
// if (_userType === "customer" && "customer" in data) {
|
|
137
|
-
// let dataCustomer: CustomerUpdateProps["data"] = {
|
|
138
|
-
// customer: {
|
|
139
|
-
// ...data.customer
|
|
140
|
-
// }
|
|
141
|
-
// }
|
|
142
|
-
// await customerService.updateCustomer({ userId: Number(updateUserId), data: dataCustomer })
|
|
143
|
-
// response = await customerService.getCustomer({ id: Number(updateUserId), datatypes: [] })
|
|
144
|
-
// }
|
|
145
|
-
// if (_userType === "operator" && "operator" in data) {
|
|
146
|
-
// let dataOperator: OperatorUpdateProps["data"] = {
|
|
147
|
-
// operator: {
|
|
148
|
-
// ...data.operator
|
|
149
|
-
// }
|
|
150
|
-
// }
|
|
151
|
-
// await operatorService.updateOperator({ userId: Number(updateUserId), data: dataOperator })
|
|
152
|
-
// response = await operatorService.getOperator({ id: Number(updateUserId), datatypes: [] })
|
|
153
|
-
// }
|
|
154
|
-
// if (_userType === "administrator" && "administrator" in data) {
|
|
155
|
-
// let dataCustomer: AdministratorUpdateProps["data"] = {
|
|
156
|
-
// administrator: {
|
|
157
|
-
// ...data.administrator
|
|
158
|
-
// }
|
|
159
|
-
// }
|
|
160
|
-
// await administratorService.updateAdministrator({ userId: Number(updateUserId), data: dataCustomer })
|
|
161
|
-
// // replace user prop
|
|
162
|
-
// await userPropService.replaceUserProp({
|
|
163
|
-
// userPropType: "LOCATION_ID",
|
|
164
|
-
// data: {
|
|
165
|
-
// userProp: {
|
|
166
|
-
// userId: Number(updateUserId),
|
|
167
|
-
// locationIds: data.props.locationIds
|
|
168
|
-
// }
|
|
169
|
-
// }
|
|
170
|
-
// })
|
|
171
|
-
// response = await administratorService.getAdministrator({ id: Number(updateUserId), datatypes: [] })
|
|
172
|
-
// }
|
|
173
|
-
// if (_userType === "worker" && "worker" in data) {
|
|
174
|
-
// let dataWorker: WorkerUpdateProps["data"] = {
|
|
175
|
-
// worker: {
|
|
176
|
-
// ...data.worker
|
|
177
|
-
// }
|
|
178
|
-
// }
|
|
179
|
-
// await workerService.updateWorker({ userId: Number(updateUserId), data: dataWorker })
|
|
180
|
-
// // replace user prop
|
|
181
|
-
// await userPropService.replaceUserProp({
|
|
182
|
-
// userPropType: "LOCATION_ID",
|
|
183
|
-
// data: {
|
|
184
|
-
// userProp: {
|
|
185
|
-
// userId: Number(updateUserId),
|
|
186
|
-
// locationIds: data.props.locationIds
|
|
187
|
-
// }
|
|
188
|
-
// }
|
|
189
|
-
// })
|
|
190
|
-
// response = await workerService.getWorker({ id: Number(updateUserId), datatypes: [] })
|
|
191
|
-
// }
|
|
192
|
-
// if (_userType === "driver" && "driver" in data) {
|
|
193
|
-
// let dataDriver: DriverUpdateProps["data"] = {
|
|
194
|
-
// driver: {
|
|
195
|
-
// ...data.driver
|
|
196
|
-
// }
|
|
197
|
-
// }
|
|
198
|
-
// await driverService.updateDriver({ userId: Number(updateUserId), data: dataDriver })
|
|
199
|
-
// // replace user prop
|
|
200
|
-
// await userPropService.replaceUserProp({
|
|
201
|
-
// userPropType: "LOCATION_ID",
|
|
202
|
-
// data: {
|
|
203
|
-
// userProp: {
|
|
204
|
-
// userId: Number(updateUserId),
|
|
205
|
-
// locationIds: data.props.locationIds
|
|
206
|
-
// }
|
|
207
|
-
// }
|
|
208
|
-
// })
|
|
209
|
-
// response = await driverService.getDriver({ id: Number(updateUserId), datatypes: [] })
|
|
210
|
-
// }
|
|
211
|
-
// if (_userType === "member" && "member" in data) {
|
|
212
|
-
// let dataMember: MemberUpdateProps["data"] = {
|
|
213
|
-
// member: {
|
|
214
|
-
// ...data.member
|
|
215
|
-
// }
|
|
216
|
-
// }
|
|
217
|
-
// await memberService.updateMember({ userId: Number(updateUserId), data: dataMember })
|
|
218
|
-
// // replace user prop
|
|
219
|
-
// // await userPropService.replaceUserProp({
|
|
220
|
-
// // userPropType: "LOCATION_ID",
|
|
221
|
-
// // data: {
|
|
222
|
-
// // userProp: {
|
|
223
|
-
// // userId: Number(updateUserId),
|
|
224
|
-
// // locationIds: data.props.locationIds
|
|
225
|
-
// // }
|
|
226
|
-
// // }
|
|
227
|
-
// // })
|
|
228
|
-
// response = await memberService.getUserMember({ id: Number(updateUserId), datatypes: [] })
|
|
229
|
-
// }
|
|
230
|
-
// if (_userType === "agent" && "agent" in data) {
|
|
231
|
-
// let dataAgent: AgentUpdateProps["data"] = {
|
|
232
|
-
// agent: {
|
|
233
|
-
// ...data.agent
|
|
234
|
-
// }
|
|
235
|
-
// }
|
|
236
|
-
// await agentService.updateAgent({ userId: Number(updateUserId), data: dataAgent })
|
|
237
|
-
// // replace user prop
|
|
238
|
-
// // await userPropService.replaceUserProp({
|
|
239
|
-
// // userPropType: "LOCATION_ID",
|
|
240
|
-
// // data: {
|
|
241
|
-
// // userProp: {
|
|
242
|
-
// // userId: Number(updateUserId),
|
|
243
|
-
// // locationIds: data.props.locationIds
|
|
244
|
-
// // }
|
|
245
|
-
// // }
|
|
246
|
-
// // })
|
|
247
|
-
// response = await agentService.getAgent({ id: Number(updateUserId), datatypes: [] })
|
|
248
|
-
// }
|
|
249
|
-
// if (_userType === "retailer" && "retailer" in data) {
|
|
250
|
-
// let dataRetailer: RetailerUpdateProps["data"] = {
|
|
251
|
-
// retailer: {
|
|
252
|
-
// ...data.retailer
|
|
253
|
-
// }
|
|
254
|
-
// }
|
|
255
|
-
// await retailerService.updateRetailer({ userId: Number(updateUserId), data: dataRetailer })
|
|
256
|
-
// response = await retailerService.getRetailer({ id: Number(updateUserId), datatypes: [] })
|
|
257
|
-
// }
|
|
258
|
-
// return response
|
|
259
|
-
// }
|
|
260
51
|
const getUserMe = async () => {
|
|
261
52
|
const id = userId;
|
|
262
53
|
const data = await userService.getUser({ id: userId, datatypes: [] });
|
|
@@ -278,10 +69,24 @@ const UserMeService = (props) => {
|
|
|
278
69
|
[`${models_1.ModelUserFields.address}`]: address,
|
|
279
70
|
}
|
|
280
71
|
});
|
|
281
|
-
|
|
72
|
+
const userMe = await userService.getUser({ id: Number(userId), datatypes: [] });
|
|
73
|
+
// Call the consumer hook, if success
|
|
74
|
+
if (features_1.UserMeHook.onSuccessUpdateMe) {
|
|
75
|
+
await features_1.UserMeHook.onSuccessUpdateMe({
|
|
76
|
+
userMe
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return userMe;
|
|
282
80
|
};
|
|
283
81
|
const removeUserMe = async () => {
|
|
82
|
+
const currentMe = await userService.getUser({ id: Number(userId), datatypes: [] });
|
|
284
83
|
const response = await userService.suspendUsers({ ids: [BigInt(userId)] });
|
|
84
|
+
// Call the consumer hook, if remove
|
|
85
|
+
if (features_1.UserMeHook.onSuccessRemoveMe) {
|
|
86
|
+
await features_1.UserMeHook.onSuccessRemoveMe({
|
|
87
|
+
userMe: currentMe
|
|
88
|
+
});
|
|
89
|
+
}
|
|
285
90
|
return response;
|
|
286
91
|
};
|
|
287
92
|
const changePasswordUserMe = async ({ currentPassword, confirmPassword, newPassword }) => {
|
|
@@ -327,6 +132,14 @@ const UserMeService = (props) => {
|
|
|
327
132
|
},
|
|
328
133
|
isOperator: Boolean(userType === "operator")
|
|
329
134
|
});
|
|
135
|
+
// Call the consumer hook, if change password
|
|
136
|
+
if (features_1.UserMeHook.onSuccessChangePasswordMe) {
|
|
137
|
+
// remove the password
|
|
138
|
+
delete user.password;
|
|
139
|
+
await features_1.UserMeHook.onSuccessChangePasswordMe({
|
|
140
|
+
userMe: user
|
|
141
|
+
});
|
|
142
|
+
}
|
|
330
143
|
return responseUser;
|
|
331
144
|
};
|
|
332
145
|
const allowUserTypes = ["any"];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserMeService.js","sourceRoot":"","sources":["../../../src/services/user/UserMeService.ts"],"names":[],"mappings":";;;AAAA,qCAOkB;AAelB,mKAAmK;AAEnK,mCAAuG;AAEvG,0CAA0C;AAE1C,+BAAuC;AAEvC,yCAA0E;AAE7D,QAAA,SAAS,GAAG;IACrB,QAAQ,EAAE,UAAU;IACpB,aAAa,EAAE,eAAe;IAC9B,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,OAAO;CACR,CAAA;AAoBV,mCAAmC;AACnC,0BAA0B;AAC1B,uCAAuC;AACvC,iBAAi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Country,\n CountryModel,\n ModelUserFields,\n ModelAdministratorFields,\n ModelCountryFields\n} from \"@/models\";\n\nimport { z } from \"zod\";\n\nimport { UserPropService, UserPropReplaceProps } from \"./UserPropService\";\n// import { CustomerGetProps, CustomerCreateProps, CustomerListProps, CustomerUpdateProps, CustomerService } from \"./CustomerService\";\n// import { AdministratorGetProps, AdministratorCreateProps, AdministratorUpdateProps, AdministratorListProps, AdministratorService } from \"./AdministratorService\";\n// import { WorkerCreateProps, WorkerGetProps, WorkerUpdateProps, WorkerListProps, WorkerService } from \"./WorkerService\";\n// import { DriverCreateProps, DriverGetProps, DriverUpdateProps, DriverListProps, DriverService } from \"./DriverService\";\n// import { RetailerCreateProps, RetailerGetProps, RetailerUpdateProps, RetailerListProps, RetailerService } from \"./RetailerService\";\n// import { MemberCreateProps, MemberGetProps, MemberUpdateProps, MemberListProps, MemberService } from \"./MemberService\";\n// import { AgentCreateProps, AgentGetProps, AgentUpdateProps, AgentListProps, AgentService } from \"./AgentService\";\n// import { OperatorCreateProps, OperatorGetProps, OperatorListProps, OperatorService, OperatorUpdateProps } from \"./OperatorService\";\n\nimport { QueryList, QueryGet } from \"@/schema/common\";\n// import { buildSqlRelation, buildSqlRawSelect, buildSqlWhere, buildSqlSelect, buildSqlLimitOffset, buildSqlOrderBy, buildInjectionFieldsSqlSelect } from \"@/lib\";\n\nimport { verifyPassword, validateLoginPasswordFormat, DefaultServiceProps, throwError } from \"@/utils\";\n\n// import { hashPassword } from \"@/utils\";\n\nimport { ServiceFactory } from \"@/lib\";\n\nimport { UserService, AccountService, UserUpdateProps } from \"@/services\";\n\nexport const userTypes = {\n operator: \"operator\",\n administrator: \"administrator\",\n worker: \"worker\",\n supplier: \"supplier\",\n customer: \"customer\",\n driver: \"driver\",\n retailer: \"retailer\",\n member: \"member\",\n agent: \"agent\",\n} as const\n\nexport type UserType = typeof userTypes[keyof typeof userTypes]\n\nexport type UserMeServiceProps = DefaultServiceProps & {\n // userType: UserType\n};\n\nexport type UserMeChangePasswordProps = {\n currentPassword: string\n newPassword: string\n confirmPassword: string\n};\n\nexport type UserMeUpdateProps = {\n firstName: string\n lastName: string\n address: string\n};\n\n// const getUpdatePayload = async (\n// userType: UserType,\n// data: UserMeUpdateProps[\"data\"],\n// contact: {\n// countryCode: number,\n// phoneNumber: string\n// }\n// ) => {\n\n// if (\"user\" in data) {\n\n// const newHashPassword = data?.user?.loginPassword ? await hashPassword(data.user.loginPassword) : \"\"\n\n// return {\n// [`${ModelUserFields.login_username}`]: data.user.loginUsername,\n// ...(newHashPassword ? { [`${ModelUserFields.login_password}`]: newHashPassword } : {}),\n// [`${ModelUserFields.address}`]: data.user.address,\n// [`${ModelUserFields.contact_country_code}`]: contact.countryCode,\n// [`${ModelUserFields.contact_phone_number}`]: contact.phoneNumber,\n// [`${ModelUserFields.email}`]: data.user.email,\n// [`${ModelUserFields.firstname}`]: data.user.firstname,\n// [`${ModelUserFields.lastname}`]: data.user.lastname,\n// [`${ModelUserFields.status}`]: Boolean(data.user.status),\n// [`${ModelUserFields.user_type}`]: `${userType}`\n// }\n// }\n\n// return false\n\n// }\n\nexport const UserMeService = (props: UserMeServiceProps) => {\n\n const {\n ...rest\n } = props\n\n const userType = rest.actionUserType as UserType\n const userId = rest.actionUserId\n\n const userService = UserService({ ...rest, userType })\n const userModel = UserModel({ ...rest })\n\n // const userModel = UserModel({ ...rest })\n\n // const userPropService = UserPropService({ ...rest, userPropType: \"LOCATION_ID\" })\n // const customerService = CustomerService({ ...rest })\n // const administratorService = AdministratorService({ ...rest })\n // const operatorService = OperatorService({ ...rest })\n // const workerService = WorkerService({ ...rest })\n // const driverService = DriverService({ ...rest })\n // const retailerService = RetailerService({ ...rest })\n // const memberService = MemberService({ ...rest })\n // const agentService = AgentService({ ...rest })\n\n // const validateAuthToken = (token: string) => {\n\n // // retrive core configuration\n // const coreConfig = getCoreConfiguration()\n\n // // const authSecretKey = config.AUTH_SECRET_KEY\n // const authSecretKey = coreConfig.authSecretKey\n\n // // const jwtData = jwt.verify(token, authSecretKey) as AuthJwtToken; // Verify JWT token\n // const jwtData = verifyAuthToken(token, authSecretKey); // Verify JWT token\n\n // }\n\n // const validateAuthAccessKey = async (accessKey: string) => {\n\n // const accessKeyUtilService = AccessKeyUtilService({\n // accessKeyUserType: \"administrator\",\n // accountId: 0,\n // actionUserId: 0,\n // actionUserType: \"\",\n // authToken: \"\",\n // isOperator: true,\n // })\n\n // const accessKeyData = await accessKeyUtilService.validateAccessKey({ data: { accessKey } });\n // }\n\n // const updateMe = async ({ id, data, userType: overrideUserType }: UserMeUpdateProps) => {\n\n // const _userType = overrideUserType || userType\n\n // // validate the credential contact no\n // const userLoginUsername = data.user.loginUsername\n // const userLoginPassword = data.user?.loginPassword ?? \"\"\n // const userContactCountryCode = data.user.contact.countryCode\n // const userContactPhoneNumber = data.user.contact.phoneNumber\n\n // // validate the contact no only can be digit in text only\n // // validate the country code in prefix\n // // await validateUserContact(userContactCountryCode, userContactPhoneNumber)\n\n // // validate login username\n // // validateLoginUsernameFormat(userLoginUsername)\n\n // // validate login password\n // // if (userLoginPassword) {\n // // validateLoginPasswordFormat(userLoginPassword)\n // // }\n\n // // check the username duplicated?\n // const checkUsername = await userModel.list({\n // limit: 1,\n // offset: 0,\n // orderBy: {\n // [`${ModelUserFields.user_id}`]: \"asc\"\n // },\n // include: [],\n // where: {\n // [`${ModelUserFields.login_username}`]: data.user.loginUsername,\n // [`${ModelUserFields.isdelete}`]: false,\n // [`${ModelUserFields.istrash}`]: false,\n // [`${ModelUserFields.accountid}`]: rest.accountId,\n // },\n // })\n\n // // console.log('ch', checkUsername)\n\n // if (checkUsername.length > 0) {\n // if (Number(checkUsername[0]?.user_id) !== Number(id)) { // if not self user id\n // throwError(`Duplicated username: ${data.user.loginUsername}(${checkUsername[0]?.user_type})`)\n // }\n // }\n\n // // validation before insertion\n // // if (_userType === \"member\" && \"member\" in data) {\n // // }\n\n // const _data = await getUpdatePayload(\n // _userType,\n // data,\n // {\n // countryCode: userContactCountryCode,\n // phoneNumber: userContactPhoneNumber\n // }\n // )\n\n // if (!_data) {\n // throw new Error(`Invalid update payload: ${JSON.stringify(_data)}`);\n // }\n\n // // update user\n // let responseUser = await userModel.update({ id, data: _data })\n\n // let updateUserId = responseUser.user_id\n\n // let response: any = {}\n\n // if (_userType === \"customer\" && \"customer\" in data) {\n\n // let dataCustomer: CustomerUpdateProps[\"data\"] = {\n // customer: {\n // ...data.customer\n // }\n // }\n\n // await customerService.updateCustomer({ userId: Number(updateUserId), data: dataCustomer })\n\n // response = await customerService.getCustomer({ id: Number(updateUserId), datatypes: [] })\n\n // }\n\n // if (_userType === \"operator\" && \"operator\" in data) {\n\n // let dataOperator: OperatorUpdateProps[\"data\"] = {\n // operator: {\n // ...data.operator\n // }\n // }\n\n // await operatorService.updateOperator({ userId: Number(updateUserId), data: dataOperator })\n\n // response = await operatorService.getOperator({ id: Number(updateUserId), datatypes: [] })\n\n // }\n\n // if (_userType === \"administrator\" && \"administrator\" in data) {\n\n // let dataCustomer: AdministratorUpdateProps[\"data\"] = {\n // administrator: {\n // ...data.administrator\n // }\n // }\n\n // await administratorService.updateAdministrator({ userId: Number(updateUserId), data: dataCustomer })\n\n // // replace user prop\n // await userPropService.replaceUserProp({\n // userPropType: \"LOCATION_ID\",\n // data: {\n // userProp: {\n // userId: Number(updateUserId),\n // locationIds: data.props.locationIds\n // }\n // }\n // })\n\n // response = await administratorService.getAdministrator({ id: Number(updateUserId), datatypes: [] })\n\n // }\n\n // if (_userType === \"worker\" && \"worker\" in data) {\n\n // let dataWorker: WorkerUpdateProps[\"data\"] = {\n // worker: {\n // ...data.worker\n // }\n // }\n\n // await workerService.updateWorker({ userId: Number(updateUserId), data: dataWorker })\n\n // // replace user prop\n // await userPropService.replaceUserProp({\n // userPropType: \"LOCATION_ID\",\n // data: {\n // userProp: {\n // userId: Number(updateUserId),\n // locationIds: data.props.locationIds\n // }\n // }\n // })\n\n // response = await workerService.getWorker({ id: Number(updateUserId), datatypes: [] })\n\n // }\n\n // if (_userType === \"driver\" && \"driver\" in data) {\n\n // let dataDriver: DriverUpdateProps[\"data\"] = {\n // driver: {\n // ...data.driver\n // }\n // }\n\n // await driverService.updateDriver({ userId: Number(updateUserId), data: dataDriver })\n\n // // replace user prop\n // await userPropService.replaceUserProp({\n // userPropType: \"LOCATION_ID\",\n // data: {\n // userProp: {\n // userId: Number(updateUserId),\n // locationIds: data.props.locationIds\n // }\n // }\n // })\n\n // response = await driverService.getDriver({ id: Number(updateUserId), datatypes: [] })\n\n // }\n\n // if (_userType === \"member\" && \"member\" in data) {\n\n // let dataMember: MemberUpdateProps[\"data\"] = {\n // member: {\n // ...data.member\n // }\n // }\n\n // await memberService.updateMember({ userId: Number(updateUserId), data: dataMember })\n\n // // replace user prop\n // // await userPropService.replaceUserProp({\n // // userPropType: \"LOCATION_ID\",\n // // data: {\n // // userProp: {\n // // userId: Number(updateUserId),\n // // locationIds: data.props.locationIds\n // // }\n // // }\n // // })\n\n // response = await memberService.getUserMember({ id: Number(updateUserId), datatypes: [] })\n\n // }\n\n // if (_userType === \"agent\" && \"agent\" in data) {\n\n // let dataAgent: AgentUpdateProps[\"data\"] = {\n // agent: {\n // ...data.agent\n // }\n // }\n\n // await agentService.updateAgent({ userId: Number(updateUserId), data: dataAgent })\n\n // // replace user prop\n // // await userPropService.replaceUserProp({\n // // userPropType: \"LOCATION_ID\",\n // // data: {\n // // userProp: {\n // // userId: Number(updateUserId),\n // // locationIds: data.props.locationIds\n // // }\n // // }\n // // })\n\n // response = await agentService.getAgent({ id: Number(updateUserId), datatypes: [] })\n\n // }\n\n // if (_userType === \"retailer\" && \"retailer\" in data) {\n\n // let dataRetailer: RetailerUpdateProps[\"data\"] = {\n // retailer: {\n // ...data.retailer\n // }\n // }\n\n // await retailerService.updateRetailer({ userId: Number(updateUserId), data: dataRetailer })\n\n // response = await retailerService.getRetailer({ id: Number(updateUserId), datatypes: [] })\n\n // }\n\n // return response\n // }\n\n const getUserMe = async () => {\n\n const id = userId\n\n const data = await userService.getUser({ id: userId, datatypes: [] })\n\n return data\n };\n\n const updateUserMe = async ({\n firstName = \"\",\n lastName = \"\",\n address = \"\"\n }: UserMeUpdateProps) => {\n\n const user = await userService.getUser({ id: Number(userId), datatypes: [] })\n\n // console.log('user', user)\n\n // check the userId is valid\n if (!user?.user_id) {\n throwError(`Invalid user id in auth token`)\n }\n\n // change user information\n await userModel.update({\n id: Number(userId),\n data: {\n [`${ModelUserFields.firstname}`]: firstName,\n [`${ModelUserFields.lastname}`]: lastName,\n [`${ModelUserFields.address}`]: address,\n }\n })\n\n return await userService.getUser({ id: Number(userId), datatypes: [] })\n\n }\n\n const removeUserMe = async () => {\n\n const response = await userService.suspendUsers({ ids: [BigInt(userId)] })\n\n return response\n };\n\n const changePasswordUserMe = async ({\n currentPassword,\n confirmPassword,\n newPassword\n }: UserMeChangePasswordProps) => {\n\n const accountId = rest?.accountId ?? 0\n const accountService = AccountService({ ...rest, isOperator: true })\n\n const user = await userService.getUser({ id: Number(userId), datatypes: [], includePassword: true })\n const account = await accountService.getAccount({ id: Number(accountId), datatypes: [] })\n\n // console.log('user', user)\n // console.log('account', account)\n\n // check the accountId / userId is valid\n if (!user?.user_id) {\n throwError(`Invalid user id in auth token`)\n }\n\n if (Object.keys(account).length <= 0) { // must have account id record\n throwError(`Invalid account id in auth token`)\n }\n\n // new password cannot same with current password\n if (newPassword === currentPassword) {\n throwError(`New and current password cannot be same`)\n }\n\n // new password must same with confirm\n if (newPassword !== confirmPassword) {\n throwError(`New and confirm password not matched`)\n }\n\n // validate the login password new format\n validateLoginPasswordFormat(newPassword);\n\n // check the current password\n try {\n const decryptedPass = await verifyPassword(currentPassword, user?.password)\n // console.log('decryptedPass', decryptedPass)\n\n if (!decryptedPass) {\n throw Error(`Invalid current password`)\n }\n\n } catch (error: any) {\n throwError(`Auth Token: ${error?.message}`)\n }\n\n // perform update credential\n const responseUser = await userService.replacePassword({\n id: Number(userId),\n data: {\n unhashLoginPassword: newPassword\n },\n isOperator: Boolean(userType === \"operator\")\n })\n\n return responseUser\n\n }\n\n const allowUserTypes = [\"any\"] as const\n\n const methodConfigs = {\n getUserMe: { fn: getUserMe, allowUserTypes, actionName: \"get user/me\" },\n updateUserMe: { fn: updateUserMe, allowUserTypes, actionName: \"update user/me\" },\n changePasswordUserMe: { fn: changePasswordUserMe, allowUserTypes, actionName: \"change password user/me\" },\n removeUserMe: { fn: removeUserMe, allowUserTypes, actionName: \"remove user/me\" },\n };\n\n return ServiceFactory(\"UserMeService\", rest, methodConfigs);\n\n}\n\n"]}
|
|
1
|
+
{"version":3,"file":"UserMeService.js","sourceRoot":"","sources":["../../../src/services/user/UserMeService.ts"],"names":[],"mappings":";;;AAAA,qCAGkB;AAElB,mCAAuG;AAEvG,+BAAuC;AAEvC,yCAAyD;AAEzD,yCAAkJ;AAErI,QAAA,SAAS,GAAG;IACrB,QAAQ,EAAE,UAAU;IACpB,aAAa,EAAE,eAAe;IAC9B,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,OAAO;CACR,CAAA;AAoBV,mCAAmC;AACnC,0BAA0B;AAC1B,uCAAuC;AACvC,iBAAiB;AACjB,+BAA+B;AAC/B,8BAA8B;AAC9B,QAAQ;AACR,SAAS;AAET,4BAA4B;AAE5B,+GAA+G;AAE/G,mBAAmB;AACnB,8EAA8E;AAC9E,sGAAsG;AACtG,iEAAiE;AACjE,gFAAgF;AAChF,gFAAgF;AAChF,6DAA6D;AAC7D,qEAAqE;AACrE,mEAAmE;AACnE,wEAAwE;AACxE,8DAA8D;AAC9D,YAAY;AACZ,QAAQ;AAER,mBAAmB;AAEnB,IAAI;AAEG,MAAM,aAAa,GAAG,CAAC,KAAyB,EAAE,EAAE;IAEvD,MAAM,EACF,GAAG,IAAI,EACV,GAAG,KAA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CAAC;YAClB,IAAI,EAAE;gBACF,mBAAmB,EAAE,WAAW;aACnC;YACD,UAAU,EAAE,OAAO,CAAC,QAAQ,KAAK,UAAU,CAAC;SAC/C,CAAC,CAAA;QAEF,6CAA6C;QAC7C,IAAI,qBAAU,CAAC,yBAAyB,EAAE,CAAC;YAEvC,sBAAsB;YACtB,OAAO,IAAI,CAAC,QAAQ,CAAA;YAEpB,MAAM,qBAAU,CAAC,yBAAyB,CAAC;gBACvC,MAAM,EAAE,IAAI;aACf,CAAC,CAAA;QACN,CAAC;QAED,OAAO,YAAY,CAAA;IAEvB,CAAC,CAAA;IAED,MAAM,cAAc,GAAG,CAAC,KAAK,CAAU,CAAA;IAEvC,MAAM,aAAa,GAAG;QAClB,SAAS,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,cAAc,EAAE,UAAU,EAAE,aAAa,EAAE;QACvE,YAAY,EAAE,EAAE,EAAE,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,gBAAgB,EAAE;QAChF,oBAAoB,EAAE,EAAE,EAAE,EAAE,oBAAoB,EAAE,cAAc,EAAE,UAAU,EAAE,yBAAyB,EAAE;QACzG,YAAY,EAAE,EAAE,EAAE,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,gBAAgB,EAAE;KACnF,CAAC;IAEF,OAAO,IAAA,oBAAc,EAAC,eAAe,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC;AAEhE,CAAC,CAAA;AAhKY,QAAA,aAAa,iBAgKzB","sourcesContent":["import {\n UserModel,\n ModelUserFields\n} from \"@/models\";\n\nimport { verifyPassword, validateLoginPasswordFormat, DefaultServiceProps, throwError } from \"@/utils\";\n\nimport { ServiceFactory } from \"@/lib\";\n\nimport { UserService, AccountService } from \"@/services\";\n\nimport { UserMeHook, FeatureUserMeSuccessUpdateProps, FeatureUserMeSuccessChangePasswordProps, FeatureUserMeSuccessRemoveProps } from \"@/features\"\n\nexport const userTypes = {\n operator: \"operator\",\n administrator: \"administrator\",\n worker: \"worker\",\n supplier: \"supplier\",\n customer: \"customer\",\n driver: \"driver\",\n retailer: \"retailer\",\n member: \"member\",\n agent: \"agent\",\n} as const\n\nexport type UserType = typeof userTypes[keyof typeof userTypes]\n\nexport type UserMeServiceProps = DefaultServiceProps & {\n // userType: UserType\n};\n\nexport type UserMeChangePasswordProps = {\n currentPassword: string\n newPassword: string\n confirmPassword: string\n};\n\nexport type UserMeUpdateProps = {\n firstName: string\n lastName: string\n address: string\n};\n\n// const getUpdatePayload = async (\n// userType: UserType,\n// data: UserMeUpdateProps[\"data\"],\n// contact: {\n// countryCode: number,\n// phoneNumber: string\n// }\n// ) => {\n\n// if (\"user\" in data) {\n\n// const newHashPassword = data?.user?.loginPassword ? await hashPassword(data.user.loginPassword) : \"\"\n\n// return {\n// [`${ModelUserFields.login_username}`]: data.user.loginUsername,\n// ...(newHashPassword ? { [`${ModelUserFields.login_password}`]: newHashPassword } : {}),\n// [`${ModelUserFields.address}`]: data.user.address,\n// [`${ModelUserFields.contact_country_code}`]: contact.countryCode,\n// [`${ModelUserFields.contact_phone_number}`]: contact.phoneNumber,\n// [`${ModelUserFields.email}`]: data.user.email,\n// [`${ModelUserFields.firstname}`]: data.user.firstname,\n// [`${ModelUserFields.lastname}`]: data.user.lastname,\n// [`${ModelUserFields.status}`]: Boolean(data.user.status),\n// [`${ModelUserFields.user_type}`]: `${userType}`\n// }\n// }\n\n// return false\n\n// }\n\nexport const UserMeService = (props: UserMeServiceProps) => {\n\n const {\n ...rest\n } = props\n\n const userType = rest.actionUserType as UserType\n const userId = rest.actionUserId\n\n const userService = UserService({ ...rest, userType })\n const userModel = UserModel({ ...rest })\n\n const getUserMe = async () => {\n\n const id = userId\n\n const data = await userService.getUser({ id: userId, datatypes: [] })\n\n return data\n };\n\n const updateUserMe = async ({\n firstName = \"\",\n lastName = \"\",\n address = \"\"\n }: UserMeUpdateProps) => {\n\n const user = await userService.getUser({ id: Number(userId), datatypes: [] })\n\n // console.log('user', user)\n\n // check the userId is valid\n if (!user?.user_id) {\n throwError(`Invalid user id in auth token`)\n }\n\n // change user information\n await userModel.update({\n id: Number(userId),\n data: {\n [`${ModelUserFields.firstname}`]: firstName,\n [`${ModelUserFields.lastname}`]: lastName,\n [`${ModelUserFields.address}`]: address,\n }\n })\n\n const userMe = await userService.getUser({ id: Number(userId), datatypes: [] })\n\n // Call the consumer hook, if success\n if (UserMeHook.onSuccessUpdateMe) {\n await UserMeHook.onSuccessUpdateMe({\n userMe\n })\n }\n\n return userMe\n\n }\n\n const removeUserMe = async () => {\n\n const currentMe = await userService.getUser({ id: Number(userId), datatypes: [] })\n\n const response = await userService.suspendUsers({ ids: [BigInt(userId)] })\n\n // Call the consumer hook, if remove\n if (UserMeHook.onSuccessRemoveMe) {\n await UserMeHook.onSuccessRemoveMe({\n userMe: currentMe\n })\n }\n\n return response\n };\n\n const changePasswordUserMe = async ({\n currentPassword,\n confirmPassword,\n newPassword\n }: UserMeChangePasswordProps) => {\n\n const accountId = rest?.accountId ?? 0\n const accountService = AccountService({ ...rest, isOperator: true })\n\n const user = await userService.getUser({ id: Number(userId), datatypes: [], includePassword: true })\n const account = await accountService.getAccount({ id: Number(accountId), datatypes: [] })\n\n // console.log('user', user)\n // console.log('account', account)\n\n // check the accountId / userId is valid\n if (!user?.user_id) {\n throwError(`Invalid user id in auth token`)\n }\n\n if (Object.keys(account).length <= 0) { // must have account id record\n throwError(`Invalid account id in auth token`)\n }\n\n // new password cannot same with current password\n if (newPassword === currentPassword) {\n throwError(`New and current password cannot be same`)\n }\n\n // new password must same with confirm\n if (newPassword !== confirmPassword) {\n throwError(`New and confirm password not matched`)\n }\n\n // validate the login password new format\n validateLoginPasswordFormat(newPassword);\n\n // check the current password\n try {\n const decryptedPass = await verifyPassword(currentPassword, user?.password)\n // console.log('decryptedPass', decryptedPass)\n\n if (!decryptedPass) {\n throw Error(`Invalid current password`)\n }\n\n } catch (error: any) {\n throwError(`Auth Token: ${error?.message}`)\n }\n\n // perform update credential\n const responseUser = await userService.replacePassword({\n id: Number(userId),\n data: {\n unhashLoginPassword: newPassword\n },\n isOperator: Boolean(userType === \"operator\")\n })\n\n // Call the consumer hook, if change password\n if (UserMeHook.onSuccessChangePasswordMe) {\n\n // remove the password\n delete user.password\n\n await UserMeHook.onSuccessChangePasswordMe({\n userMe: user\n })\n }\n\n return responseUser\n\n }\n\n const allowUserTypes = [\"any\"] as const\n\n const methodConfigs = {\n getUserMe: { fn: getUserMe, allowUserTypes, actionName: \"get user/me\" },\n updateUserMe: { fn: updateUserMe, allowUserTypes, actionName: \"update user/me\" },\n changePasswordUserMe: { fn: changePasswordUserMe, allowUserTypes, actionName: \"change password user/me\" },\n removeUserMe: { fn: removeUserMe, allowUserTypes, actionName: \"remove user/me\" },\n };\n\n return ServiceFactory(\"UserMeService\", rest, methodConfigs);\n\n}\n\n"]}
|