feat: 开发user、auth相关接口,初始化后台管理项目admin

This commit is contained in:
R524809
2025-11-19 17:42:53 +08:00
parent 7acadf191f
commit d195495449
45 changed files with 3016 additions and 101 deletions

24
apps/admin/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
apps/admin/README.md Normal file
View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is currently not compatible with SWC. See [this issue](https://github.com/vitejs/vite-plugin-react/issues/428) for tracking the progress.
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

16
apps/admin/index.html Normal file
View File

@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>admin</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

30
apps/admin/package.json Normal file
View File

@@ -0,0 +1,30 @@
{
"name": "admin",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.0",
"react-dom": "^19.2.0"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/node": "^24.10.0",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"@vitejs/plugin-react-swc": "^4.2.1",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.3",
"vite": "^7.2.2"
}
}

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

42
apps/admin/src/App.css Normal file
View File

@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

35
apps/admin/src/App.tsx Normal file
View File

@@ -0,0 +1,35 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
function App() {
const [count, setCount] = useState(0)
return (
<>
<div>
<a href="https://vite.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
)
}
export default App

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

68
apps/admin/src/index.css Normal file
View File

@@ -0,0 +1,68 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

10
apps/admin/src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
apps/admin/tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})

View File

@@ -7,3 +7,6 @@ DB_USER=
DB_PASSWORD=
DB_DATABASE=vest_mind_test
# DB_DATABASE_TEST=vest_mind_test
JWT_SECRET=vest_thinking_key
JWT_EXPIRES_IN=7d

View File

@@ -24,16 +24,22 @@
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
"@nestjs/jwt": "^11.0.1",
"@nestjs/mapped-types": "^2.1.0",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/swagger": "^11.2.2",
"@nestjs/typeorm": "^11.0.0",
"@types/jsonwebtoken": "^9.0.10",
"bcrypt": "^6.0.0",
"body-parser": "^2.2.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.2",
"compression": "^1.8.1",
"express-rate-limit": "^8.2.1",
"helmet": "^8.1.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"pg": "^8.16.3",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
@@ -45,11 +51,13 @@
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/bcrypt": "^6.0.0",
"@types/body-parser": "^1.19.6",
"@types/compression": "^1.8.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^22.10.7",
"@types/passport-jwt": "^4.0.1",
"@types/pg": "^8.15.6",
"@types/supertest": "^6.0.2",
"eslint": "^9.18.0",

View File

@@ -1,22 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@@ -1,12 +0,0 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

View File

@@ -3,8 +3,8 @@ import { ConfigModule } from '@nestjs/config';
import { DatabaseModule } from './database/database.module';
import { CoreModule } from './core/core.module';
import { BrokerModule } from './modules/broker/broker.module';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './modules/user/user.module';
import { AuthModule } from './modules/auth/auth.module';
@Module({
imports: [
@@ -18,8 +18,10 @@ import { AppService } from './app.service';
CoreModule,
DatabaseModule,
BrokerModule,
UserModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
controllers: [],
providers: [],
})
export class AppModule {}

View File

@@ -1,8 +0,0 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@@ -0,0 +1,66 @@
import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { LoginResponse } from './interfaces/login-response.interface';
@ApiTags('auth')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
/**
* 用户登录
*/
@Post('login')
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: '用户登录',
description: '使用用户名/邮箱和密码登录,返回 access_token 和用户信息',
})
@ApiResponse({
status: 200,
description: '登录成功',
schema: {
type: 'object',
properties: {
code: { type: 'number', example: 0 },
message: { type: 'string', example: 'success' },
data: {
type: 'object',
properties: {
accessToken: {
type: 'string',
example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
},
user: {
type: 'object',
properties: {
userId: { type: 'number', example: 1 },
username: {
type: 'string',
example: 'john_doe',
},
email: {
type: 'string',
example: 'user@example.com',
},
nickname: {
type: 'string',
example: 'John Doe',
},
role: { type: 'string', example: 'user' },
},
},
},
},
timestamp: { type: 'string' },
},
},
})
@ApiResponse({ status: 401, description: '用户名或密码错误' })
@ApiResponse({ status: 400, description: '请求参数错误' })
async login(@Body() loginDto: LoginDto): Promise<LoginResponse> {
return this.authService.login(loginDto);
}
}

View File

