@ohos-ports/core 1.0.113-beta.0 → 1.16.33-beta.0
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/LICENSE +13 -0
- package/README.md +3 -0
- package/lib/api/node.js +176 -0
- package/lib/api/team.js +1889 -0
- package/lib/blocklet/downloader/blocklet-downloader.js +246 -0
- package/lib/blocklet/downloader/bundle-downloader.js +316 -0
- package/lib/blocklet/downloader/constants.js +3 -0
- package/lib/blocklet/downloader/resolve-download.js +187 -0
- package/lib/blocklet/extras.js +177 -0
- package/lib/blocklet/hooks.js +89 -0
- package/lib/blocklet/manager/base.js +49 -0
- package/lib/blocklet/manager/config-synchronizer.js +128 -0
- package/lib/blocklet/manager/disk.js +5170 -0
- package/lib/blocklet/manager/engine.js +124 -0
- package/lib/blocklet/manager/helper/install-application-from-backup.js +285 -0
- package/lib/blocklet/manager/helper/install-application-from-dev.js +72 -0
- package/lib/blocklet/manager/helper/install-application-from-general.js +209 -0
- package/lib/blocklet/manager/helper/install-component-from-dev.js +128 -0
- package/lib/blocklet/manager/helper/install-component-from-upload.js +197 -0
- package/lib/blocklet/manager/helper/install-component-from-url.js +214 -0
- package/lib/blocklet/manager/helper/migrate-application-to-struct-v2.js +557 -0
- package/lib/blocklet/manager/helper/rollback-cache.js +41 -0
- package/lib/blocklet/manager/helper/upgrade-components.js +179 -0
- package/lib/blocklet/manager/pm2-events.js +50 -0
- package/lib/blocklet/migration-dist/migration.cjs +38605 -0
- package/lib/blocklet/migration-dist/run-script.cjs +29 -0
- package/lib/blocklet/migration.js +145 -0
- package/lib/blocklet/project/connect-by-studio.js +91 -0
- package/lib/blocklet/project/connect-to-store.js +64 -0
- package/lib/blocklet/project/create-pack-release.js +293 -0
- package/lib/blocklet/project/disconnect-from-store.js +13 -0
- package/lib/blocklet/project/get-is-multiple-tenant.js +8 -0
- package/lib/blocklet/project/index.js +545 -0
- package/lib/blocklet/project/logo.png +0 -0
- package/lib/blocklet/project/publish-to-store.js +108 -0
- package/lib/blocklet/project/util.js +194 -0
- package/lib/blocklet/security/access-policy.js +131 -0
- package/lib/blocklet/security/index.js +309 -0
- package/lib/blocklet/security/response-header-policy.js +178 -0
- package/lib/blocklet/security/security-rule.js +127 -0
- package/lib/blocklet/security/utils.js +35 -0
- package/lib/blocklet/security/validator.js +40 -0
- package/lib/blocklet/storage/backup/base.js +149 -0
- package/lib/blocklet/storage/backup/blocklet-extras.js +110 -0
- package/lib/blocklet/storage/backup/blocklet.js +159 -0
- package/lib/blocklet/storage/backup/blocklets.js +109 -0
- package/lib/blocklet/storage/backup/data.js +35 -0
- package/lib/blocklet/storage/backup/disk.js +131 -0
- package/lib/blocklet/storage/backup/logs.js +24 -0
- package/lib/blocklet/storage/backup/routing-rule.js +47 -0
- package/lib/blocklet/storage/backup/spaces.js +345 -0
- package/lib/blocklet/storage/restore/base.js +74 -0
- package/lib/blocklet/storage/restore/blocklet-extras.js +89 -0
- package/lib/blocklet/storage/restore/blocklet.js +56 -0
- package/lib/blocklet/storage/restore/blocklets.js +43 -0
- package/lib/blocklet/storage/restore/disk.js +104 -0
- package/lib/blocklet/storage/restore/logs.js +21 -0
- package/lib/blocklet/storage/restore/spaces.js +174 -0
- package/lib/blocklet/storage/utils/disk.js +178 -0
- package/lib/blocklet/storage/utils/hash.js +53 -0
- package/lib/blocklet/storage/utils/zip.js +43 -0
- package/lib/cert.js +221 -0
- package/lib/crons/check-new-version.js +68 -0
- package/lib/crons/monitor-disk-usage.js +46 -0
- package/lib/crons/rotate-pm2-logs/index.js +41 -0
- package/lib/crons/rotate-pm2-logs/script.js +56 -0
- package/lib/event/auto-backup-handler.js +48 -0
- package/lib/event/index.js +520 -0
- package/lib/index.js +768 -364
- package/lib/locales/ar.js +18 -0
- package/lib/locales/de.js +21 -0
- package/lib/locales/en.js +19 -0
- package/lib/locales/es.js +21 -0
- package/lib/locales/fr.js +21 -0
- package/lib/locales/hi.js +18 -0
- package/lib/locales/i18n.db +0 -0
- package/lib/locales/id.js +20 -0
- package/lib/locales/index.js +54 -0
- package/lib/locales/ja.js +19 -0
- package/lib/locales/ko.js +18 -0
- package/lib/locales/pt.js +20 -0
- package/lib/locales/ru.js +21 -0
- package/lib/locales/th.js +18 -0
- package/lib/locales/vi.js +18 -0
- package/lib/locales/zh-tw.js +17 -0
- package/lib/locales/zh.js +17 -0
- package/lib/migrations/1.0.21-update-config.js +34 -0
- package/lib/migrations/1.0.22-max-memory.js +40 -0
- package/lib/migrations/1.0.25.js +36 -0
- package/lib/migrations/1.0.32-update-config.js +30 -0
- package/lib/migrations/1.0.33-blocklets.js +33 -0
- package/lib/migrations/1.0.36-snapshot.js +10 -0
- package/lib/migrations/1.1.10-team.js +26 -0
- package/lib/migrations/1.1.9-snapshot.js +7 -0
- package/lib/migrations/1.16.11-component-status.js +22 -0
- package/lib/migrations/1.16.33-blocklet-security-rule.js +17 -0
- package/lib/migrations/1.16.6-chain-info.js +78 -0
- package/lib/migrations/1.16.8-component-title.js +66 -0
- package/lib/migrations/1.2.11-blocklet-registry.js +10 -0
- package/lib/migrations/1.2.2-blocklet-registry.js +10 -0
- package/lib/migrations/1.3.1-disk-alert-threshold.js +10 -0
- package/lib/migrations/1.4.5-access-key.js +18 -0
- package/lib/migrations/1.5.0-site.js +34 -0
- package/lib/migrations/1.5.15-site.js +184 -0
- package/lib/migrations/1.5.20-registry.js +15 -0
- package/lib/migrations/1.6.17-blocklet-children.js +48 -0
- package/lib/migrations/1.6.21-rename-ip-echo-domain.js +35 -0
- package/lib/migrations/1.6.4-security.js +59 -0
- package/lib/migrations/1.6.5-security.js +60 -0
- package/lib/migrations/1.6.9-update-node-info-and-certificate.js +39 -0
- package/lib/migrations/1.7.1-blocklet-setup.js +18 -0
- package/lib/migrations/1.7.12-blocklet-meta.js +51 -0
- package/lib/migrations/1.7.15-blocklet-bundle-source.js +42 -0
- package/lib/migrations/1.7.20-blocklet-component.js +41 -0
- package/lib/migrations/1.8.33-blocklet-mem-limit.js +20 -0
- package/lib/migrations/README.md +71 -0
- package/lib/migrations/index.js +215 -0
- package/lib/monitor/blocklet-runtime-monitor.js +204 -0
- package/lib/monitor/get-history-list.js +37 -0
- package/lib/monitor/node-monit-sender.js +99 -0
- package/lib/monitor/node-runtime-monitor.js +205 -0
- package/lib/processes/updater.js +186 -0
- package/lib/router/helper.js +1653 -0
- package/lib/router/index.js +341 -0
- package/lib/router/manager.js +806 -0
- package/lib/states/README.md +38 -0
- package/lib/states/access-key.js +124 -0
- package/lib/states/access-policy.js +29 -0
- package/lib/states/audit-log.js +734 -0
- package/lib/states/backup.js +165 -0
- package/lib/states/base.js +25 -0
- package/lib/states/blocklet-extras.js +257 -0
- package/lib/states/blocklet.js +755 -0
- package/lib/states/cache.js +23 -0
- package/lib/states/connect-account.js +8 -0
- package/lib/states/index.js +76 -0
- package/lib/states/job.js +8 -0
- package/lib/states/migration.js +34 -0
- package/lib/states/node.js +324 -0
- package/lib/states/notification.js +81 -0
- package/lib/states/passport.js +8 -0
- package/lib/states/project.js +119 -0
- package/lib/states/release.js +50 -0
- package/lib/states/response-header-policy.js +30 -0
- package/lib/states/routing-snapshot.js +146 -0
- package/lib/states/runtime-insight.js +25 -0
- package/lib/states/security-rule.js +30 -0
- package/lib/states/session.js +53 -0
- package/lib/states/site.js +102 -0
- package/lib/states/tag.js +8 -0
- package/lib/states/traffic-insight.js +25 -0
- package/lib/states/user-session.js +8 -0
- package/lib/states/user.js +717 -0
- package/lib/states/verify-code.js +152 -0
- package/lib/states/webhook.js +66 -0
- package/lib/team/manager.js +508 -0
- package/lib/util/blocklet.js +2182 -0
- package/lib/util/cache.js +63 -0
- package/lib/util/chain.js +29 -0
- package/lib/util/default-node-config.js +46 -0
- package/lib/util/docker/blocklet-custom-dockerfile.js +92 -0
- package/lib/util/docker/check-docker-has-image.js +23 -0
- package/lib/util/docker/check-docker-installed.js +32 -0
- package/lib/util/docker/check-docker-run-history.js +18 -0
- package/lib/util/docker/check-need-run-docker.js +32 -0
- package/lib/util/docker/create-docker-image.js +65 -0
- package/lib/util/docker/debian-dockerfile.js +50 -0
- package/lib/util/docker/docker-container-prune.js +75 -0
- package/lib/util/docker/docker-exec-chown.js +39 -0
- package/lib/util/docker/docker-exec.js +68 -0
- package/lib/util/docker/docker-remove-by-name.js +20 -0
- package/lib/util/docker/get-docker-runtime-info.js +39 -0
- package/lib/util/docker/parse-docker-name.js +10 -0
- package/lib/util/docker/parse-docker-options-from-pm2.js +295 -0
- package/lib/util/docker/shard-network.js +10 -0
- package/lib/util/domain-status.js +118 -0
- package/lib/util/get-accessible-external-node-ip.js +92 -0
- package/lib/util/get-dynamic-components.js +47 -0
- package/lib/util/get-meta-from-url.js +30 -0
- package/lib/util/get-migration-scripts.js +36 -0
- package/lib/util/get-safe-env.js +12 -0
- package/lib/util/index.js +522 -0
- package/lib/util/install-external-dependencies.js +67 -0
- package/lib/util/ip.js +53 -0
- package/lib/util/launcher.js +475 -0
- package/lib/util/log.js +431 -0
- package/lib/util/maintain.js +178 -0
- package/lib/util/promise-debounce.js +29 -0
- package/lib/util/promise-once.js +14 -0
- package/lib/util/promise-spawn.js +93 -0
- package/lib/util/queue.js +44 -0
- package/lib/util/ready.js +89 -0
- package/lib/util/request.js +10 -0
- package/lib/util/requirement.js +61 -0
- package/lib/util/reset-node.js +166 -0
- package/lib/util/rotator.js +194 -0
- package/lib/util/router.js +122 -0
- package/lib/util/rpc.js +78 -0
- package/lib/util/spaces.js +102 -0
- package/lib/util/store.js +184 -0
- package/lib/util/sysinfo.js +46 -0
- package/lib/util/ua.js +54 -0
- package/lib/validators/backup.js +34 -0
- package/lib/validators/blocklet-extra.js +18 -0
- package/lib/validators/node.js +73 -0
- package/lib/validators/permission.js +38 -0
- package/lib/validators/project.js +39 -0
- package/lib/validators/role.js +64 -0
- package/lib/validators/router.js +192 -0
- package/lib/validators/space-gateway.js +33 -0
- package/lib/validators/trusted-factory.js +28 -0
- package/lib/validators/trusted-passport.js +32 -0
- package/lib/validators/user.js +62 -0
- package/lib/validators/util.js +92 -0
- package/lib/validators/webhook.js +42 -0
- package/lib/webhook/index.js +216 -0
- package/lib/webhook/reduce-queue.js +12 -0
- package/lib/webhook/sender/api/index.js +67 -0
- package/lib/webhook/sender/base.js +11 -0
- package/lib/webhook/sender/index.js +44 -0
- package/lib/webhook/sender/slack/index.js +167 -0
- package/lib/webhook/sender/wallet/index.js +62 -0
- package/package.json +107 -34
- package/examples/BatchClient.js +0 -61
- package/examples/compressor/example.js +0 -7
- package/examples/jsonrpcserver/rpcmethod.js +0 -21
- package/examples/jsonrpcserver/rpcrequest.js +0 -20
- package/examples/jsonrpcserver/rpctest.js +0 -6
- package/examples/loader-pipes/test-mc.js +0 -52
- package/examples/loader-pipes/test.js +0 -51
- package/examples/mc-test.js +0 -44
- package/examples/redisdebug.js +0 -80
- package/lib/cache/CFMemcache.js +0 -57
- package/lib/cache/CacheLoader.js +0 -217
- package/lib/cache/Memcache.js +0 -406
- package/lib/class/Class.js +0 -54
- package/lib/client/MemcacheAdapter.js +0 -139
- package/lib/client/Memcached.js +0 -142
- package/lib/client/MemcachedSocket.js +0 -570
- package/lib/client/MySQLPool.js +0 -153
- package/lib/client/PGPool.js +0 -296
- package/lib/client/Redis.js +0 -787
- package/lib/client/S3.js +0 -103
- package/lib/client/S3Client.js +0 -392
- package/lib/client/pg/CursorQueryWorker.js +0 -160
- package/lib/client/rabbitmq/RbmqChannel.js +0 -61
- package/lib/client/rabbitmq/RbmqConfig.js +0 -144
- package/lib/client/rabbitmq/RbmqConnection.js +0 -259
- package/lib/client/rabbitmq/RbmqExchange.js +0 -112
- package/lib/client/rabbitmq/RbmqIncomingMessage.js +0 -53
- package/lib/client/rabbitmq/RbmqMessage.js +0 -120
- package/lib/client/rabbitmq/RbmqOutcomingMessage.js +0 -47
- package/lib/client/rabbitmq/RbmqQueue.js +0 -87
- package/lib/client/rabbitmq/index.js +0 -8
- package/lib/common/Assertions.js +0 -184
- package/lib/common/Merge.js +0 -32
- package/lib/common/Net.js +0 -56
- package/lib/common/Process.js +0 -20
- package/lib/common/Random.js +0 -53
- package/lib/common/Sort.js +0 -19
- package/lib/common/Types.js +0 -163
- package/lib/credentials/CredentialsProvider.js +0 -45
- package/lib/credentials/Manager.js +0 -101
- package/lib/crypto/Crypto.js +0 -66
- package/lib/data/BinaryData.js +0 -363
- package/lib/data/Compressor.js +0 -83
- package/lib/data/FormData.js +0 -144
- package/lib/data/Mime.js +0 -45
- package/lib/event/ErrorEvent.js +0 -71
- package/lib/event/Event.js +0 -20
- package/lib/event/EventDispatcher.js +0 -157
- package/lib/http/ConnectionPool.js +0 -82
- package/lib/http/ExpressServer.js +0 -19
- package/lib/http/Headers.js +0 -165
- package/lib/http/Loader.js +0 -584
- package/lib/http/Message.js +0 -189
- package/lib/http/Request.js +0 -848
- package/lib/http/RequestProcessor.js +0 -150
- package/lib/http/Response.js +0 -850
- package/lib/http/Server.js +0 -267
- package/lib/http/Socket.js +0 -157
- package/lib/http/Url.js +0 -2
- package/lib/jsonrpc/JsonRpcAbstract.js +0 -109
- package/lib/jsonrpc/JsonRpcBatchRequest.js +0 -54
- package/lib/jsonrpc/JsonRpcBatchResponse.js +0 -73
- package/lib/jsonrpc/JsonRpcError.js +0 -191
- package/lib/jsonrpc/JsonRpcMethod.js +0 -67
- package/lib/jsonrpc/JsonRpcRequest.js +0 -224
- package/lib/jsonrpc/JsonRpcRequestProcessor.js +0 -366
- package/lib/jsonrpc/JsonRpcResponse.js +0 -175
- package/lib/jsonrpc/JsonRpcServer.js +0 -81
- package/lib/logger/EmptyLogger.js +0 -15
- package/lib/logger/LoggerFactory.js +0 -20
- package/lib/logger/WildFireLogger.js +0 -267
- package/lib/pattern/Pool.js +0 -187
- package/lib/pattern/decorator/AbstractDecorator.js +0 -49
- package/lib/pattern/decorator/DecoratorChain.js +0 -285
- package/lib/util/DeviceDetector.js +0 -153
- package/lib/yaml/YAML.js +0 -46
- package/patterns.conf +0 -6
- package/tests/cache/CacheLoaderSpec.js +0 -7
- package/tests/class/ClassSpec.js +0 -106
- package/tests/client/MemcachedSocketSpec.js +0 -1228
- package/tests/client/MemcachedSpec.js +0 -77
- package/tests/client/MySQLPoolSpec.js +0 -231
- package/tests/client/PGPoolSpec.js +0 -479
- package/tests/client/RedisSpec.js +0 -471
- package/tests/client/S3ClientSpec.js +0 -26
- package/tests/client/S3Spec.js +0 -129
- package/tests/client/rabbitmq/RbmqConnectionSpec.js +0 -71
- package/tests/common/AssertionsSpec.js +0 -278
- package/tests/common/NetSpec.js +0 -6
- package/tests/common/RandomSpec.js +0 -35
- package/tests/common/TypesSpec.js +0 -7
- package/tests/credentials/CredentialsProviderSpec.js +0 -46
- package/tests/crypto/CryptoSpec.js +0 -33
- package/tests/data/BinaryDataSpec.js +0 -50
- package/tests/data/CompressorSpec.js +0 -7
- package/tests/data/FormDataSpec.js +0 -7
- package/tests/data/MimeSpec.js +0 -7
- package/tests/event/ErrorEventSpec.js +0 -20
- package/tests/event/EventDispatcherSpec.js +0 -319
- package/tests/event/EventSpec.js +0 -17
- package/tests/http/ConnectionPoolSpec.js +0 -7
- package/tests/http/HeadersSpec.js +0 -79
- package/tests/http/LoaderSpec.js +0 -43
- package/tests/http/MessageSpec.js +0 -251
- package/tests/http/RequestProcessorSpec.js +0 -124
- package/tests/http/RequestSpec.js +0 -651
- package/tests/http/ResponseSpec.js +0 -491
- package/tests/http/ServerSpec.js +0 -7
- package/tests/http/SocketSpec.js +0 -7
- package/tests/http/UrlSpec.js +0 -14
- package/tests/jsonrpc/JsonRpcAbstractSpec.js +0 -20
- package/tests/jsonrpc/JsonRpcBatchRequestSpec.js +0 -31
- package/tests/jsonrpc/JsonRpcBatchResponseSpec.js +0 -38
- package/tests/jsonrpc/JsonRpcErrorSpec.js +0 -58
- package/tests/jsonrpc/JsonRpcMethodSpec.js +0 -7
- package/tests/jsonrpc/JsonRpcRequestProcessorSpec.js +0 -271
- package/tests/jsonrpc/JsonRpcRequestSpec.js +0 -70
- package/tests/jsonrpc/JsonRpcResponseSpec.js +0 -63
- package/tests/jsonrpc/JsonRpcServerSpec.js +0 -42
- package/tests/pattern/PoolSpec.js +0 -180
- package/tests/pattern/decorator/AbstractDecoratorSpec.js +0 -7
- package/tests/pattern/decorator/DecoratorChainSpec.js +0 -7
- package/tests/yaml/YAMLSpec.js +0 -132
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
const cloneDeep = require('lodash/cloneDeep');
|
|
2
|
+
const pickBy = require('lodash/pickBy');
|
|
3
|
+
const get = require('lodash/get');
|
|
4
|
+
const pick = require('lodash/pick');
|
|
5
|
+
const uniq = require('lodash/uniq');
|
|
6
|
+
const { isValid, toAddress } = require('@arcblock/did');
|
|
7
|
+
const { PASSPORT_STATUS, USER_MAX_INVITE_DEPTH } = require('@abtnode/constant');
|
|
8
|
+
const { BaseState } = require('@ohos-ports/models');
|
|
9
|
+
const { Sequelize, Op } = require('sequelize');
|
|
10
|
+
const { updateConnectedAccount } = require('@abtnode/util/lib/user');
|
|
11
|
+
const { LOGIN_PROVIDER } = require('@blocklet/constant');
|
|
12
|
+
const logger = require('@abtnode/logger')('@abtnode/core:states:user');
|
|
13
|
+
|
|
14
|
+
const { validateOwner } = require('../util');
|
|
15
|
+
const { loginSchema, disconnectAccountSchema } = require('../validators/user');
|
|
16
|
+
const ExtendBase = require('./base');
|
|
17
|
+
|
|
18
|
+
const isNullOrUndefined = (x) => x === undefined || x === null;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Auth0Account
|
|
22
|
+
* @typedef {Object} OAuthAccount
|
|
23
|
+
* @property {'auth0'|'google'|'github'|'apple'} provider
|
|
24
|
+
* @property {string} id - id from oauth
|
|
25
|
+
* @property {string} did - did for oauth account
|
|
26
|
+
* @property {string} pk - pk for oauth account
|
|
27
|
+
* @property {string} lastLoginAt - Last login time new Date().toISOString()
|
|
28
|
+
* @property {string} firstLoginAt - First login time new Date().toISOString()
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* WalletAccount
|
|
33
|
+
* @typedef {Object} WalletAccount
|
|
34
|
+
* @property {'wallet'} provider
|
|
35
|
+
* @property {string} did - did for wallet account
|
|
36
|
+
* @property {string} pk - pk for wallet account
|
|
37
|
+
* @property {string} lastLoginAt - Last login time new Date().toISOString()
|
|
38
|
+
* @property {string} firstLoginAt - First login time new Date().toISOString()
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* NFTAccount
|
|
43
|
+
* @typedef {Object} NFTAccount
|
|
44
|
+
* @property {'nft'} provider
|
|
45
|
+
* @property {string} did - did for nft account
|
|
46
|
+
* @property {string} owner - owner for nft account
|
|
47
|
+
* @property {string} lastLoginAt - Last login time new Date().toISOString()
|
|
48
|
+
* @property {string} firstLoginAt - First login time new Date().toISOString()
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* ConnectedAccount
|
|
53
|
+
* @typedef {(OAuthAccount|WalletAccount|NFTAccount)} ConnectedAccount
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @extends ExtendBase<import('@ohos-ports/models').UserState>
|
|
58
|
+
*/
|
|
59
|
+
class User extends ExtendBase {
|
|
60
|
+
constructor(model, config, models) {
|
|
61
|
+
super(model, config);
|
|
62
|
+
|
|
63
|
+
this.models = models;
|
|
64
|
+
this.passport = new BaseState(models.Passport, config);
|
|
65
|
+
this.connectedAccount = new BaseState(models.ConnectedAccount, config);
|
|
66
|
+
this.userSession = new BaseState(models.UserSession, config);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// FIXME: @wangshijun wrap these in a transaction
|
|
70
|
+
async addUser(user) {
|
|
71
|
+
if (!validateOwner(user)) {
|
|
72
|
+
throw new Error('user is invalid');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const newUser = {
|
|
76
|
+
...user,
|
|
77
|
+
...(await this._extractInviteInfo(user)),
|
|
78
|
+
sourceProvider: user.sourceProvider || LOGIN_PROVIDER.WALLET,
|
|
79
|
+
approved: !!user.approved,
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// create user
|
|
83
|
+
await this.insert(this._normalizeUser(newUser));
|
|
84
|
+
|
|
85
|
+
// create passports and connectedAccounts
|
|
86
|
+
await Promise.all((get(user, 'passports') || []).map((x) => this.passport.insert({ ...x, userDid: user.did })));
|
|
87
|
+
await Promise.all(
|
|
88
|
+
(get(user, 'connectedAccounts') || []).map((x) => {
|
|
89
|
+
// FIXME: @zhanghan 这里在修复完 https://github.com/blocklet/tweet-token/issues/131 之后需要去除特殊处理的逻辑
|
|
90
|
+
const mergeData = { ...x, userDid: user.did };
|
|
91
|
+
if (mergeData.id === null && mergeData.provider === LOGIN_PROVIDER.AUTH0) {
|
|
92
|
+
mergeData.provider = LOGIN_PROVIDER.WALLET;
|
|
93
|
+
}
|
|
94
|
+
return this.connectedAccount.insert(mergeData);
|
|
95
|
+
})
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
return this.getUser(user.did);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// FIXME: @wangshijun wrap these in a transaction
|
|
102
|
+
async updateUser(did, updates) {
|
|
103
|
+
const exist = await super.findOne({ did });
|
|
104
|
+
if (!exist) {
|
|
105
|
+
throw new Error(`user does not exist: ${did}`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Allow to update inviter only when inviter is not set
|
|
109
|
+
const pending = this._normalizeUser(cloneDeep(updates));
|
|
110
|
+
if (exist.inviter) {
|
|
111
|
+
delete pending.inviter;
|
|
112
|
+
} else {
|
|
113
|
+
Object.assign(pending, await this._extractInviteInfo({ did, ...pending }));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
await super.update({ did }, { $set: pending });
|
|
117
|
+
await Promise.all(
|
|
118
|
+
(get(updates, 'passports') || [])
|
|
119
|
+
.filter((x) => x.id)
|
|
120
|
+
.map((x) => this.passport.upsert({ id: x.id }, { ...x, userDid: did }))
|
|
121
|
+
);
|
|
122
|
+
await Promise.all(
|
|
123
|
+
(get(updates, 'connectedAccounts') || [])
|
|
124
|
+
.filter((x) => x.did)
|
|
125
|
+
.map((x) => {
|
|
126
|
+
// FIXME: @zhanghan 这里在修复完 https://github.com/blocklet/tweet-token/issues/131 之后需要去除特殊处理的逻辑
|
|
127
|
+
const mergeData = { ...x, userDid: did };
|
|
128
|
+
if (mergeData.id === null && mergeData.provider === LOGIN_PROVIDER.AUTH0) {
|
|
129
|
+
mergeData.provider = LOGIN_PROVIDER.WALLET;
|
|
130
|
+
}
|
|
131
|
+
return this.connectedAccount.upsert({ did: x.did }, mergeData);
|
|
132
|
+
})
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
return this.getUser(did);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
revokePassportById({ did, id }) {
|
|
139
|
+
return this._setPassportStatusById({ did, id, status: PASSPORT_STATUS.REVOKED });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
enablePassportById({ did, id }) {
|
|
143
|
+
return this._setPassportStatusById({ did, id, status: PASSPORT_STATUS.VALID });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async removePassportById({ id }) {
|
|
147
|
+
const num = await this.passport.remove({ id });
|
|
148
|
+
if (num === 0) {
|
|
149
|
+
throw new Error(`passport does not exist: ${id}`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return num;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* remove a user by user's did
|
|
157
|
+
* @param {object} params
|
|
158
|
+
* @param {string} params.did - the did of user
|
|
159
|
+
*/
|
|
160
|
+
async remove({ did }) {
|
|
161
|
+
if (process.env.NODE_ENV !== 'test') {
|
|
162
|
+
await Promise.all([
|
|
163
|
+
this.passport.remove({ userDid: did }),
|
|
164
|
+
this.connectedAccount.remove({ userDid: did }),
|
|
165
|
+
this.userSession.remove({ userDid: did }),
|
|
166
|
+
]);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const num = await super.remove({ did });
|
|
170
|
+
if (num === 0) {
|
|
171
|
+
throw new Error(`user does not exist: ${did}`);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return num;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* enable/disable user login
|
|
179
|
+
* @param {object} params
|
|
180
|
+
* @param {string} params.did user's did
|
|
181
|
+
* @param {boolean} params.approved enable/disable user login
|
|
182
|
+
*/
|
|
183
|
+
async updateApproved({ did, approved }) {
|
|
184
|
+
const [num, [doc]] = await super.update({ did }, { $set: { approved } });
|
|
185
|
+
if (num === 0) {
|
|
186
|
+
throw new Error(`user does not exist: ${did}`);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return doc;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* update user's role
|
|
194
|
+
* @param {object} params
|
|
195
|
+
* @param {string} params.did user's did
|
|
196
|
+
* @param {string} params.role user's role
|
|
197
|
+
*/
|
|
198
|
+
async updateRole({ did, role }) {
|
|
199
|
+
const [num, [doc]] = await super.update({ did }, { $set: { role } });
|
|
200
|
+
if (num === 0) {
|
|
201
|
+
throw new Error(`user does not exist: ${did}`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return doc;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Get blocklet service user list
|
|
209
|
+
*/
|
|
210
|
+
async getUsers({ query, sort, paging } = {}) {
|
|
211
|
+
const where = {};
|
|
212
|
+
const replacements = {};
|
|
213
|
+
|
|
214
|
+
const {
|
|
215
|
+
approved,
|
|
216
|
+
role,
|
|
217
|
+
search,
|
|
218
|
+
tags,
|
|
219
|
+
invitee,
|
|
220
|
+
inviter,
|
|
221
|
+
generation, // 0 - unlimited, 1 - invited by inviter, 2 - invited by another
|
|
222
|
+
includeTags,
|
|
223
|
+
includePassports,
|
|
224
|
+
includeUserSessions,
|
|
225
|
+
} = query || {};
|
|
226
|
+
const shouldIncludeTag = (tags && tags.length) || includeTags;
|
|
227
|
+
|
|
228
|
+
if (isNullOrUndefined(approved) === false) {
|
|
229
|
+
where.approved = approved;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const sorting = pickBy(sort, (x) => !isNullOrUndefined(x));
|
|
233
|
+
if (!Object.keys(sorting).length) {
|
|
234
|
+
sorting.createdAt = -1;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (search) {
|
|
238
|
+
if (search.length > 50) {
|
|
239
|
+
throw new Error('the length of search text should not more than 50');
|
|
240
|
+
}
|
|
241
|
+
if (isValid(search)) {
|
|
242
|
+
where.did = toAddress(search);
|
|
243
|
+
} else {
|
|
244
|
+
where[Op.or] = [{ fullName: { [Op.like]: `%${search}%` } }, { email: { [Op.like]: `%${search}%` } }];
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (inviter && invitee) {
|
|
249
|
+
throw new Error('You can not query by inviter and invitee at the same time');
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
let total = 0;
|
|
253
|
+
if (!where.did) {
|
|
254
|
+
// handle descendant query
|
|
255
|
+
if (inviter) {
|
|
256
|
+
if (isValid(inviter) === false) {
|
|
257
|
+
throw new Error('inviter did invalid');
|
|
258
|
+
}
|
|
259
|
+
const exist = await this.model.findByPk(toAddress(inviter), { attributes: ['did', 'generation'] });
|
|
260
|
+
if (!exist) {
|
|
261
|
+
throw new Error(`inviter not found: ${inviter}`);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
try {
|
|
265
|
+
const { pageSize: size = 20, page = 1 } = paging || {};
|
|
266
|
+
const pageSize = Math.min(100, size);
|
|
267
|
+
const offset = (page - 1) * pageSize;
|
|
268
|
+
// LIMIT ${pageSize} OFFSET ${offset}
|
|
269
|
+
const subQuery = `
|
|
270
|
+
WITH RECURSIVE UserTree(did,inviter,generation,createdAt) AS (
|
|
271
|
+
SELECT did,inviter,generation,createdAt FROM users WHERE inviter="${exist.did}"
|
|
272
|
+
UNION ALL
|
|
273
|
+
SELECT child.did,child.inviter,child.generation,child.createdAt FROM users AS child INNER JOIN UserTree AS parent ON (child.inviter=parent.did) ORDER BY child.createdAt DESC
|
|
274
|
+
)
|
|
275
|
+
SELECT did,inviter,generation FROM UserTree ${generation > 0 ? `WHERE generation=${(exist.generation > 0 ? exist.generation : 0) + generation}` : ''}`.trim();
|
|
276
|
+
const children = await this.query(subQuery);
|
|
277
|
+
total = children.length;
|
|
278
|
+
where.did = children.slice(offset, offset + pageSize).map((x) => x.did);
|
|
279
|
+
} catch (err) {
|
|
280
|
+
console.error('Failed to get descendants', err);
|
|
281
|
+
where.did = [];
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// handle ancestor query
|
|
286
|
+
if (invitee) {
|
|
287
|
+
if (isValid(invitee) === false) {
|
|
288
|
+
throw new Error('invitee did invalid');
|
|
289
|
+
}
|
|
290
|
+
const exist = await this.model.findByPk(toAddress(invitee), { attributes: ['did', 'generation'] });
|
|
291
|
+
if (!exist) {
|
|
292
|
+
throw new Error(`invitee not found: ${invitee}`);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
try {
|
|
296
|
+
const subQuery = `
|
|
297
|
+
WITH RECURSIVE UserTree(did,inviter,generation) AS (
|
|
298
|
+
SELECT did,inviter,generation FROM users WHERE did="${exist.did}"
|
|
299
|
+
UNION ALL
|
|
300
|
+
SELECT
|
|
301
|
+
inviter,
|
|
302
|
+
(SELECT inviter FROM users AS parent WHERE parent.did=child.inviter),
|
|
303
|
+
(SELECT generation FROM users AS parent WHERE parent.did=child.inviter)
|
|
304
|
+
FROM UserTree AS child
|
|
305
|
+
WHERE inviter IS NOT NULL
|
|
306
|
+
)
|
|
307
|
+
SELECT did,inviter,generation FROM UserTree`.trim();
|
|
308
|
+
const children = await this.query(subQuery);
|
|
309
|
+
where.did = children.map((x) => x.did).filter((x) => x !== exist.did);
|
|
310
|
+
} catch (err) {
|
|
311
|
+
console.error('Failed to get ancestors', err);
|
|
312
|
+
where.did = [];
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// handle role/status query
|
|
317
|
+
if (role && role !== '$all') {
|
|
318
|
+
replacements.status = PASSPORT_STATUS.VALID;
|
|
319
|
+
if (role === '$none') {
|
|
320
|
+
where.did = {
|
|
321
|
+
[Op.notIn]: Sequelize.literal('(SELECT DISTINCT userDid FROM passports WHERE status = :status)'),
|
|
322
|
+
};
|
|
323
|
+
} else if (role === '$blocked') {
|
|
324
|
+
where.approved = false;
|
|
325
|
+
} else {
|
|
326
|
+
replacements.role = role;
|
|
327
|
+
where.did = {
|
|
328
|
+
[Op.in]: Sequelize.literal(
|
|
329
|
+
'(SELECT DISTINCT userDid FROM passports WHERE name = :role AND status = :status)'
|
|
330
|
+
),
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const include = [];
|
|
337
|
+
if (shouldIncludeTag) {
|
|
338
|
+
include.push(this.getTagInclude(tags));
|
|
339
|
+
}
|
|
340
|
+
if (includePassports) {
|
|
341
|
+
include.push({
|
|
342
|
+
model: this.models.Passport,
|
|
343
|
+
as: 'passports',
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
if (includeUserSessions) {
|
|
347
|
+
include.push({
|
|
348
|
+
model: this.models.UserSession,
|
|
349
|
+
as: 'userSessions',
|
|
350
|
+
where: {
|
|
351
|
+
status: 'online',
|
|
352
|
+
},
|
|
353
|
+
required: false,
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const result = await this.paginate({ where, include, replacements }, sorting, paging);
|
|
358
|
+
return { list: result.list, paging: { ...result.paging, total: total || result.paging.total } };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// eslint-disable-next-line require-await
|
|
362
|
+
async getUsersByDids({ dids, query }) {
|
|
363
|
+
const { approved, includeTags, includePassports, includeUserSessions } = query || {};
|
|
364
|
+
const condition = { did: dids };
|
|
365
|
+
if (isNullOrUndefined(approved) === false) {
|
|
366
|
+
condition.approved = !!approved;
|
|
367
|
+
}
|
|
368
|
+
const include = [];
|
|
369
|
+
if (includeTags) {
|
|
370
|
+
include.push(this.getTagInclude());
|
|
371
|
+
}
|
|
372
|
+
if (includePassports) {
|
|
373
|
+
include.push({
|
|
374
|
+
model: this.models.Passport,
|
|
375
|
+
as: 'passports',
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
if (includeUserSessions) {
|
|
379
|
+
include.push({
|
|
380
|
+
model: this.models.UserSession,
|
|
381
|
+
as: 'userSessions',
|
|
382
|
+
where: {
|
|
383
|
+
status: 'online',
|
|
384
|
+
},
|
|
385
|
+
required: false,
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
return this.find({ where: condition, include });
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// eslint-disable-next-line require-await
|
|
393
|
+
async countByPassport({ name, status = PASSPORT_STATUS.VALID }) {
|
|
394
|
+
if (name === '$none') {
|
|
395
|
+
return this.count({
|
|
396
|
+
where: {
|
|
397
|
+
did: {
|
|
398
|
+
[Op.notIn]: Sequelize.literal('(SELECT DISTINCT userDid FROM passports WHERE status = :status)'),
|
|
399
|
+
},
|
|
400
|
+
},
|
|
401
|
+
replacements: { status: PASSPORT_STATUS.VALID },
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
if (name === '$all') {
|
|
406
|
+
return this.count({});
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (name === '$blocked') {
|
|
410
|
+
return this.count({ approved: false });
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
return this.count({
|
|
414
|
+
distinct: true,
|
|
415
|
+
col: 'did',
|
|
416
|
+
where: {
|
|
417
|
+
did: {
|
|
418
|
+
[Op.in]: Sequelize.literal(
|
|
419
|
+
'(SELECT DISTINCT userDid FROM passports WHERE name = :name AND status = :status)'
|
|
420
|
+
),
|
|
421
|
+
},
|
|
422
|
+
},
|
|
423
|
+
replacements: { name, status },
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* get user by did
|
|
429
|
+
* @param {string} did user's did
|
|
430
|
+
*/
|
|
431
|
+
async getUser(did, { enableConnectedAccount = false, includeTags = false } = {}) {
|
|
432
|
+
let user = await this.findOne({ where: { did }, include: includeTags ? [this.getTagInclude()] : [] });
|
|
433
|
+
let connectedAccounts = [];
|
|
434
|
+
let passports = [];
|
|
435
|
+
|
|
436
|
+
// search in connected accounts
|
|
437
|
+
if (!user && enableConnectedAccount) {
|
|
438
|
+
const connectedAccount = await this.connectedAccount.findOne({ did });
|
|
439
|
+
if (connectedAccount) {
|
|
440
|
+
user = await this.findOne({ did: connectedAccount.userDid });
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (user) {
|
|
445
|
+
[connectedAccounts, passports] = await Promise.all([
|
|
446
|
+
this.connectedAccount.find({ userDid: user.did }),
|
|
447
|
+
this.passport.find({ userDid: user.did }),
|
|
448
|
+
]);
|
|
449
|
+
|
|
450
|
+
user.connectedAccounts = connectedAccounts;
|
|
451
|
+
user.passports = passports;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
return user;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* @param {object} params
|
|
459
|
+
* @param {string} params.did user did
|
|
460
|
+
* @param {string} params.id passport id
|
|
461
|
+
* @param {string} params.status passport status
|
|
462
|
+
*/
|
|
463
|
+
async _setPassportStatusById({ did, id, status }) {
|
|
464
|
+
const exist = this.passport.count({ id });
|
|
465
|
+
if (!exist) {
|
|
466
|
+
throw new Error(`cannot find passport by id ${id}`);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const [num] = await this.passport.update({ id }, { $set: { status } });
|
|
470
|
+
if (num === 0) {
|
|
471
|
+
throw new Error('user passport does not exist');
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
return this.getUser(did);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* 用户登录
|
|
479
|
+
* @param {Object} user
|
|
480
|
+
* @param {string} user.did
|
|
481
|
+
* @param {string} user.pk
|
|
482
|
+
* @param {ConnectedAccount} user.connectedAccount
|
|
483
|
+
* @param {string} user.fullName - user profile's name
|
|
484
|
+
* @param {string} user.avatar - url of user's avatar, eg: bn://avatar/7f8848569405f8cdf8b1b2788ebf7d0f.jpg
|
|
485
|
+
* @param {string} user.locale - locale
|
|
486
|
+
* @param {string} user.inviter - inviter
|
|
487
|
+
* @param {Object} [user.extra] - extra data of user
|
|
488
|
+
* @param {string} user.lastLoginIp - lastLoginIp
|
|
489
|
+
* @param {('owner'|'admin'|'member'|'guest'|string)} user.role - deprecated user's role
|
|
490
|
+
*/
|
|
491
|
+
async loginUser(raw) {
|
|
492
|
+
const { error, value: user } = loginSchema.validate(raw);
|
|
493
|
+
if (error) {
|
|
494
|
+
console.error(error);
|
|
495
|
+
throw new Error(error.message);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
let updated;
|
|
499
|
+
|
|
500
|
+
const now = new Date().toISOString();
|
|
501
|
+
const exist = await this.getUser(user.did, { enableConnectedAccount: true });
|
|
502
|
+
|
|
503
|
+
const updates = {
|
|
504
|
+
...pick(user, [
|
|
505
|
+
'fullName',
|
|
506
|
+
'email',
|
|
507
|
+
'phone',
|
|
508
|
+
'avatar',
|
|
509
|
+
'url',
|
|
510
|
+
'role',
|
|
511
|
+
'locale',
|
|
512
|
+
'extra',
|
|
513
|
+
'lastLoginIp',
|
|
514
|
+
'remark',
|
|
515
|
+
'inviter',
|
|
516
|
+
'generation',
|
|
517
|
+
'emailVerified',
|
|
518
|
+
'phoneVerified',
|
|
519
|
+
'sourceAppPid',
|
|
520
|
+
]),
|
|
521
|
+
lastLoginAt: now,
|
|
522
|
+
passports: user.passport ? [{ ...user.passport, lastLoginAt: now }] : [],
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
// HACK: joi 会把 null 值过滤掉,暂时手动判断 null 值
|
|
526
|
+
if (raw.sourceAppPid === null) {
|
|
527
|
+
updates.sourceAppPid = null;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
Object.assign(updates, await this._extractInviteInfo(raw));
|
|
531
|
+
|
|
532
|
+
if (exist) {
|
|
533
|
+
// immutable fields
|
|
534
|
+
delete updates.locale;
|
|
535
|
+
// NOTICE: 开放允许修改 sourceAppPid 字段,来进行旧数据的修正
|
|
536
|
+
// delete updates.sourceAppPid;
|
|
537
|
+
delete updates.inviter;
|
|
538
|
+
delete updates.generation;
|
|
539
|
+
|
|
540
|
+
// update user, connectedAccount, passport
|
|
541
|
+
updates.connectedAccounts = updateConnectedAccount(exist.connectedAccounts, user.connectedAccount);
|
|
542
|
+
updated = await this.updateUser(exist.did, updates);
|
|
543
|
+
} else {
|
|
544
|
+
// create user, connectedAccount, passport
|
|
545
|
+
updates.did = user.did;
|
|
546
|
+
updates.pk = user.pk;
|
|
547
|
+
updates.firstLoginAt = now;
|
|
548
|
+
updates.approved = true;
|
|
549
|
+
updates.connectedAccounts = updateConnectedAccount([], user.connectedAccount);
|
|
550
|
+
updates.sourceProvider = updates.connectedAccounts[0].provider;
|
|
551
|
+
updated = await this.addUser(updates);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
return { ...updated, _action: exist ? 'update' : 'add' };
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
async _extractInviteInfo(raw) {
|
|
558
|
+
const info = {};
|
|
559
|
+
|
|
560
|
+
if (raw.inviter) {
|
|
561
|
+
// sybil-attack
|
|
562
|
+
if (isValid(raw.inviter)) {
|
|
563
|
+
const inviterId = toAddress(raw.inviter);
|
|
564
|
+
const inviter = await this.model.findByPk(inviterId, { attributes: ['did', 'generation'] });
|
|
565
|
+
if (inviter) {
|
|
566
|
+
// circle preventing
|
|
567
|
+
const { list: ancestors } = await this.getUsers({ query: { invitee: inviterId } });
|
|
568
|
+
const hasCircle = ancestors.some((x) => x.did === raw.did);
|
|
569
|
+
if (hasCircle) {
|
|
570
|
+
logger.warn('Set inviter result in cycle is not allowed', raw);
|
|
571
|
+
info.inviter = null;
|
|
572
|
+
} else {
|
|
573
|
+
info.inviter = inviterId;
|
|
574
|
+
info.generation = inviter.generation + 1;
|
|
575
|
+
}
|
|
576
|
+
} else {
|
|
577
|
+
logger.warn('Set inviter to non-exist user is not allowed', raw);
|
|
578
|
+
}
|
|
579
|
+
} else {
|
|
580
|
+
logger.warn('Set inviter to invalid did is not allowed', raw);
|
|
581
|
+
info.inviter = null;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// anti-land-attack
|
|
585
|
+
if (info.inviter === raw.did) {
|
|
586
|
+
logger.warn('Set inviter to self is not allowed', raw);
|
|
587
|
+
info.inviter = null;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
if (!info.inviter) {
|
|
591
|
+
info.generation = 0;
|
|
592
|
+
}
|
|
593
|
+
if (info.generation > USER_MAX_INVITE_DEPTH) {
|
|
594
|
+
throw new Error('You have exceeded max user invite chain length');
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
return info;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
async disconnectUserAccount(raw) {
|
|
601
|
+
const { error, value: connectedAccount } = disconnectAccountSchema.validate(raw);
|
|
602
|
+
if (error) {
|
|
603
|
+
throw new Error(error);
|
|
604
|
+
}
|
|
605
|
+
const result = await this.connectedAccount.remove(connectedAccount);
|
|
606
|
+
return result;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// eslint-disable-next-line require-await
|
|
610
|
+
async getUserByDid(did) {
|
|
611
|
+
return this.findOne(
|
|
612
|
+
{ did },
|
|
613
|
+
{
|
|
614
|
+
did: 1,
|
|
615
|
+
pk: 1,
|
|
616
|
+
fullName: 1,
|
|
617
|
+
email: 1,
|
|
618
|
+
role: 1,
|
|
619
|
+
approved: 1,
|
|
620
|
+
inviter: 1,
|
|
621
|
+
generation: 1,
|
|
622
|
+
emailVerified: 1,
|
|
623
|
+
phoneVerified: 1,
|
|
624
|
+
}
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
async isUserValid(did) {
|
|
629
|
+
const count = await super.count({ did, approved: true });
|
|
630
|
+
return count > 0;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
async isConnectedAccount(did) {
|
|
634
|
+
const count = await this.connectedAccount.count({ did });
|
|
635
|
+
return count > 0;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
async isPassportValid(passportId) {
|
|
639
|
+
const count = await this.passport.count({ id: passportId, status: PASSPORT_STATUS.VALID });
|
|
640
|
+
return count > 0;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
async updateTags(did, tags) {
|
|
644
|
+
const user = await this.getUserByDid(did);
|
|
645
|
+
if (user) {
|
|
646
|
+
const instance = this.build(user);
|
|
647
|
+
await instance.setTags(uniq(tags));
|
|
648
|
+
return this.getUser(did, { includeTags: true });
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
return null;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
getTagInclude(tags = []) {
|
|
655
|
+
const result = {
|
|
656
|
+
model: this.models.Tag,
|
|
657
|
+
as: 'tags',
|
|
658
|
+
through: {
|
|
659
|
+
attributes: [],
|
|
660
|
+
},
|
|
661
|
+
};
|
|
662
|
+
|
|
663
|
+
if (tags.length) {
|
|
664
|
+
result.where = { id: { [Op.in]: tags.filter(Boolean) } };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
return result;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
async getPassports(did) {
|
|
671
|
+
const passports = await this.passport.find({ userDid: did });
|
|
672
|
+
return passports;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
async getPassportById(passportId) {
|
|
676
|
+
const passport = await this.passport.findOne({ id: passportId });
|
|
677
|
+
return passport;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
async isEmailUsed(email, verified = false, sourceProvider = '') {
|
|
681
|
+
const condition = this._normalizeUser({ email });
|
|
682
|
+
if (verified) {
|
|
683
|
+
condition.emailVerified = true;
|
|
684
|
+
}
|
|
685
|
+
if (Object.values(LOGIN_PROVIDER).includes(sourceProvider)) {
|
|
686
|
+
condition.sourceProvider = sourceProvider;
|
|
687
|
+
}
|
|
688
|
+
const doc = await this.findOne(condition);
|
|
689
|
+
return email && !!doc;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
async isPhoneUsed(phone, verified = false) {
|
|
693
|
+
const condition = this._normalizeUser({ phone });
|
|
694
|
+
if (verified) {
|
|
695
|
+
condition.phoneVerified = true;
|
|
696
|
+
}
|
|
697
|
+
const doc = await this.findOne(condition);
|
|
698
|
+
return phone && !!doc;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
async isSubjectIssued(userDid, subject, status = PASSPORT_STATUS.VALID) {
|
|
702
|
+
const passport = await this.passport.findOne({ userDid, name: String(subject).trim().toLowerCase(), status });
|
|
703
|
+
return !!passport;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
_normalizeUser(user) {
|
|
707
|
+
if (user.email) {
|
|
708
|
+
user.email = String(user.email).trim().toLowerCase();
|
|
709
|
+
}
|
|
710
|
+
if (user.phone) {
|
|
711
|
+
user.phone = String(user.phone).trim().toLowerCase().replace(/\s+/g, '').replace(/[()-]/g, '');
|
|
712
|
+
}
|
|
713
|
+
return user;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
module.exports = User;
|