Compare commits

...
10 Commits
Author SHA1 Message Date
Radmehr e32995c70f feat: add trust proxy 2026-11-28 16:50:42 +03:30
Radmehr 9c7f1340b6 tmp: add logging to npm ci 2026-11-28 15:45:58 +03:30
Radmehr 155cb09c22 fix: fix create-admin:prod 2026-11-25 13:57:04 +03:30
Radmehr 8bc3c24a7a fix: fix datasource 2026-11-25 12:54:09 +03:30
Radmehr 5238dd872c feat: change admin panel content 2026-11-25 11:42:29 +03:30
Radmehr 4086209241 fix: fix create admin command 2026-11-25 11:17:00 +03:30
Radmehr 7611033c44 feat: add create admin script 2026-11-22 15:08:23 +03:30
Radmehr 302d06b44f feat: add reset password 2026-11-22 09:25:21 +03:30
Radmehr 88b4a99908 feat: add get chatbot conversation by id endpoint 2026-11-14 23:58:34 +03:30
Radmehr d572f6b7a2 feat: add chatbot conversations endpoint 2026-11-14 23:24:10 +03:30
36 changed files with 994 additions and 55 deletions
+7 -1
View File
@@ -16,7 +16,13 @@ WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
RUN npm ci --omit=dev --verbose \
--fetch-retries=5 \
--fetch-timeout=600000 \
--maxsockets=2 \
--no-audit \
--no-fund \
|| (cat /root/.npm/_logs/*debug-0.log; exit 1)
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
+362 -23
View File
@@ -12,6 +12,7 @@
"@adminjs/express": "^5.1.0",
"@adminjs/nestjs": "^5.1.1",
"@adminjs/typeorm": "^4.0.0",
"@inquirer/prompts": "^8.8.1",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.3",
"@nestjs/core": "^11.0.1",
@@ -72,7 +73,7 @@
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"tsx": "^4.23.12",
"tsx": "^4.23.15",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
}
@@ -3378,25 +3379,23 @@
}
},
"node_modules/@inquirer/prompts": {
"version": "7.10.1",
"resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-7.10.1.tgz",
"integrity": "sha512-Dx/y9bCQcXLI5ooQ5KyvA4FTgeo2jYj/7plWfV5Ak5wDPKQZgudKez2ixyfz7tKXzcJciTxqLeK7R9HItwiByg==",
"dev": true,
"license": "MIT",
"version": "8.8.1",
"resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.8.1.tgz",
"integrity": "sha512-8zlCcD72QWvFAKnrT2TFckcgKOMXjPAaeBjp0IXXMpPLo8v41OZ8hS6MDUI5mw/Ow8NfOnSXguONheAxwdzrNw==",
"dependencies": {
"@inquirer/checkbox": "^4.3.2",
"@inquirer/confirm": "^5.1.21",
"@inquirer/editor": "^4.2.23",
"@inquirer/expand": "^4.0.23",
"@inquirer/input": "^4.3.1",
"@inquirer/number": "^3.0.23",
"@inquirer/password": "^4.0.23",
"@inquirer/rawlist": "^4.1.11",
"@inquirer/search": "^3.2.2",
"@inquirer/select": "^4.4.2"
"@inquirer/checkbox": "^5.3.1",
"@inquirer/confirm": "^6.4.1",
"@inquirer/editor": "^5.5.0",
"@inquirer/expand": "^5.2.1",
"@inquirer/input": "^5.2.1",
"@inquirer/number": "^4.3.1",
"@inquirer/password": "^5.3.1",
"@inquirer/rawlist": "^5.4.1",
"@inquirer/search": "^4.4.1",
"@inquirer/select": "^5.3.1"
},
"engines": {
"node": ">=18"
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
@@ -3407,6 +3406,299 @@
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/ansi": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.1.1.tgz",
"integrity": "sha512-WwCc5T9554vU/M3W6mztOJvZK/5RgMwQsGlSZSZpKA/H2IfsTWIPdn1WiS8+HHjhe3H0IsmQCXUlDbvGM6vvuA==",
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/checkbox": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-5.3.1.tgz",
"integrity": "sha512-AWb8O1kl/olRQt0fReEIlu8iCn8qaQ0OEIffeFsMrfhIlVSz/ud1EeeBhWnm057xhRqD+kYVD7Fk2X9Bk/oW6w==",
"dependencies": {
"@inquirer/ansi": "^2.1.1",
"@inquirer/core": "^12.1.1",
"@inquirer/figures": "^2.1.1",
"@inquirer/type": "4.3.1"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/confirm": {
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.4.1.tgz",
"integrity": "sha512-ZLvGnS/+OtditM3RxULWDI3FVl3lR8mvh1ljZ8GCK8XKyfjI6Fq+ni6/2gbbH6n3gj6tinfNbE3QPplZ/xNVtQ==",
"dependencies": {
"@inquirer/core": "^12.1.1",
"@inquirer/type": "4.3.1"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/core": {
"version": "12.1.1",
"resolved": "https://registry.npmjs.org/@inquirer/core/-/core-12.1.1.tgz",
"integrity": "sha512-JrVSjoB/+B4le+A/0GyZGv/oIK30KgGNUA0eVtEMNQLUmdpizfyXM0zglUZnwTtHLjpKGRlU/q6Iv5z2GYQw9w==",
"dependencies": {
"@inquirer/ansi": "^2.1.1",
"@inquirer/figures": "^2.1.1",
"@inquirer/type": "4.3.1",
"cli-width": "^4.1.0",
"fast-string-width": "^3.0.2",
"fast-wrap-ansi": "^0.2.0",
"mute-stream": "^3.0.0",
"signal-exit": "^4.1.0"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/editor": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-5.5.0.tgz",
"integrity": "sha512-g6wUVWLXDkW7/M+Jm82vMfPHEeZpJB2ltuSTZ/1Ovs/+h5eY65Bey91ZFoaVXaSKD0l+Sf4WCm/8km/e7oe7dg==",
"dependencies": {
"@inquirer/core": "^12.1.1",
"@inquirer/external-editor": "^3.1.1",
"@inquirer/type": "4.3.1"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/expand": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.2.1.tgz",
"integrity": "sha512-PPHYJokseQ7RQoAZ8fVh3gL7jD+lhQ6O5ikQXNTPtpxwprsoGNocJIPt+GTLJL3reTqhkJEsIsZeTTcvdNDFzg==",
"dependencies": {
"@inquirer/core": "^12.1.1",
"@inquirer/type": "4.3.1"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/external-editor": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-3.1.1.tgz",
"integrity": "sha512-XMDPBC6m7/3ZfeRrzgfz86pkyGcUAxHpsPEk2PumQ7Dfzh8EwV9VywkK1D+bFytxFHzQBTRF6O2HlhdSWwwqmA==",
"dependencies": {
"chardet": "^2.1.1",
"iconv-lite": "^0.7.2"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/figures": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.1.1.tgz",
"integrity": "sha512-63AOoKi9Wlsd1G+X5dKRg15GzN/WIEf0VghxHkcVn9JswideMlwq40qJMAO3II6JyhpDZPmi3CmVKjwOSYBAmA==",
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/input": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/@inquirer/input/-/input-5.2.1.tgz",
"integrity": "sha512-HvxWvTZ+Yn7Ad0HJ6C4ajlLWL+cEIPMPjwkcqythTxu4nxwvFSNkEpBQJbnhSW3zbEi0JQ84I93CRsCz9P/opw==",
"dependencies": {
"@inquirer/core": "^12.1.1",
"@inquirer/type": "4.3.1"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/number": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/@inquirer/number/-/number-4.3.1.tgz",
"integrity": "sha512-9ApB+70Yin5Ty0dgR9GIAj4sNAu7IHJ9na6MLXjV0q8w51aaK8oMa2HUwWdNomNOX7c7UgykZkqtcPr8TY8d+Q==",
"dependencies": {
"@inquirer/core": "^12.1.1",
"@inquirer/type": "4.3.1"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/password": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/@inquirer/password/-/password-5.3.1.tgz",
"integrity": "sha512-j9QfwKO4vJ5Y1elu9MwZMxq9zjX5GES+9lSKqa9cy4xXV5qo/eDZUpdIzsPn/rbao78PxxMUPEGkUvSoMPB2ug==",
"dependencies": {
"@inquirer/ansi": "^2.1.1",
"@inquirer/core": "^12.1.1",
"@inquirer/type": "4.3.1"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/rawlist": {
"version": "5.4.1",
"resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-5.4.1.tgz",
"integrity": "sha512-hihU5YgysNOU7TxZcLtVijYPFbXKNwBsAGjuD/TSDU5RKtN6ElEAOdO/trfc3r7G//VmIGTFoaR65HdBRYNZBA==",
"dependencies": {
"@inquirer/core": "^12.1.1",
"@inquirer/type": "4.3.1"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/search": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/@inquirer/search/-/search-4.4.1.tgz",
"integrity": "sha512-9YpLazL6mR0TU77ldZ7mm7sCQpYE/aopXB1RLX7Zt5nSU27l40PQc2H317L+OudSe0xyr8N5WJl23bjnzNWuUw==",
"dependencies": {
"@inquirer/core": "^12.1.1",
"@inquirer/figures": "^2.1.1",
"@inquirer/type": "4.3.1"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/select": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.3.1.tgz",
"integrity": "sha512-V5LBhmayDvTJwcY0ADCyikptINrzSr+SIsoflkWovVTJ3qETyVhyX96hfFgy80jK8YaUe/wjTb9to3oPaw5VyQ==",
"dependencies": {
"@inquirer/ansi": "^2.1.1",
"@inquirer/core": "^12.1.1",
"@inquirer/figures": "^2.1.1",
"@inquirer/type": "4.3.1"
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/@inquirer/type": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.3.1.tgz",
"integrity": "sha512-WzfM7UPG5F8fhKPey5pTkAZQrGcGjOHbm6YLotuDdiuAkXEHiHSZh59yNeZs4RyrMHcZEZrl+GOcuLzzfLKJqg==",
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@inquirer/prompts/node_modules/mute-stream": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz",
"integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==",
"engines": {
"node": "^20.17.0 || >=22.9.0"
}
},
"node_modules/@inquirer/rawlist": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-4.1.11.tgz",
@@ -4189,6 +4481,35 @@
}
}
},
"node_modules/@nestjs/cli/node_modules/@inquirer/prompts": {
"version": "7.10.1",
"resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-7.10.1.tgz",
"integrity": "sha512-Dx/y9bCQcXLI5ooQ5KyvA4FTgeo2jYj/7plWfV5Ak5wDPKQZgudKez2ixyfz7tKXzcJciTxqLeK7R9HItwiByg==",
"dev": true,
"dependencies": {
"@inquirer/checkbox": "^4.3.2",
"@inquirer/confirm": "^5.1.21",
"@inquirer/editor": "^4.2.23",
"@inquirer/expand": "^4.0.23",
"@inquirer/input": "^4.3.1",
"@inquirer/number": "^3.0.23",
"@inquirer/password": "^4.0.23",
"@inquirer/rawlist": "^4.1.11",
"@inquirer/search": "^3.2.2",
"@inquirer/select": "^4.4.2"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/@nestjs/cli/node_modules/ajv": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
@@ -7585,7 +7906,6 @@
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/chardet/-/chardet-2.2.0.tgz",
"integrity": "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==",
"dev": true,
"license": "MIT"
},
"node_modules/chokidar": {
@@ -7703,7 +8023,6 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz",
"integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">= 12"
@@ -9013,6 +9332,19 @@
"integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
"license": "MIT"
},
"node_modules/fast-string-truncated-width": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz",
"integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g=="
},
"node_modules/fast-string-width": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz",
"integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==",
"dependencies": {
"fast-string-truncated-width": "^3.0.2"
}
},
"node_modules/fast-uri": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
@@ -9030,6 +9362,14 @@
],
"license": "BSD-3-Clause"
},
"node_modules/fast-wrap-ansi": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz",
"integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==",
"dependencies": {
"fast-string-width": "^3.0.2"
}
},
"node_modules/fb-watchman": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz",
@@ -15073,11 +15413,10 @@
"license": "0BSD"
},
"node_modules/tsx": {
"version": "4.23.12",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.12.tgz",
"integrity": "sha512-FDf4L4sYzKtzWYhU/Xm0AQFdTjdIxNo9ElTf2mxXM6k8YMHXzYUe4yODVaXP4V9uMFbVg8c0qyBccK2OOxb45Q==",
"version": "4.23.15",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz",
"integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.28.0"
},
+5 -2
View File
@@ -27,12 +27,15 @@
"migration:revert:dev": "npm run typeorm:dev -- migration:revert",
"migration:revert:prod": "npm run typeorm:prod -- migration:revert",
"seed": "cross-env NODE_ENV=development tsx src/database/seeds/seed.ts",
"seed:prod": "cross-env NODE_ENV=production node dist/database/seeds/seed.js"
"seed:prod": "cross-env NODE_ENV=production node dist/database/seeds/seed.js",
"create-admin:dev": "npm run build && cross-env NODE_ENV=development node dist/cli/create-admin.js",
"create-admin:prod": "cross-env NODE_ENV=production node dist/cli/create-admin.js"
},
"dependencies": {
"@adminjs/express": "^5.1.0",
"@adminjs/nestjs": "^5.1.1",
"@adminjs/typeorm": "^4.0.0",
"@inquirer/prompts": "^8.8.1",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.3",
"@nestjs/core": "^11.0.1",
@@ -93,7 +96,7 @@
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"tsx": "^4.23.12",
"tsx": "^4.23.15",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
+2
View File
@@ -77,6 +77,8 @@ const ENV = process.env.NODE_ENV;
database: configService.get('database.name'),
autoLoadEntities: configService.get<boolean>('database.autoLoad'),
synchronize: false,
migrationsRun: false,
migrationsTableName: 'migrations',
}),
}),
+92
View File
@@ -0,0 +1,92 @@
import { NestFactory } from '@nestjs/core';
import { UsersService } from '@/modules/users/providers/users.service';
import { Role } from '@/common/enums/roles.enum';
import { password, input, select } from '@inquirer/prompts';
import { AppModule } from '@/app.module';
import { ConfigService } from '@nestjs/config';
import { CreatePrivilegedUserDTO } from '@/modules/users/dtos/create-privileged-user.dto';
import { plainToInstance } from 'class-transformer';
import { validateOrReject } from 'class-validator';
async function bootstrap() {
const app = await NestFactory.createApplicationContext(AppModule);
try {
const configService = app.get(ConfigService);
if (!configService.get<boolean>('app.enablePrivilegedUserCli')) {
throw new Error('Privileged user creation is disabled.');
}
const usersService = app.get(UsersService);
const phone = await input({
message: 'Enter phone:',
});
const firstName = await input({
message: 'Enter First Name:',
});
const lastName = await input({
message: 'Enter Last Name:',
});
const role = await select({
message: 'Select role:',
choices: [
{ name: 'Admin', value: Role.ADMIN },
{ name: 'Superuser', value: Role.SUPERUSER },
],
});
const userPassword = await password({
message: 'Enter Password:',
mask: '*',
});
const userConfirmPassword = await password({
message: 'Enter Password Confirmation:',
mask: '*',
});
if (userPassword !== userConfirmPassword) {
throw new Error('Passwords should match!');
}
const confirmation = await input({
message: `Type "${role}" to confirm:`,
});
if ((confirmation as Role) !== role) {
throw new Error('Confirmation failed.');
}
const rawData: CreatePrivilegedUserDTO = {
phone,
firstName,
lastName,
password: userPassword,
confirmPassword: userConfirmPassword,
role,
};
const dto = plainToInstance(CreatePrivilegedUserDTO, rawData);
await validateOrReject(dto, {
whitelist: true,
forbidNonWhitelisted: true,
});
const user = await usersService.createPrivilegedUser(dto);
console.log(`Successfully created ${role}: ${user.phone}`);
} catch (error) {
console.error('Error:', error);
process.exitCode = 1;
} finally {
await app.close();
}
}
bootstrap();
+2
View File
@@ -10,4 +10,6 @@ export default registerAs('app', () => ({
origin.trim(),
),
logLevel: process.env.LOG_LEVEL,
enablePrivilegedUserCli:
process.env.ENABLE_PRIVILEGED_USER_CLI === 'true' ? true : false,
}));
+3
View File
@@ -49,4 +49,7 @@ export default Joi.object({
ADMIN_COOKIE_PASSWORD: Joi.string().allow('').default(''),
ADMIN_ROOT_PATH: Joi.string().default('/admin'),
ADMIN_SESSION_TTL_MINUTES: Joi.number().integer().min(5).default(120),
// CLI
ENABLE_PRIVILEGED_USER_CLI: Joi.boolean().default('true'),
});
+2
View File
@@ -18,6 +18,8 @@ export default new DataSource({
password: process.env.DATABASE_PASS,
database: process.env.DATABASE_NAME,
synchronize: false,
migrationsRun: false,
migrationsTableName: 'migrations',
entities: [path.join(__dirname, `../**/*.entity.${extension}`)],
migrations: [path.join(__dirname, `../migrations/*.${extension}`)],
});
+1
View File
@@ -10,6 +10,7 @@
"unauthorized": "Unauthorized access",
"tokenReuse": "Token reuse detected.",
"invalidOTP": "OTP is invalid or expired.",
"accountNotFound": "Account not found.",
"accessDenied": "Access denied. You do not have the required permissions to perform this action."
},
"messages": {
+1
View File
@@ -10,6 +10,7 @@
"unauthorized": "دسترسی غیر مجاز",
"tokenReuse": "توکن قبلا استفاده شده.",
"invalidOTP": "کد تایید اشتباه است یا منقضی شده.",
"accountNotFound": "حساب کاربری یافت نشد.",
"accessDenied": "دسترسی غیرمجاز. شما مجوزهای لازم برای انجام این عملیات را ندارید."
},
"messages": {
+3
View File
@@ -11,6 +11,9 @@ import { AdminPanelSetup } from './modules/admin-panel/admin-panel.setup';
async function bootstrap() {
const app = await NestFactory.create(AppModule, { bufferLogs: true });
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
app.getHttpAdapter().getInstance().set('trust proxy', 1);
app.useLogger(app.get(Logger));
app.setGlobalPrefix('v1');
@@ -0,0 +1,13 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class OtpPurpose1795305600000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "otp" ADD "purpose" varchar NOT NULL DEFAULT 'signup'`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "otp" DROP COLUMN "purpose"`);
}
}
+8 -2
View File
@@ -18,6 +18,7 @@ const fa = {
resetFilter: 'پاک کردن فیلترها',
confirmRemovalMany: 'حذف موارد انتخاب‌شده',
logout: 'خروج',
login: 'ورود',
},
labels: {
@@ -39,9 +40,14 @@ const fa = {
noRecordsInResource: 'هیچ موردی برای نمایش وجود ندارد.',
confirmDelete: 'آیا از حذف این مورد مطمئن هستید؟',
loginWelcome: 'برای ورود به پنل مدیریت، اطلاعات خود را وارد کنید.',
loginFailed: 'شماره موبایل یا رمز عبور اشتباه است.',
},
properties: {
email: 'شماره موبایل',
password: 'رمز عبور',
},
properties: {},
resources: {
User: {
labels: {
@@ -104,7 +110,7 @@ const fa = {
},
Test: {
labels: {
Test: 'آزمایش',
Test: 'آزمایش‌ها',
},
},
SubmissionAnswer: {
+40 -1
View File
@@ -1,4 +1,11 @@
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import {
Body,
Controller,
Header,
HttpCode,
HttpStatus,
Post,
} from '@nestjs/common';
import { LoginDTO } from './dtos/login.dto';
import { AuthService } from './providers/auth.service';
import { VerifyOtpDTO } from './dtos/verify-otp.dto';
@@ -13,6 +20,8 @@ import { LogoutDTO } from './dtos/logout.dto';
import { ActiveUser } from '@/common/decorators/active-user.decorator';
import { AccessToken } from './decorators/access-token.decorator';
import { User } from '@/modules/users/entities/user.entity';
import { ResetPasswordDTO } from './dtos/reset-password.dto';
import { ResetPasswordOtpResponseDTO } from './dtos/responses/reset-password-otp.dto';
@Controller('auth')
export class AuthController {
@@ -109,6 +118,36 @@ export class AuthController {
return await this.authService.verifyOTP(verifyOtpDto);
}
@Public()
@Post('reset-password')
@HttpCode(HttpStatus.OK)
@Header('Cache-Control', 'no-store')
@Throttle({ default: { limit: 30, ttl: 60_000 } })
@ApiAppResponse([
{
status: HttpStatus.OK,
variants: [
{ model: ResetPasswordOtpResponseDTO },
{ model: TokensResponseDTO },
],
},
{
status: HttpStatus.UNAUTHORIZED,
variants: [{ messageExample: 'کد تایید اشتباه است یا منقضی شده.' }],
},
{
status: HttpStatus.NOT_FOUND,
variants: [{ messageExample: 'حساب کاربری یافت نشد.' }],
},
{
status: HttpStatus.TOO_MANY_REQUESTS,
variants: [{ messageExample: 'لطفا بعد از ۱ دقیقه دوباره امتحان کنید.' }],
},
])
public async resetPassword(@Body() dto: ResetPasswordDTO) {
return this.authService.resetPassword(dto);
}
@Public()
@Post('refresh')
@HttpCode(HttpStatus.OK)
+2
View File
@@ -16,6 +16,7 @@ import { RefreshTokensProvider } from './providers/refresh-tokens.provider';
import { RedisModule } from '@/common/modules/redis/redis.module';
import { AuthRedisProvider } from './providers/auth-redis.provider';
import { LogoutProvider } from './providers/logout.provider';
import { ResetPasswordProvider } from './providers/reset-password.provider';
@Module({
imports: [
@@ -45,6 +46,7 @@ import { LogoutProvider } from './providers/logout.provider';
RefreshTokensProvider,
AuthRedisProvider,
LogoutProvider,
ResetPasswordProvider,
{
provide: APP_GUARD,
useClass: GlobalAuthGuard,
+3 -1
View File
@@ -22,7 +22,9 @@ export class PhoneDTO {
field: '$t(auth.fields.phone)',
}),
})
@Transform(({ value }) => Utils.StringUtils.normalizePhone(value as string))
@Transform(({ value }: { value: unknown }) =>
typeof value === 'string' ? Utils.StringUtils.normalizePhone(value) : value,
)
phone!: string;
}
@@ -0,0 +1,14 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsString, Matches, ValidateIf } from 'class-validator';
import { i18nValidationMessage as t } from 'nestjs-i18n';
import { PhoneDTO } from './login.dto';
export class ResetPasswordDTO extends PhoneDTO {
@ApiPropertyOptional({ description: '5-digit OTP code', example: '12345' })
@ValidateIf((_object, value) => value !== undefined)
@IsString()
@Matches(/^[0-9]{5}$/, {
message: t('validation.wrongFieldFormat', { field: '$t(auth.fields.otp)' }),
})
otp?: string;
}
@@ -0,0 +1,9 @@
import { ApiProperty } from '@nestjs/swagger';
export class ResetPasswordOtpResponseDTO {
@ApiProperty({ example: '12345' })
code!: string;
@ApiProperty({ type: Date })
otpExpiresAt!: Date;
}
@@ -0,0 +1,6 @@
POST {{baseUrl}}/auth/reset-password/
Content-Type: application/json
{
"phone": "09333026363"
}
@@ -7,6 +7,8 @@ import { RefreshTokenDTO } from '../dtos/refresh-token.dto';
import { RefreshTokensProvider } from './refresh-tokens.provider';
import { LogoutDTO } from '../dtos/logout.dto';
import { LogoutProvider } from './logout.provider';
import { ResetPasswordDTO } from '../dtos/reset-password.dto';
import { ResetPasswordProvider } from './reset-password.provider';
@Injectable()
export class AuthService {
@@ -30,6 +32,7 @@ export class AuthService {
* Inject Logout Provider
*/
private readonly logoutProvider: LogoutProvider,
private readonly resetPasswordProvider: ResetPasswordProvider,
) {}
public async logIn(loginDto: LoginDTO) {
@@ -44,6 +47,10 @@ export class AuthService {
return await this.refreshTokensProvider.refreshTokens(refreshTokenDto);
}
public async resetPassword(dto: ResetPasswordDTO) {
return this.resetPasswordProvider.resetPassword(dto);
}
public async logout(
userId: number,
logoutDto: LogoutDTO,
@@ -0,0 +1,42 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { AppResponse } from '@/common/responses';
import { OtpService } from '@/modules/otp/providers/otp.service';
import { UsersService } from '@/modules/users/providers/users.service';
import { ResetPasswordDTO } from '../dtos/reset-password.dto';
import { GenerateTokenProvider } from './generate-token.provider';
import { OtpPurpose } from '@/modules/otp/enums/otp-purpose.enum';
@Injectable()
export class ResetPasswordProvider {
constructor(
private readonly usersService: UsersService,
private readonly otpService: OtpService,
private readonly generateTokenProvider: GenerateTokenProvider,
) {}
public async resetPassword({ phone, otp }: ResetPasswordDTO) {
// if (
// process.env.NODE_ENV !== 'development' ||
// process.env.AUTH_RESET_PASSWORD_RETURN_OTP !== 'true'
// ) {
// throw new NotFoundException();
// }
const user = await this.usersService.findOneByPhone(phone);
if (!user) {
throw new NotFoundException('auth.errors.accountNotFound');
}
if (otp !== undefined) {
await this.otpService.verifyOTP(phone, otp, OtpPurpose.PASSWORD_RESET);
return this.generateTokenProvider.generateTokens(user, randomUUID());
}
const { code, expiresAt } = await this.otpService.createOTP(
phone,
OtpPurpose.PASSWORD_RESET,
);
return new AppResponse({ code, otpExpiresAt: expiresAt });
}
}
+32
View File
@@ -1,8 +1,11 @@
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Param,
ParseIntPipe,
Post,
Res,
} from '@nestjs/common';
@@ -13,6 +16,8 @@ import { ActiveUser } from '@/common/decorators/active-user.decorator';
import { User } from '../users/entities/user.entity';
import { ApiAppResponse } from '@/common/decorators/api-app-response.decorator';
import { Throttle } from '@nestjs/throttler';
import { GetConversationDTO } from './dtos/get-conversation.dto';
import { GetConversationDetailsDTO } from './dtos/get-conversation-details.dto';
@Controller('chatbot')
@Throttle({ default: { limit: 30, ttl: 60_000 } })
@@ -24,6 +29,33 @@ export class ChatbotController {
private readonly chatbotService: ChatbotService,
) {}
@Get('conversations')
@ApiAppResponse([
{
status: HttpStatus.OK,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
variants: [{ model: GetConversationDTO, isArray: true }],
},
])
public async getConversations(@ActiveUser() user: User) {
return this.chatbotService.getConversations(user);
}
@Get('conversations/:conversationId')
@ApiAppResponse([
{
status: HttpStatus.OK,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
variants: [{ model: GetConversationDetailsDTO }],
},
])
public async getConversation(
@Param('conversationId', ParseIntPipe) conversationId: number,
@ActiveUser() user: User,
) {
return this.chatbotService.getConversation(user, conversationId);
}
@Post('chat')
@HttpCode(HttpStatus.OK)
@ApiAppResponse([
@@ -0,0 +1,25 @@
import { ApiProperty } from '@nestjs/swagger';
import { MessageRole } from '@/modules/conversation/enums/message-role.enum';
import { GetConversationDTO } from './get-conversation.dto';
export class GetConversationMessageDTO {
@ApiProperty({ type: 'number', example: 1 })
messageId!: number;
@ApiProperty({ enum: MessageRole })
role!: MessageRole;
@ApiProperty({ type: 'string' })
content!: string;
@ApiProperty({ type: 'string', format: 'date-time' })
createdAt!: Date;
}
export class GetConversationDetailsDTO extends GetConversationDTO {
@ApiProperty({ type: 'string', format: 'date-time' })
createdAt!: Date;
@ApiProperty({ type: GetConversationMessageDTO, isArray: true })
messages!: GetConversationMessageDTO[];
}
@@ -0,0 +1,12 @@
import { ApiProperty } from '@nestjs/swagger';
export class GetConversationDTO {
@ApiProperty({ type: 'number', example: 1 })
conversationId!: number;
@ApiProperty({ type: 'string', nullable: true })
title!: string | null;
@ApiProperty({ type: 'string', format: 'date-time' })
updatedAt!: Date;
}
@@ -0,0 +1,6 @@
GET {{baseUrl}}/chatbot/conversations
Authorization: Bearer {{$global.accessToken}}
### Get a conversation owned by the authenticated user
GET {{baseUrl}}/chatbot/conversations/1
Authorization: Bearer {{$global.accessToken}}
@@ -27,6 +27,38 @@ export class ChatbotService {
private readonly openRouterService: OpenRouterService,
) {}
public async getConversations(user: User) {
const conversations =
await this.conversationService.findConversationsByUser(user);
return conversations.map((conversation) => ({
conversationId: conversation.id,
title: conversation.title,
updatedAt: conversation.updatedAt,
}));
}
public async getConversation(user: User, conversationId: number) {
const conversation = await this.conversationService.findConversationById(
conversationId,
user,
);
const messages = await this.conversationService.getMessages(conversation);
return {
conversationId: conversation.id,
title: conversation.title,
createdAt: conversation.createdAt,
updatedAt: conversation.updatedAt,
messages: messages.map((message) => ({
messageId: message.id,
role: message.role,
content: message.content,
createdAt: message.createdAt,
})),
};
}
private async getConversationMessages(
user: User,
message: string,
@@ -0,0 +1,86 @@
import { Repository } from 'typeorm';
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
import { ConversationService } from './conversation.service';
import { Conversation } from '../entities/conversation.entity';
import { Message } from '../entities/message.entity';
import { User } from '@/modules/users/entities/user.entity';
import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
import { HttpStatus } from '@nestjs/common';
describe('Conversation list', () => {
const find = jest.fn<Repository<Conversation>['find']>();
const service = new ConversationService(
{ find } as unknown as Repository<Conversation>,
{} as Repository<Message>,
);
const user = { id: 42 } as User;
// eslint-disable-next-line @typescript-eslint/require-await
beforeEach(async () => jest.resetAllMocks());
it('restricts results to the authenticated user and orders newest first', async () => {
find.mockResolvedValue([]);
await expect(service.findConversationsByUser(user)).resolves.toEqual([]);
expect(find).toHaveBeenCalledWith({
select: { id: true, title: true, updatedAt: true },
where: { userId: 42 },
order: { updatedAt: 'DESC', id: 'DESC' },
});
});
it('handles repository failures using the application exception', async () => {
find.mockRejectedValue(new Error('Database unavailable'));
await expect(service.findConversationsByUser(user)).rejects.toBeInstanceOf(
AppTimeoutException,
);
});
});
describe('Conversation details access', () => {
const findOne = jest.fn<Repository<Conversation>['findOne']>();
const findMessages = jest.fn<Repository<Message>['find']>();
const service = new ConversationService(
{ findOne } as unknown as Repository<Conversation>,
{ find: findMessages } as unknown as Repository<Message>,
);
const user = { id: 42 } as User;
beforeEach(() => {
jest.resetAllMocks();
});
it('looks up a conversation by both its ID and its owner', async () => {
const conversation = { id: 7, userId: 42 } as Conversation;
findOne.mockResolvedValue(conversation);
await expect(service.findConversationById(7, user)).resolves.toBe(
conversation,
);
expect(findOne).toHaveBeenCalledWith({
where: { id: 7, user: { id: 42 } },
});
});
it('returns not found for missing conversations or conversations owned by another user', async () => {
findOne.mockResolvedValue(null);
await expect(service.findConversationById(7, user)).rejects.toMatchObject({
status: HttpStatus.NOT_FOUND,
});
expect(findMessages).not.toHaveBeenCalled();
});
it('loads only the conversation messages in chronological order with a stable tie breaker', async () => {
findMessages.mockResolvedValue([]);
await expect(
service.getMessages({ id: 7 } as Conversation),
).resolves.toEqual([]);
expect(findMessages).toHaveBeenCalledWith({
where: { conversation: { id: 7 } },
order: { createdAt: 'ASC', id: 'ASC' },
});
});
});
@@ -24,6 +24,18 @@ export class ConversationService {
private readonly messageRepository: Repository<Message>,
) {}
public async findConversationsByUser(user: User): Promise<Conversation[]> {
try {
return await this.conversationRepository.find({
select: { id: true, title: true, updatedAt: true },
where: { userId: user.id },
order: { updatedAt: 'DESC', id: 'DESC' },
});
} catch (err) {
throw new AppTimeoutException(err);
}
}
public async createConversation(
user: User,
title?: string,
@@ -100,6 +112,7 @@ export class ConversationService {
},
order: {
createdAt: 'ASC',
id: 'ASC',
},
});
} catch (err) {
+4
View File
@@ -7,6 +7,7 @@ import {
PrimaryGeneratedColumn,
BaseEntity,
} from 'typeorm';
import { OtpPurpose } from '../enums/otp-purpose.enum';
@Entity()
@Index(['phone', 'used'])
@@ -28,6 +29,9 @@ export class OTP extends BaseEntity {
})
code!: string;
@Column({ type: 'enum', enum: OtpPurpose, default: 'signup' })
purpose!: OtpPurpose;
@CreateDateColumn()
createdAt!: Date;
@@ -0,0 +1,4 @@
export enum OtpPurpose {
PASSWORD_RESET = 'password-reset',
SIGNUP = 'signup',
}
+15 -1
View File
@@ -3,6 +3,7 @@ import { OTP } from '../entities/otp.entity';
import { OtpService } from './otp.service';
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
import { OtpPurpose } from '../enums/otp-purpose.enum';
describe('OTP verification', () => {
let otp: OTP;
@@ -48,7 +49,7 @@ describe('OTP verification', () => {
it('consumes the latest OTP under a database write lock and rejects reuse', async () => {
await expect(service.verifyOTP(otp.phone, '12345')).resolves.toBe(otp);
expect(findOne).toHaveBeenCalledWith({
where: { phone: otp.phone },
where: { phone: otp.phone, purpose: 'signup' },
order: { createdAt: 'DESC', id: 'DESC' },
lock: { mode: 'pessimistic_write' },
});
@@ -71,6 +72,19 @@ describe('OTP verification', () => {
expect(save).toHaveBeenCalledTimes(10);
});
it('looks up password reset codes by both phone and purpose', async () => {
findOne.mockResolvedValue(null);
await expect(
service.verifyOTP(otp.phone, '12345', OtpPurpose.PASSWORD_RESET),
).rejects.toThrow();
expect(findOne).toHaveBeenCalledWith(
expect.objectContaining({
where: { phone: otp.phone, purpose: 'password-reset' },
}),
);
expect(compare).not.toHaveBeenCalled();
});
it('allows a correct code after nine wrong guesses', async () => {
otp.failedAttempts = 9;
await expect(service.verifyOTP(otp.phone, '12345')).resolves.toBe(otp);
+21 -8
View File
@@ -7,6 +7,7 @@ import { Cron, CronExpression } from '@nestjs/schedule';
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
import { AppException } from '@/common/exceptions/app.exception';
import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
import { OtpPurpose } from '../enums/otp-purpose.enum';
@Injectable()
export class OtpService {
@@ -36,9 +37,13 @@ export class OtpService {
*/
public async createOTP(
phone: string,
purpose: OtpPurpose = OtpPurpose.SIGNUP,
): Promise<{ code: string; expiresAt: Date }> {
// OTP request Rate limit
const lastOTP = await this.otpRepository.findOne({
return this.otpRepository.manager.transaction(async (manager) => {
// Serialize requests even when the phone has no OTP rows yet.
await manager.query('SELECT pg_advisory_xact_lock($1::bigint)', [phone]);
const repository = manager.getRepository(OTP);
const lastOTP = await repository.findOne({
where: { phone },
order: { createdAt: 'DESC', id: 'DESC' },
});
@@ -53,18 +58,26 @@ export class OtpService {
const code = this.generateOTPCode();
const hashedCode = await this.hashingProvider.hash(code);
const otp = this.otpRepository.create({ phone, code: hashedCode });
await this.otpRepository.save(otp);
const otp = repository.create({
phone,
code: hashedCode,
purpose,
createdAt: new Date(),
});
await repository.save(otp);
return { code, expiresAt: otp.expiresAt };
});
}
/**
* Verify OTP
*/
public async verifyOTP(phone: string, code: string): Promise<OTP> {
public async verifyOTP(
phone: string,
code: string,
purpose: OtpPurpose = OtpPurpose.SIGNUP,
): Promise<OTP> {
let verifiedOTP: OTP | null;
try {
@@ -72,7 +85,7 @@ export class OtpService {
async (manager) => {
const repository = manager.getRepository(OTP);
const otp = await repository.findOne({
where: { phone },
where: { phone, purpose },
order: { createdAt: 'DESC', id: 'DESC' },
lock: { mode: 'pessimistic_write' },
});
@@ -0,0 +1,51 @@
import { MatchField } from '@/common/decorators/match-field.decorator';
import { Role } from '@/common/enums/roles.enum';
import { PhoneDTO } from '@/modules/auth/dtos/login.dto';
import {
IsEnum,
IsNotEmpty,
IsString,
Matches,
MaxLength,
MinLength,
} from 'class-validator';
import { i18nValidationMessage as t } from 'nestjs-i18n';
export class CreatePrivilegedUserDTO extends PhoneDTO {
@IsString()
@IsNotEmpty()
@MaxLength(96)
firstName!: string;
@IsString()
@IsNotEmpty()
@MaxLength(96)
lastName!: string;
@IsString()
@IsNotEmpty()
@MinLength(8, {
message: t('validation.minLengthField', {
field: '$t(users.fields.password)',
min: 8,
}),
})
@MaxLength(96, {
message: t('validation.maxLengthField', {
field: '$t(users.fields.password)',
max: 96,
}),
})
@Matches(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z\d]).{8,}$/, {
message: t('users.errors.passwordPattern'),
})
password!: string;
@IsNotEmpty()
@MatchField('password')
confirmPassword!: string;
@IsEnum(Role)
@IsNotEmpty()
role!: Role;
}
@@ -0,0 +1,37 @@
import { ConflictException, Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
import { CreatePrivilegedUserDTO } from '../dtos/create-privileged-user.dto';
@Injectable()
export class PrivilegedUserProvider {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
private readonly hashingProvider: HashingProvider,
) {}
public async createPrivilegedUser(data: CreatePrivilegedUserDTO) {
const existingUser = await this.userRepository.findOne({
where: { phone: data.phone },
});
if (existingUser) {
throw new ConflictException('User already exists.');
}
const hashedPassword = await this.hashingProvider.hash(data.password);
const user = this.userRepository.create({
phone: data.phone,
firstName: data.firstName,
lastName: data.lastName,
password: hashedPassword,
role: data.role,
});
return this.userRepository.save(user);
}
}
@@ -5,6 +5,8 @@ import { InjectRepository } from '@nestjs/typeorm';
import { UpdateProfileDTO } from '../dtos/update-profile.dto';
import { UserProfileProvider } from './user-profile.provider';
import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
import { PrivilegedUserProvider } from './privileged-user.provider';
import { CreatePrivilegedUserDTO } from '../dtos/create-privileged-user.dto';
@Injectable()
export class UsersService {
@@ -19,6 +21,11 @@ export class UsersService {
* Inject UpdateProfile Provider
*/
private readonly userProfileProvider: UserProfileProvider,
/**
* Inject PrivilegedUser Provider
*/
private readonly privilegedUserProvider: PrivilegedUserProvider,
) {}
public async findOneById(id: number) {
@@ -63,4 +70,12 @@ export class UsersService {
public async updateProfile(user: User, updateProfileDto: UpdateProfileDTO) {
return await this.userProfileProvider.updateProfile(user, updateProfileDto);
}
public async createPrivilegedUser(
createPrivilegedUserDto: CreatePrivilegedUserDTO,
) {
return await this.privilegedUserProvider.createPrivilegedUser(
createPrivilegedUserDto,
);
}
}
+2 -1
View File
@@ -5,11 +5,12 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { HashingModule } from '@/common/modules/hashing/hashing.module';
import { UserProfileProvider } from './providers/user-profile.provider';
import { PrivilegedUserProvider } from './providers/privileged-user.provider';
@Module({
imports: [TypeOrmModule.forFeature([User]), HashingModule],
controllers: [UsersController],
providers: [UsersService, UserProfileProvider],
providers: [UsersService, UserProfileProvider, PrivilegedUserProvider],
exports: [UsersService],
})
export class UsersModule {}