@@ -0,0 +1,41 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './strategies/jwt.strategy';
import { User } from '../user/user.entity';
@Module({
imports: [
TypeOrmModule.forFeature([User]),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [ConfigModule],
// @ts-expect-error - JWT expiresIn accepts string but type definition is strict
useFactory: (configService: ConfigService) => {
const expiresIn = configService.get<string>(
'JWT_EXPIRES_IN',
'7d',
);
const secret = configService.get<string>(
'JWT_SECRET',
'your-secret-key-change-in-production',
);
return {
secret: secret,
signOptions: {
expiresIn: expiresIn || '7d', // 默认7天过期
},
};
},
inject: [ConfigService],
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [AuthService, JwtModule],
})
export class AuthModule {}

View File

@@ -0,0 +1,73 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { User } from '../user/user.entity';
import { LoginDto } from './dto/login.dto';
import { JwtPayload } from './interfaces/jwt-payload.interface';
import { LoginResponse } from './interfaces/login-response.interface';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
private readonly jwtService: JwtService,
) {}
/**
* 用户登录
*/
async login(loginDto: LoginDto): Promise<LoginResponse> {
// 根据用户名或邮箱查找用户
const user = await this.userRepository.findOne({
where: [
{ username: loginDto.usernameOrEmail },
{ email: loginDto.usernameOrEmail },
],
});
if (!user) {
throw new UnauthorizedException('用户名或密码错误');
}
// 检查用户状态
if (user.status !== 'active') {
throw new UnauthorizedException('用户已被禁用');
}
// 验证密码
const isPasswordValid = await bcrypt.compare(
loginDto.password,
user.passwordHash,
);
if (!isPasswordValid) {
throw new UnauthorizedException('用户名或密码错误');
}
// 更新最后登录时间
user.lastLoginAt = new Date();
await this.userRepository.save(user);
// 生成 JWT token
const payload: JwtPayload = {
sub: user.userId,
username: user.username,
email: user.email,
role: user.role,
};
const accessToken = this.jwtService.sign(payload);
// 返回 token 和用户信息(排除密码)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { passwordHash, ...userWithoutPassword } = user;
return {
accessToken,
user: userWithoutPassword,
};
}
}

View File

@@ -0,0 +1,37 @@
import { SetMetadata } from '@nestjs/common';
/**
* 角色权限装饰器
*
* 这个装饰器用于在控制器或方法上标记需要的角色权限。
* 配合 RolesGuard 使用实现基于角色的访问控制RBAC
*
* 使用示例:
* @Roles('admin', 'super_admin')
* @Get()
* findAll() { ... }
*
* 工作原理:
* 1. SetMetadata 会在目标方法或类上设置元数据
* 2. ROLES_KEY 作为元数据的键,存储角色数组
* 3. RolesGuard 通过 Reflector 读取这些元数据来验证用户权限
*/
/**
* 元数据键名
* 用于在 Reflector 中存储和读取角色信息
*/
export const ROLES_KEY = 'roles';
/**
* 角色权限装饰器工厂函数
*
* @param roles - 允许访问的角色列表(可变参数)
* @returns 返回一个装饰器函数,用于设置元数据
*
* 示例:
* - @Roles('admin') - 只允许 admin 角色访问
* - @Roles('admin', 'super_admin') - 允许 admin 或 super_admin 角色访问
* - @Roles() - 不传参数时RolesGuard 会允许所有已认证用户访问
*/
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);

View File

@@ -0,0 +1,22 @@
import { IsString, IsNotEmpty, MinLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class LoginDto {
@ApiProperty({
description: '用户名或邮箱',
example: 'john_doe',
})
@IsString()
@IsNotEmpty()
@MinLength(3)
usernameOrEmail: string;
@ApiProperty({
description: '密码',
example: 'password123',
})
@IsString()
@IsNotEmpty()
@MinLength(6)
password: string;
}

View File

@@ -0,0 +1,24 @@
import {
Injectable,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
handleRequest<TUser = unknown>(
err: Error | null,
user: TUser | false,
info: Error | string | undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_context: ExecutionContext,
): TUser {
// 如果认证失败user 为 false 或 undefined或者有错误
if (err || !user || info) {
throw new UnauthorizedException('身份验证失败');
}
return user;
}
}

View File

@@ -0,0 +1,44 @@
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles) {
// 如果没有设置角色要求,允许访问
return true;
}
const request = context.switchToHttp().getRequest<{
user?: { role: string };
}>();
const user = request.user;
if (!user) {
throw new ForbiddenException('未授权访问');
}
const hasRole = requiredRoles.some((role) => user.role === role);
if (!hasRole) {
throw new ForbiddenException(
`需要以下角色之一:${requiredRoles.join('、')}`,
);
}
return true;
}
}

View File

@@ -0,0 +1,6 @@
export interface JwtPayload {
sub: number; // 用户ID
username: string;
email: string;
role: string;
}

View File

@@ -0,0 +1,6 @@
import { User } from '../../user/user.entity';
export interface LoginResponse {
accessToken: string;
user: Omit<User, 'passwordHash'>; // 排除密码哈希
}

View File

@@ -0,0 +1,38 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../user/user.entity';
import { JwtPayload } from '../interfaces/jwt-payload.interface';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly configService: ConfigService,
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>(
'JWT_SECRET',
'your-secret-key',
),
});
}
async validate(payload: JwtPayload): Promise<User> {
const user = await this.userRepository.findOne({
where: { userId: payload.sub },
});
if (!user || user.status !== 'active') {
throw new UnauthorizedException('用户不存在或已被禁用');
}
return user;
}
}

View File

@@ -32,7 +32,7 @@ export class BrokerService {
if (existingByCode) {
throw new ConflictException(
`Broker with code "${createBrokerDto.brokerCode}" already exists in region "${createBrokerDto.region}"`,
`地区 "${createBrokerDto.region}" 中已存在代码为 "${createBrokerDto.brokerCode}" 的券商`,
);
}
@@ -46,7 +46,7 @@ export class BrokerService {
if (existingByName) {
throw new ConflictException(
`Broker with name "${createBrokerDto.brokerName}" already exists in region "${createBrokerDto.region}"`,
`地区 "${createBrokerDto.region}" 中已存在名称为 "${createBrokerDto.brokerName}" 的券商`,
);
}
@@ -88,10 +88,10 @@ export class BrokerService {
if (existingBrokers.length > 0) {
const conflicts = existingBrokers.map(
(b) => `${b.brokerCode} in ${b.region}`,
(b) => `${b.brokerCode} (${b.region})`,
);
throw new ConflictException(
`The following brokers already exist: ${conflicts.join(', ')}`,
`以下券商已存在:${conflicts.join('')}`,
);
}
@@ -101,7 +101,7 @@ export class BrokerService {
);
if (uniquePairs.size !== codeRegionPairs.length) {
throw new ConflictException(
'Duplicate broker_code and region combinations in batch data',
'批量数据中存在重复的券商代码和地区组合',
);
}
@@ -152,7 +152,7 @@ export class BrokerService {
});
if (!broker) {
throw new NotFoundException(`Broker with ID ${id} not found`);
throw new NotFoundException(`未找到ID ${id} 的券商`);
}
return broker;
@@ -187,9 +187,7 @@ export class BrokerService {
const broker = await this.brokerRepository.findOne({ where });
if (!broker) {
throw new NotFoundException(
'Broker not found with the given conditions',
);
throw new NotFoundException('未找到符合给定条件的券商');
}
return broker;
@@ -218,7 +216,7 @@ export class BrokerService {
if (existing && existing.brokerId !== id) {
throw new ConflictException(
`Broker with code "${newCode}" already exists in region "${newRegion}"`,
`地区 "${newRegion}" 中已存在代码为 "${newCode}" 的券商`,
);
}
}
@@ -237,7 +235,7 @@ export class BrokerService {
if (existing && existing.brokerId !== id) {
throw new ConflictException(
`Broker with name "${newName}" already exists in region "${newRegion}"`,
`地区 "${newRegion}" 中已存在名称为 "${newName}" 的券商`,
);
}
}

View File

@@ -0,0 +1,23 @@
import { IsString, IsNotEmpty, MinLength, MaxLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class ChangePasswordDto {
@ApiProperty({
description: '旧密码',
example: 'OldPassword123!',
})
@IsString()
@IsNotEmpty()
oldPassword: string;
@ApiProperty({
description: '新密码',
example: 'NewPassword123!',
minLength: 6,
})
@IsString()
@IsNotEmpty()
@MinLength(6)
@MaxLength(100)
newPassword: string;
}

View File

@@ -0,0 +1,109 @@
import {
IsString,
IsNotEmpty,
IsOptional,
IsEmail,
MinLength,
MaxLength,
Matches,
IsIn,
} from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({
description: '用户名',
example: 'john_doe',
maxLength: 100,
})
@IsString()
@IsNotEmpty()
@MinLength(3)
@MaxLength(100)
username: string;
@ApiProperty({
description: '密码(明文,服务端会使用 bcrypt 加密后存储)',
example: 'SecurePassword123!',
minLength: 6,
})
@IsString()
@IsNotEmpty()
@MinLength(6)
@MaxLength(100)
password: string;
@ApiProperty({
description: '邮箱',
example: 'user@example.com',
maxLength: 100,
})
@IsEmail()
@IsNotEmpty()
@MaxLength(100)
email: string;
@ApiPropertyOptional({
description: '用户昵称',
example: 'John Doe',
maxLength: 100,
})
@IsOptional()
@IsString()
@MaxLength(100)
nickname?: string;
@ApiPropertyOptional({
description: '头像URL',
example: 'https://example.com/avatar.jpg',
maxLength: 255,
})
@IsOptional()
@IsString()
@MaxLength(255)
avatarUrl?: string;
@ApiPropertyOptional({
description: '电话号码',
example: '13800138000',
maxLength: 20,
})
@IsOptional()
@IsString()
@Matches(/^[0-9+\-() ]+$/, {
message: '电话号码格式不正确',
})
@MaxLength(20)
phone?: string;
@ApiPropertyOptional({
description: '微信 openId',
example: 'openid123456',
maxLength: 100,
})
@IsOptional()
@IsString()
@MaxLength(100)
openId?: string;
@ApiPropertyOptional({
description: '微信 unionId',
example: 'unionid123456',
maxLength: 100,
})
@IsOptional()
@IsString()
@MaxLength(100)
unionId?: string;
@ApiPropertyOptional({
description: '用户角色',
example: 'user',
enum: ['user', 'admin', 'super_admin'],
default: 'user',
})
@IsOptional()
@IsString()
@IsIn(['user', 'admin', 'super_admin'])
role?: string;
}

View File

@@ -0,0 +1,20 @@
import { IsOptional, IsString, IsEmail } from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger';
export class QueryUserDto {
@ApiPropertyOptional({
description: '用户名',
example: 'john_doe',
})
@IsOptional()
@IsString()
username?: string;
@ApiPropertyOptional({
description: '邮箱',
example: 'user@example.com',
})
@IsOptional()
@IsEmail()
email?: string;
}

View File

@@ -0,0 +1,73 @@
import {
IsString,
IsOptional,
IsEmail,
MaxLength,
Matches,
IsIn,
} from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger';
export class UpdateUserDto {
@ApiPropertyOptional({
description: '邮箱',
example: 'newemail@example.com',
maxLength: 100,
})
@IsOptional()
@IsEmail()
@MaxLength(100)
email?: string;
@ApiPropertyOptional({
description: '电话号码',
example: '13800138000',
maxLength: 20,
})
@IsOptional()
@IsString()
@Matches(/^[0-9+\-() ]+$/, {
message: '电话号码格式不正确',
})
@MaxLength(20)
phone?: string;
@ApiPropertyOptional({
description: '用户昵称',
example: 'John Doe',
maxLength: 100,
})
@IsOptional()
@IsString()
@MaxLength(100)
nickname?: string;
@ApiPropertyOptional({
description: '头像URL',
example: 'https://example.com/avatar.jpg',
maxLength: 255,
})
@IsOptional()
@IsString()
@MaxLength(255)
avatarUrl?: string;
@ApiPropertyOptional({
description: '用户状态',
example: 'active',
enum: ['active', 'inactive', 'deleted'],
})
@IsOptional()
@IsString()
status?: string;
@ApiPropertyOptional({
description: '用户角色',
example: 'user',
enum: ['user', 'admin', 'super_admin'],
})
@IsOptional()
@IsString()
@IsIn(['user', 'admin', 'super_admin'])
role?: string;
}

View File

@@ -0,0 +1,180 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
Query,
HttpCode,
HttpStatus,
UseGuards,
} from '@nestjs/common';
import {
ApiTags,
ApiOperation,
ApiResponse,
ApiParam,
ApiBearerAuth,
} from '@nestjs/swagger';
import { UserService } from './user.service';
import { User } from './user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { QueryUserDto } from './dto/query-user.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator';
@ApiTags('user')
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
/**
* 注册用户
*/
@Post('register')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({
summary: '注册用户',
description: '创建新用户username、password、email 为必填项',
})
@ApiResponse({
status: 201,
description: '注册成功',
type: User,
})
@ApiResponse({ status: 400, description: '请求参数错误' })
@ApiResponse({
status: 409,
description: '用户名、邮箱或其他唯一字段已存在',
})
create(@Body() createUserDto: CreateUserDto): Promise<User> {
return this.userService.create(createUserDto);
}
/**
* 查询所有用户
*/
@Get()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin', 'super_admin')
@ApiBearerAuth()
@ApiOperation({
summary: '查询所有用户',
description: '获取所有用户列表(需要管理员权限)',
})
@ApiResponse({
status: 200,
description: '查询成功',
type: [User],
})
@ApiResponse({ status: 401, description: '未授权' })
@ApiResponse({ status: 403, description: '权限不足' })
findAll(): Promise<User[]> {
return this.userService.findAll();
}
/**
* 根据 username 或 email 查询单个用户
*/
@Get('find')
@ApiOperation({
summary: '查询单个用户',
description: '根据 username 或 email 查询用户',
})
@ApiResponse({
status: 200,
description: '查询成功',
type: User,
})
@ApiResponse({
status: 400,
description: '请求参数错误,必须提供 username 或 email',
})
@ApiResponse({ status: 404, description: '用户不存在' })
findOne(@Query() queryDto: QueryUserDto): Promise<User> {
return this.userService.findOne(queryDto);
}
/**
* 根据 ID 查询单个用户
*/
@Get(':id')
@ApiOperation({
summary: '根据ID查询用户',
description: '根据用户ID获取详细信息',
})
@ApiParam({ name: 'id', description: '用户ID', type: Number })
@ApiResponse({
status: 200,
description: '查询成功',
type: User,
})
@ApiResponse({ status: 404, description: '用户不存在' })
findOneById(@Param('id') id: string): Promise<User> {
return this.userService.findOneById(+id);
}
/**
* 更新用户信息
*/
@Patch(':id')
@ApiOperation({
summary: '更新用户信息',
description: '更新用户信息,不允许修改 username、openId、unionId',
})
@ApiParam({ name: 'id', description: '用户ID', type: Number })
@ApiResponse({
status: 200,
description: '更新成功',
type: User,
})
@ApiResponse({ status: 404, description: '用户不存在' })
@ApiResponse({ status: 409, description: '邮箱或手机号已存在' })
update(
@Param('id') id: string,
@Body() updateUserDto: UpdateUserDto,
): Promise<User> {
return this.userService.update(+id, updateUserDto);
}
/**
* 修改密码
*/
@Patch(':id/password')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({
summary: '修改密码',
description: '修改用户密码,需要先验证旧密码',
})
@ApiParam({ name: 'id', description: '用户ID', type: Number })
@ApiResponse({ status: 204, description: '密码修改成功' })
@ApiResponse({ status: 400, description: '旧密码错误' })
@ApiResponse({ status: 404, description: '用户不存在' })
changePassword(
@Param('id') id: string,
@Body() changePasswordDto: ChangePasswordDto,
): Promise<void> {
return this.userService.changePassword(+id, changePasswordDto);
}
/**
* 删除用户(软删除)
*/
@Delete(':id')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({
summary: '删除用户',
description: '软删除用户,将状态更新为 deleted',
})
@ApiParam({ name: 'id', description: '用户ID', type: Number })
@ApiResponse({ status: 204, description: '删除成功' })
@ApiResponse({ status: 404, description: '用户不存在' })
remove(@Param('id') id: string): Promise<void> {
return this.userService.remove(+id);
}
}

View File

@@ -0,0 +1,142 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
Index,
} from 'typeorm';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
@Entity('user')
export class User {
@ApiProperty({ description: '用户ID', example: 1 })
@PrimaryGeneratedColumn({ name: 'user_id' })
userId: number;
@ApiPropertyOptional({
description: '微信 openId',
example: 'openid123456',
maxLength: 100,
})
@Column({ name: 'open_id', type: 'varchar', length: 100, nullable: true })
@Index()
openId?: string;
@ApiPropertyOptional({
description: '微信 unionId',
example: 'unionid123456',
maxLength: 100,
})
@Column({ name: 'union_id', type: 'varchar', length: 100, nullable: true })
@Index()
unionId?: string;
@ApiProperty({
description: '用户名',
example: 'john_doe',
maxLength: 100,
})
@Column({ name: 'username', type: 'varchar', length: 100 })
@Index()
username: string;
@ApiProperty({
description: '密码哈希值bcrypt加密',
example: '$2b$10$...',
maxLength: 255,
})
@Column({ name: 'password_hash', type: 'varchar', length: 255 })
passwordHash: string;
@ApiProperty({
description: '邮箱',
example: 'user@example.com',
maxLength: 100,
})
@Column({ name: 'email', type: 'varchar', length: 100 })
@Index()
email: string;
@ApiPropertyOptional({
description: '电话号码',
example: '13800138000',
maxLength: 20,
})
@Column({ name: 'phone', type: 'varchar', length: 20, nullable: true })
@Index()
phone?: string;
@ApiPropertyOptional({
description: '用户昵称',
example: 'John Doe',
maxLength: 100,
})
@Column({ name: 'nickname', type: 'varchar', length: 100, nullable: true })
nickname?: string;
@ApiPropertyOptional({
description: '头像URL',
example: 'https://example.com/avatar.jpg',
maxLength: 255,
})
@Column({
name: 'avatar_url',
type: 'varchar',
length: 255,
nullable: true,
})
avatarUrl?: string;
@ApiProperty({
description: '创建时间',
example: '2024-01-01T00:00:00.000Z',
})
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@ApiProperty({
description: '更新时间',
example: '2024-01-01T00:00:00.000Z',
})
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
@ApiPropertyOptional({
description: '最后登录时间',
example: '2024-01-01T00:00:00.000Z',
})
@Column({ name: 'last_login_at', type: 'timestamp', nullable: true })
lastLoginAt?: Date;
@ApiProperty({
description: '用户状态',
example: 'active',
enum: ['active', 'inactive', 'deleted'],
default: 'active',
})
@Column({
name: 'status',
type: 'varchar',
length: 20,
default: 'active',
nullable: false,
})
status: string;
@ApiProperty({
description: '用户角色',
example: 'user',
enum: ['user', 'admin', 'super_admin'],
default: 'user',
})
@Column({
name: 'role',
type: 'varchar',
length: 20,
default: 'user',
nullable: false,
})
@Index()
role: string;
}

View File

@@ -1,4 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { User } from './user.entity';
@Module({})
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}

View File

@@ -0,0 +1,240 @@
import {
Injectable,
NotFoundException,
ConflictException,
BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { User } from './user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { QueryUserDto } from './dto/query-user.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {}
/**
* 注册用户
*/
async create(createUserDto: CreateUserDto): Promise<User> {
// 检查用户名是否已存在
const existingByUsername = await this.userRepository.findOne({
where: { username: createUserDto.username },
});
if (existingByUsername) {
throw new ConflictException(
`用户名 "${createUserDto.username}" 已存在`,
);
}
// 检查邮箱是否已存在
const existingByEmail = await this.userRepository.findOne({
where: { email: createUserDto.email },
});
if (existingByEmail) {
throw new ConflictException(`邮箱 "${createUserDto.email}" 已存在`);
}
// 检查 phone 是否已存在(如果提供了)
/* if (createUserDto.phone) {
const existingByPhone = await this.userRepository.findOne({
where: { phone: createUserDto.phone },
});
if (existingByPhone) {
throw new ConflictException(
`Phone "${createUserDto.phone}" already exists`,
);
}
}
// 检查 openId 是否已存在(如果提供了)
if (createUserDto.openId) {
const existingByOpenId = await this.userRepository.findOne({
where: { openId: createUserDto.openId },
});
if (existingByOpenId) {
throw new ConflictException(
`OpenId "${createUserDto.openId}" already exists`,
);
}
}
// 检查 unionId 是否已存在(如果提供了)
if (createUserDto.unionId) {
const existingByUnionId = await this.userRepository.findOne({
where: { unionId: createUserDto.unionId },
});
if (existingByUnionId) {
throw new ConflictException(
`UnionId "${createUserDto.unionId}" already exists`,
);
}
} */
// 使用 bcrypt 加密密码
const saltRounds = 10;
const passwordHash = await bcrypt.hash(
createUserDto.password,
saltRounds,
);
// 创建用户
const user = this.userRepository.create({
username: createUserDto.username,
passwordHash,
email: createUserDto.email,
nickname: createUserDto.nickname,
avatarUrl: createUserDto.avatarUrl,
phone: createUserDto.phone,
openId: createUserDto.openId,
unionId: createUserDto.unionId,
status: 'active',
role: createUserDto.role || 'user', // 默认为普通用户
});
return this.userRepository.save(user);
}
/**
* 查询所有用户
*/
async findAll(): Promise<User[]> {
return this.userRepository.find({
order: {
createdAt: 'DESC',
},
});
}
/**
* 根据 username 或 email 查询单个用户
*/
async findOne(queryDto: QueryUserDto): Promise<User> {
if (!queryDto.username && !queryDto.email) {
throw new BadRequestException('必须提供用户名或邮箱');
}
const where: { username?: string; email?: string } = {};
if (queryDto.username) {
where.username = queryDto.username;
}
if (queryDto.email) {
where.email = queryDto.email;
}
const user = await this.userRepository.findOne({ where });
if (!user) {
const identifier = queryDto.username || queryDto.email;
throw new NotFoundException(
`未找到${queryDto.username ? '用户名' : '邮箱'}为 "${identifier}" 的用户`,
);
}
return user;
}
/**
* 根据 ID 查询单个用户
*/
async findOneById(id: number): Promise<User> {
const user = await this.userRepository.findOne({
where: { userId: id },
});
if (!user) {
throw new NotFoundException(`未找到ID为 ${id} 的用户`);
}
return user;
}
/**
* 更新用户信息(不允许修改 username、openId、unionId
*/
async update(id: number, updateUserDto: UpdateUserDto): Promise<User> {
const user = await this.findOneById(id);
// 如果更新邮箱,检查是否与其他用户冲突
if (updateUserDto.email && updateUserDto.email !== user.email) {
const existingByEmail = await this.userRepository.findOne({
where: { email: updateUserDto.email },
});
if (existingByEmail) {
throw new ConflictException(
`邮箱 "${updateUserDto.email}" 已存在`,
);
}
}
// 如果更新 phone检查是否与其他用户冲突
if (updateUserDto.phone && updateUserDto.phone !== user.phone) {
const existingByPhone = await this.userRepository.findOne({
where: { phone: updateUserDto.phone },
});
if (existingByPhone) {
throw new ConflictException(
`手机号 "${updateUserDto.phone}" 已存在`,
);
}
}
// 更新用户信息
Object.assign(user, updateUserDto);
return this.userRepository.save(user);
}
/**
* 修改密码(需要先验证旧密码)
*/
async changePassword(
id: number,
changePasswordDto: ChangePasswordDto,
): Promise<void> {
const user = await this.findOneById(id);
// 验证旧密码
const isOldPasswordValid = await bcrypt.compare(
changePasswordDto.oldPassword,
user.passwordHash,
);
if (!isOldPasswordValid) {
throw new BadRequestException('旧密码错误');
}
// 加密新密码
const saltRounds = 10;
const newPasswordHash = await bcrypt.hash(
changePasswordDto.newPassword,
saltRounds,
);
// 更新密码
user.passwordHash = newPasswordHash;
await this.userRepository.save(user);
}
/**
* 删除用户(软删除,更新状态为 deleted
*/
async remove(id: number): Promise<void> {
const user = await this.findOneById(id);
user.status = 'deleted';
await this.userRepository.save(user);
}
}

View File

@@ -1,7 +0,0 @@
import { User } from './user';
describe('User', () => {
it('should be defined', () => {
expect(new User()).toBeDefined();
});
});

View File

@@ -1 +0,0 @@
export class User {}

View File

@@ -0,0 +1,293 @@
import { Test, TestingModule } from '@nestjs/testing';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserService } from '../../../src/modules/user/user.service';
import { User } from '../../../src/modules/user/user.entity';
import { UserModule } from '../../../src/modules/user/user.module';
import { CreateUserDto } from '../../../src/modules/user/dto/create-user.dto';
import { getDatabaseConfig } from '../../../src/database/database.config';
import { ConflictException } from '@nestjs/common';
describe('UserService (集成测试)', () => {
let service: UserService;
let repository: Repository<User>;
let module: TestingModule;
beforeAll(async () => {
jest.setTimeout(30000); // 设置超时为 30 秒
// 创建测试模块,使用真实数据库连接
module = await Test.createTestingModule({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: ['.env.development', '.env'],
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => {
const config = getDatabaseConfig(configService);
// 使用测试数据库(如果配置了),否则使用开发数据库
const testDatabase =
configService.get<string>('DB_DATABASE') ||
(config.database as string);
return {
...config,
database: testDatabase,
synchronize: true, // 测试环境允许同步
dropSchema: false, // 不删除现有数据
} as typeof config;
},
inject: [ConfigService],
}),
UserModule,
],
}).compile();
service = module.get<UserService>(UserService);
repository = module.get<Repository<User>>(getRepositoryToken(User));
// 清理测试数据(可选)
await repository.clear();
});
afterAll(async () => {
// 测试结束后清理
// await repository.clear();
await module.close();
});
describe('create - 集成测试', () => {
it('应该成功在数据库中创建用户', async () => {
const createUserDto: CreateUserDto = {
username: 'test_user_1',
password: 'password123',
email: 'test1@example.com',
nickname: '测试用户1',
};
const result = await service.create(createUserDto);
console.log('regitser result', result);
expect(result).toBeDefined();
expect(result.userId).toBeDefined();
expect(result.username).toBe(createUserDto.username);
expect(result.email).toBe(createUserDto.email);
expect(result.nickname).toBe(createUserDto.nickname);
expect(result.status).toBe('active');
expect(result.role).toBe('user'); // 默认角色
expect(result.passwordHash).toBeDefined();
expect(result.passwordHash).not.toBe(createUserDto.password); // 密码应该被加密
// 验证数据确实保存到数据库
const savedUser = await repository.findOne({
where: { userId: result.userId },
});
expect(savedUser).toBeDefined();
expect(savedUser?.username).toBe(createUserDto.username);
expect(savedUser?.email).toBe(createUserDto.email);
// 清理
await repository.remove(result);
});
it('应该使用默认角色和状态', async () => {
const createUserDto: CreateUserDto = {
username: 'test_user_2',
password: 'password123',
email: 'test2@example.com',
// 不提供 role
};
const result = await service.create(createUserDto);
expect(result.role).toBe('user'); // 默认角色
expect(result.status).toBe('active'); // 默认状态
// 清理
// await repository.remove(result);
});
it('应该支持可选字段', async () => {
const createUserDto: CreateUserDto = {
username: 'test_user_3',
password: 'password123',
email: 'test3@example.com',
nickname: '测试用户3',
avatarUrl: 'https://example.com/avatar.jpg',
phone: '13800138000',
};
const result = await service.create(createUserDto);
expect(result.nickname).toBe(createUserDto.nickname);
expect(result.avatarUrl).toBe(createUserDto.avatarUrl);
expect(result.phone).toBe(createUserDto.phone);
// 清理
// await repository.remove(result);
});
it('应该抛出 ConflictException 当用户名已存在时', async () => {
const createUserDto: CreateUserDto = {
username: 'duplicate_username',
password: 'password123',
email: 'unique@example.com',
};
// 先创建一个用户
await service.create(createUserDto);
// 尝试创建相同用户名的用户
const duplicateDto: CreateUserDto = {
username: 'duplicate_username',
password: 'password456',
email: 'another@example.com',
};
await expect(service.create(duplicateDto)).rejects.toThrow(
ConflictException,
);
await expect(service.create(duplicateDto)).rejects.toThrow(
'用户名',
);
// 清理
// const user = await repository.findOne({ where: { username: 'duplicate_username' } });
// if (user) await repository.remove(user);
});
it('应该抛出 ConflictException 当邮箱已存在时', async () => {
const createUserDto: CreateUserDto = {
username: 'unique_username',
password: 'password123',
email: 'duplicate@example.com',
};
// 先创建一个用户
await service.create(createUserDto);
// 尝试创建相同邮箱的用户
const duplicateDto: CreateUserDto = {
username: 'another_username',
password: 'password456',
email: 'duplicate@example.com',
};
await expect(service.create(duplicateDto)).rejects.toThrow(
ConflictException,
);
await expect(service.create(duplicateDto)).rejects.toThrow('邮箱');
// 清理
// const user = await repository.findOne({ where: { email: 'duplicate@example.com' } });
// if (user) await repository.remove(user);
});
});
describe('findAll - 集成测试', () => {
it('应该返回所有用户列表', async () => {
// 先创建几个测试用户
const users: CreateUserDto[] = [
{
username: 'findall_user_1',
password: 'password123',
email: 'findall1@example.com',
nickname: '查询测试用户1',
},
{
username: 'findall_user_2',
password: 'password123',
email: 'findall2@example.com',
nickname: '查询测试用户2',
},
{
username: 'findall_user_3',
password: 'password123',
email: 'findall3@example.com',
nickname: '查询测试用户3',
role: 'admin',
},
];
const createdUsers: User[] = [];
for (const userDto of users) {
const user = await service.create(userDto);
createdUsers.push(user);
}
// 查询所有用户
const result = await service.findAll();
expect(result).toBeDefined();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBeGreaterThanOrEqual(users.length);
// 验证创建的用户都在列表中
const usernames = result.map((u) => u.username);
users.forEach((userDto) => {
expect(usernames).toContain(userDto.username);
});
// 验证排序(按创建时间倒序)
if (result.length > 1) {
for (let i = 0; i < result.length - 1; i++) {
expect(
result[i].createdAt.getTime(),
).toBeGreaterThanOrEqual(result[i + 1].createdAt.getTime());
}
}
// 清理
// await repository.remove(createdUsers);
});
it('应该返回空数组当没有用户时', async () => {
// 清理所有用户
await repository.clear();
const result = await service.findAll();
expect(result).toBeDefined();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBe(0);
});
it('应该包含用户的所有字段', async () => {
// 创建一个完整信息的用户
const createUserDto: CreateUserDto = {
username: 'full_info_user',
password: 'password123',
email: 'fullinfo@example.com',
nickname: '完整信息用户',
avatarUrl: 'https://example.com/avatar.jpg',
phone: '13800138000',
role: 'admin',
};
await service.create(createUserDto);
// 查询所有用户
const result = await service.findAll();
const foundUser = result.find(
(u) => u.username === createUserDto.username,
);
expect(foundUser).toBeDefined();
expect(foundUser?.userId).toBeDefined();
expect(foundUser?.username).toBe(createUserDto.username);
expect(foundUser?.email).toBe(createUserDto.email);
expect(foundUser?.nickname).toBe(createUserDto.nickname);
expect(foundUser?.avatarUrl).toBe(createUserDto.avatarUrl);
expect(foundUser?.phone).toBe(createUserDto.phone);
expect(foundUser?.role).toBe(createUserDto.role);
expect(foundUser?.status).toBe('active');
expect(foundUser?.createdAt).toBeDefined();
expect(foundUser?.updatedAt).toBeDefined();
// 清理
// if (foundUser) await repository.remove(foundUser);
});
});
});