feat: 优化项目目录结构
This commit is contained in:
25
apps/backend/.eslintrc.js
Normal file
25
apps/backend/.eslintrc.js
Normal file
@@ -0,0 +1,25 @@
|
||||
module.exports = {
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
project: 'tsconfig.json',
|
||||
tsconfigRootDir: __dirname,
|
||||
sourceType: 'module',
|
||||
},
|
||||
plugins: ['@typescript-eslint/eslint-plugin'],
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:prettier/recommended',
|
||||
],
|
||||
root: true,
|
||||
env: {
|
||||
node: true,
|
||||
jest: true,
|
||||
},
|
||||
ignorePatterns: ['.eslintrc.js'],
|
||||
rules: {
|
||||
'@typescript-eslint/interface-name-prefix': 'off',
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
};
|
||||
56
apps/backend/.gitignore
vendored
Normal file
56
apps/backend/.gitignore
vendored
Normal file
@@ -0,0 +1,56 @@
|
||||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Tests
|
||||
/coverage
|
||||
/.nyc_output
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# temp directory
|
||||
.temp
|
||||
.tmp
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
4
apps/backend/.prettierrc
Normal file
4
apps/backend/.prettierrc
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
99
apps/backend/README.md
Normal file
99
apps/backend/README.md
Normal file
@@ -0,0 +1,99 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
|
||||
## Project setup
|
||||
|
||||
```bash
|
||||
$ pnpm install
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ pnpm run start
|
||||
|
||||
# watch mode
|
||||
$ pnpm run start:dev
|
||||
|
||||
# production mode
|
||||
$ pnpm run start:prod
|
||||
```
|
||||
|
||||
## Run tests
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ pnpm run test
|
||||
|
||||
# e2e tests
|
||||
$ pnpm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ pnpm run test:cov
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
|
||||
```bash
|
||||
$ pnpm install -g mau
|
||||
$ mau deploy
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
8
apps/backend/nest-cli.json
Normal file
8
apps/backend/nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
91
apps/backend/package.json
Normal file
91
apps/backend/package.json
Normal file
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"name": "tone-page-server",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@alicloud/credentials": "^2.4.3",
|
||||
"@alicloud/dm20151123": "1.2.6",
|
||||
"@alicloud/dysmsapi20170525": "4.1.0",
|
||||
"@alicloud/openapi-client": "^0.4.14",
|
||||
"@alicloud/tea-util": "^1.4.10",
|
||||
"@nestjs/common": "^10.0.0",
|
||||
"@nestjs/config": "^4.0.2",
|
||||
"@nestjs/core": "^10.0.0",
|
||||
"@nestjs/jwt": "^11.0.0",
|
||||
"@nestjs/mapped-types": "*",
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^10.0.0",
|
||||
"@nestjs/throttler": "^6.4.0",
|
||||
"@nestjs/typeorm": "^11.0.0",
|
||||
"@types/ali-oss": "^6.16.11",
|
||||
"ali-oss": "^6.23.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.2",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"pg": "^8.15.6",
|
||||
"reflect-metadata": "^0.2.0",
|
||||
"rxjs": "^7.8.1",
|
||||
"typeorm": "^0.3.22",
|
||||
"uuid": "^11.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^10.0.0",
|
||||
"@nestjs/schematics": "^10.0.0",
|
||||
"@nestjs/testing": "^10.0.0",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^29.5.2",
|
||||
"@types/node": "^20.3.1",
|
||||
"@types/passport-jwt": "^4.0.1",
|
||||
"@types/supertest": "^6.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.0.0",
|
||||
"@typescript-eslint/parser": "^8.0.0",
|
||||
"eslint": "^8.0.0",
|
||||
"eslint-config-prettier": "^9.0.0",
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"jest": "^29.5.0",
|
||||
"prettier": "^3.0.0",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.1.0",
|
||||
"ts-loader": "^9.4.3",
|
||||
"ts-node": "^10.9.1",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.1.3"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
7218
apps/backend/pnpm-lock.yaml
generated
Normal file
7218
apps/backend/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
18
apps/backend/src/admin/admin.controller.spec.ts
Normal file
18
apps/backend/src/admin/admin.controller.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AdminController } from './admin.controller';
|
||||
|
||||
describe('AdminController', () => {
|
||||
let controller: AdminController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AdminController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AdminController>(AdminController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
4
apps/backend/src/admin/admin.controller.ts
Normal file
4
apps/backend/src/admin/admin.controller.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { Controller } from '@nestjs/common';
|
||||
|
||||
@Controller('admin')
|
||||
export class AdminController {}
|
||||
26
apps/backend/src/admin/admin.module.ts
Normal file
26
apps/backend/src/admin/admin.module.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AdminController } from './admin.controller';
|
||||
import { AdminUserController } from './controller/admin-user.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { User } from 'src/user/entities/user.entity';
|
||||
import { UserModule } from 'src/user/user.module';
|
||||
import { AdminWebResourceController } from './controller/web/admin-web-resource.controller';
|
||||
import { AdminWebBlogController } from './controller/web/admin-web-blog.controller';
|
||||
import { ResourceModule } from 'src/resource/resource.module';
|
||||
import { BlogModule } from 'src/blog/blog.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([User]),
|
||||
UserModule,
|
||||
ResourceModule,
|
||||
BlogModule,
|
||||
],
|
||||
controllers: [
|
||||
AdminController,
|
||||
AdminUserController,
|
||||
AdminWebResourceController,
|
||||
AdminWebBlogController,
|
||||
],
|
||||
})
|
||||
export class AdminModule {}
|
||||
83
apps/backend/src/admin/controller/admin-user.controller.ts
Normal file
83
apps/backend/src/admin/controller/admin-user.controller.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ListDto } from '../dto/admin-user/list.dto';
|
||||
import { CreateDto } from '../dto/admin-user/create.dto';
|
||||
import { UserService } from 'src/user/user.service';
|
||||
import { UpdateDto } from '../dto/admin-user/update.dto';
|
||||
import { UpdatePasswordDto } from '../dto/admin-user/update-password.dto';
|
||||
import { RemoveUserDto } from '../dto/admin-user/remove.dto';
|
||||
import { RolesGuard } from 'src/common/guard/roles.guard';
|
||||
import { Roles } from 'src/common/decorators/role.decorator';
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Controller('admin/user')
|
||||
@UseGuards(AuthGuard('jwt'), RolesGuard)
|
||||
@Roles(Role.Admin)
|
||||
export class AdminUserController {
|
||||
constructor(private readonly userService: UserService) {}
|
||||
|
||||
@Get()
|
||||
async list(@Query() listDto: ListDto) {
|
||||
return this.userService.list(listDto.page, listDto.pageSize);
|
||||
}
|
||||
|
||||
@Get(':userId')
|
||||
async get(
|
||||
@Param('userId', new ParseUUIDPipe({ version: '4' })) userId: string,
|
||||
) {
|
||||
return this.userService.findOne({ userId });
|
||||
}
|
||||
|
||||
@Post()
|
||||
async create(@Body() createDto: CreateDto) {
|
||||
return this.userService.create({
|
||||
...createDto,
|
||||
...(createDto.password &&
|
||||
(() => {
|
||||
const salt = this.userService.generateSalt();
|
||||
return {
|
||||
salt,
|
||||
password_hash: this.userService.hashPassword(
|
||||
createDto.password,
|
||||
salt,
|
||||
),
|
||||
};
|
||||
})()),
|
||||
});
|
||||
}
|
||||
|
||||
@Put(':userId')
|
||||
async update(
|
||||
@Param('userId', new ParseUUIDPipe({ version: '4' })) userId: string,
|
||||
@Body() updateDto: UpdateDto,
|
||||
) {
|
||||
return this.userService.update(userId, updateDto);
|
||||
}
|
||||
|
||||
@Delete(':userId')
|
||||
async delete(
|
||||
@Param('userId', new ParseUUIDPipe({ version: '4' })) userId: string,
|
||||
@Query() dto: RemoveUserDto,
|
||||
) {
|
||||
return this.userService.delete(userId, dto.soft);
|
||||
}
|
||||
|
||||
@Post(':userId/password')
|
||||
async setPassword(
|
||||
@Param('userId', new ParseUUIDPipe({ version: '4' })) userId: string,
|
||||
@Body() updatePasswordDto: UpdatePasswordDto,
|
||||
) {
|
||||
return this.userService.setPassword(userId, updatePasswordDto.password);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { CreateBlogDto } from 'src/admin/dto/admin-web/create-blog.dto';
|
||||
import { SetBlogPasswordDto } from 'src/admin/dto/admin-web/set-blog-password.dto';
|
||||
import { UpdateBlogDto } from 'src/admin/dto/admin-web/update-blog.dto';
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
import { BlogService } from 'src/blog/blog.service';
|
||||
import { Roles } from 'src/common/decorators/role.decorator';
|
||||
import { RolesGuard } from 'src/common/guard/roles.guard';
|
||||
|
||||
@Controller('/admin/web/blog')
|
||||
@UseGuards(AuthGuard('jwt'), RolesGuard)
|
||||
@Roles(Role.Admin)
|
||||
export class AdminWebBlogController {
|
||||
constructor(private readonly adminWebBlogService: BlogService) {}
|
||||
|
||||
@Get()
|
||||
async list() {
|
||||
return this.adminWebBlogService.list({
|
||||
withAll: true,
|
||||
});
|
||||
}
|
||||
|
||||
@Post()
|
||||
async create(@Body() dto: CreateBlogDto) {
|
||||
return this.adminWebBlogService.create(dto);
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
async update(
|
||||
@Param('id', new ParseUUIDPipe({ version: '4' })) id: string,
|
||||
@Body() dto: UpdateBlogDto,
|
||||
) {
|
||||
return this.adminWebBlogService.update(id, dto);
|
||||
}
|
||||
|
||||
@Post(':id/password')
|
||||
async setPassword(
|
||||
@Param('id', new ParseUUIDPipe({ version: '4' })) id: string,
|
||||
@Body() dto: SetBlogPasswordDto,
|
||||
) {
|
||||
return this.adminWebBlogService.setPassword(id, dto.password);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async get(@Param('id', new ParseUUIDPipe({ version: '4' })) id: string) {
|
||||
return this.adminWebBlogService.findById(id);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
async remove(@Param('id', new ParseUUIDPipe({ version: '4' })) id: string) {
|
||||
return this.adminWebBlogService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { CreateResourceDto } from 'src/admin/dto/admin-web/create-resource.dto';
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
import { Roles } from 'src/common/decorators/role.decorator';
|
||||
import { RolesGuard } from 'src/common/guard/roles.guard';
|
||||
import { ResourceService } from 'src/resource/resource.service';
|
||||
|
||||
@Controller('/admin/web/resource')
|
||||
@UseGuards(AuthGuard('jwt'), RolesGuard)
|
||||
@Roles(Role.Admin)
|
||||
export class AdminWebResourceController {
|
||||
constructor(private readonly resourceService: ResourceService) {}
|
||||
|
||||
@Get()
|
||||
async list() {
|
||||
return this.resourceService.findAll();
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async get(@Param('id', new ParseUUIDPipe({ version: '4' })) id: string) {
|
||||
return this.resourceService.findById(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
async create(@Body() data: CreateResourceDto) {
|
||||
return this.resourceService.create(data);
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
async update(
|
||||
@Param('id', new ParseUUIDPipe({ version: '4' })) id: string,
|
||||
@Body() data: CreateResourceDto,
|
||||
) {
|
||||
return this.resourceService.update(id, data);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
async delete(@Param('id', new ParseUUIDPipe({ version: '4' })) id: string) {
|
||||
return this.resourceService.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { IsString } from 'class-validator';
|
||||
|
||||
export class CreatePermissionDto {
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@IsString()
|
||||
description: string;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ArrayMinSize, IsArray, IsUUID } from 'class-validator';
|
||||
|
||||
export class DeleteRolePermissionsDto {
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@IsUUID('4', { each: true })
|
||||
permissionIds: string[];
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ArrayMinSize, IsArray, IsUUID } from 'class-validator';
|
||||
|
||||
export class SetRolePermissionsDto {
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@IsUUID('4', { each: true })
|
||||
permissionIds: string[];
|
||||
}
|
||||
9
apps/backend/src/admin/dto/admin-role/create-role.dto.ts
Normal file
9
apps/backend/src/admin/dto/admin-role/create-role.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { IsString } from 'class-validator';
|
||||
|
||||
export class CreateRoleDto {
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@IsString()
|
||||
localName: string;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { IsBoolean, IsDateString, IsOptional, IsUUID } from 'class-validator';
|
||||
|
||||
export class CreateUserRoleDto {
|
||||
@IsUUID('4')
|
||||
roleId: string;
|
||||
|
||||
@IsBoolean()
|
||||
isEnabled: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
expiredAt?: Date;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { IsUUID } from 'class-validator';
|
||||
|
||||
export class DeleteUserRoleDto {
|
||||
@IsUUID('4')
|
||||
roleId: string;
|
||||
}
|
||||
32
apps/backend/src/admin/dto/admin-user/create.dto.ts
Normal file
32
apps/backend/src/admin/dto/admin-user/create.dto.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { IsString, Length, Matches, ValidateIf } from 'class-validator';
|
||||
|
||||
export class CreateDto {
|
||||
@ValidateIf((o) => o.username !== null)
|
||||
@IsString({ message: '用户名不得为空' })
|
||||
@Length(4, 32, { message: '用户名长度只能为4~32' })
|
||||
username: string | null;
|
||||
|
||||
@ValidateIf((o) => o.nickname !== null)
|
||||
@IsString({ message: '昵称不得为空' })
|
||||
@Length(1, 30, { message: '昵称长度只能为1~30' })
|
||||
nickname: string | null;
|
||||
|
||||
@ValidateIf((o) => o.email !== null)
|
||||
@IsString({ message: '邮箱不得为空' })
|
||||
@Length(6, 254, { message: '邮箱长度只能为6~254' })
|
||||
email: string | null;
|
||||
|
||||
@ValidateIf((o) => o.phone !== null)
|
||||
@IsString({ message: '手机号不得为空' })
|
||||
@Length(11, 11, { message: '手机号长度只能为11' })
|
||||
phone: string | null;
|
||||
|
||||
@ValidateIf((o) => o.password !== null)
|
||||
@IsString({ message: '密码不得为空' })
|
||||
@Length(6, 32, { message: '密码长度只能为6~32' })
|
||||
@Matches(
|
||||
/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d!@#$%^&*()_+\-=\[\]{};:'",.<>/?]{6,32}$/,
|
||||
{ message: '密码必须包含字母和数字,且长度在6~32之间' },
|
||||
)
|
||||
password: string | null;
|
||||
}
|
||||
3
apps/backend/src/admin/dto/admin-user/list.dto.ts
Normal file
3
apps/backend/src/admin/dto/admin-user/list.dto.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { PaginationDto } from '../common/pagination.dto';
|
||||
|
||||
export class ListDto extends PaginationDto {}
|
||||
8
apps/backend/src/admin/dto/admin-user/remove.dto.ts
Normal file
8
apps/backend/src/admin/dto/admin-user/remove.dto.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Transform } from 'class-transformer';
|
||||
import { IsBoolean } from 'class-validator';
|
||||
|
||||
export class RemoveUserDto {
|
||||
@Transform(({ value }) => value === 'true')
|
||||
@IsBoolean({ message: '需指定删除类型' })
|
||||
soft: boolean;
|
||||
}
|
||||
11
apps/backend/src/admin/dto/admin-user/update-password.dto.ts
Normal file
11
apps/backend/src/admin/dto/admin-user/update-password.dto.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { IsString, Length, Matches } from 'class-validator';
|
||||
|
||||
export class UpdatePasswordDto {
|
||||
@IsString({ message: '密码不得为空' })
|
||||
@Length(6, 32, { message: '密码长度只能为6~32' })
|
||||
@Matches(
|
||||
/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d!@#$%^&*()_+\-=\[\]{};:'",.<>/?]{6,32}$/,
|
||||
{ message: '密码必须包含字母和数字,且长度在6~32之间' },
|
||||
)
|
||||
password: string;
|
||||
}
|
||||
35
apps/backend/src/admin/dto/admin-user/update.dto.ts
Normal file
35
apps/backend/src/admin/dto/admin-user/update.dto.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
IsEmail,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Length,
|
||||
Matches,
|
||||
} from 'class-validator';
|
||||
|
||||
export class UpdateDto {
|
||||
@IsString({ message: '用户名不得为空' })
|
||||
@Length(4, 32, { message: '用户名长度只能为4~32' })
|
||||
username: string;
|
||||
|
||||
@IsString({ message: '昵称不得为空' })
|
||||
@Length(1, 30, { message: '昵称长度只能为1~30' })
|
||||
nickname: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: '请输入有效的邮箱地址', always: false })
|
||||
@Length(6, 254, {
|
||||
message: '邮箱长度只能为6~254',
|
||||
// 仅在值不为 null 或 undefined 时验证
|
||||
always: false,
|
||||
})
|
||||
email?: string;
|
||||
|
||||
@IsOptional() // 标记字段为可选
|
||||
@IsString({ message: '手机号不得为空', always: false })
|
||||
@Matches(/^1[3456789]\d{9}$/, {
|
||||
message: '请输入有效的手机号码',
|
||||
// 仅在值不为 null 或 undefined 时验证
|
||||
always: false,
|
||||
})
|
||||
phone?: string;
|
||||
}
|
||||
19
apps/backend/src/admin/dto/admin-web/create-blog.dto.ts
Normal file
19
apps/backend/src/admin/dto/admin-web/create-blog.dto.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { IsEnum, IsString } from 'class-validator';
|
||||
import { BlogPermission } from 'src/blog/blog.permission.enum';
|
||||
|
||||
export class CreateBlogDto {
|
||||
@IsString()
|
||||
title: string;
|
||||
|
||||
@IsString()
|
||||
description: string;
|
||||
|
||||
@IsString()
|
||||
contentUrl: string;
|
||||
|
||||
@IsEnum(BlogPermission, { each: true, message: '请求类型错误' })
|
||||
permissions: BlogPermission[];
|
||||
|
||||
@IsString()
|
||||
password: string; // 允许空串
|
||||
}
|
||||
28
apps/backend/src/admin/dto/admin-web/create-resource.dto.ts
Normal file
28
apps/backend/src/admin/dto/admin-web/create-resource.dto.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsString, ValidateNested } from 'class-validator';
|
||||
|
||||
class ResourceTagDto {
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@IsString()
|
||||
type: string;
|
||||
}
|
||||
|
||||
export class CreateResourceDto {
|
||||
@IsString()
|
||||
title: string;
|
||||
|
||||
@IsString()
|
||||
description: string;
|
||||
|
||||
@IsString()
|
||||
imageUrl: string;
|
||||
|
||||
@IsString()
|
||||
link: string;
|
||||
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => ResourceTagDto)
|
||||
tags: ResourceTagDto[];
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { IsString } from 'class-validator';
|
||||
|
||||
export class SetBlogPasswordDto {
|
||||
@IsString()
|
||||
password: string;
|
||||
}
|
||||
16
apps/backend/src/admin/dto/admin-web/update-blog.dto.ts
Normal file
16
apps/backend/src/admin/dto/admin-web/update-blog.dto.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { IsEnum, IsString } from 'class-validator';
|
||||
import { BlogPermission } from 'src/blog/blog.permission.enum';
|
||||
|
||||
export class UpdateBlogDto {
|
||||
@IsString()
|
||||
title: string;
|
||||
|
||||
@IsString()
|
||||
description: string;
|
||||
|
||||
@IsString()
|
||||
contentUrl: string;
|
||||
|
||||
@IsEnum(BlogPermission, { each: true, message: '请求类型错误' })
|
||||
permissions: BlogPermission[];
|
||||
}
|
||||
16
apps/backend/src/admin/dto/common/pagination.dto.ts
Normal file
16
apps/backend/src/admin/dto/common/pagination.dto.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsInt, IsOptional, Min } from 'class-validator';
|
||||
|
||||
export class PaginationDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page?: number = 1;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
pageSize?: number = 20;
|
||||
}
|
||||
22
apps/backend/src/app.controller.spec.ts
Normal file
22
apps/backend/src/app.controller.spec.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
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!');
|
||||
});
|
||||
});
|
||||
});
|
||||
12
apps/backend/src/app.controller.ts
Normal file
12
apps/backend/src/app.controller.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
52
apps/backend/src/app.module.ts
Normal file
52
apps/backend/src/app.module.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { UserModule } from './user/user.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { VerificationModule } from './verification/verification.module';
|
||||
import { NotificationModule } from './notification/notification.module';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { ResourceModule } from './resource/resource.module';
|
||||
import { BlogModule } from './blog/blog.module';
|
||||
import { AdminModule } from './admin/admin.module';
|
||||
import { OssModule } from './oss/oss.module';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
TypeOrmModule.forRoot({
|
||||
type: 'postgres',
|
||||
host: process.env.DATABASE_HOST,
|
||||
port: parseInt(process.env.DATABASE_PORT, 10) || 5432,
|
||||
username: process.env.DATABASE_USERNAME,
|
||||
password: process.env.DATABASE_PASSWORD,
|
||||
database: process.env.DATABASE_NAME,
|
||||
autoLoadEntities: true,
|
||||
entities: [],
|
||||
synchronize: process.env.NODE_ENV !== 'production', // Set to false in production
|
||||
}),
|
||||
PassportModule.register({ defaultStrategy: 'jwt' }),
|
||||
ThrottlerModule.forRoot({
|
||||
throttlers: [
|
||||
{
|
||||
limit: 1000,
|
||||
ttl: 60000, // 1 minute
|
||||
},
|
||||
],
|
||||
}),
|
||||
UserModule,
|
||||
AuthModule,
|
||||
VerificationModule,
|
||||
NotificationModule,
|
||||
ResourceModule,
|
||||
BlogModule,
|
||||
AdminModule,
|
||||
OssModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
})
|
||||
export class AppModule {}
|
||||
8
apps/backend/src/app.service.ts
Normal file
8
apps/backend/src/app.service.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
18
apps/backend/src/auth/auth.controller.spec.ts
Normal file
18
apps/backend/src/auth/auth.controller.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthController } from './auth.controller';
|
||||
|
||||
describe('AuthController', () => {
|
||||
let controller: AuthController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AuthController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AuthController>(AuthController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
46
apps/backend/src/auth/auth.controller.ts
Normal file
46
apps/backend/src/auth/auth.controller.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Post,
|
||||
Request,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { UserSessionService } from 'src/user/services/user-session.service';
|
||||
import { Throttle, ThrottlerGuard } from '@nestjs/throttler';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private readonly authService: AuthService,
|
||||
private readonly userSessionService: UserSessionService,
|
||||
) {}
|
||||
|
||||
@Post('login')
|
||||
@UseGuards(ThrottlerGuard)
|
||||
@Throttle({ default: { limit: 20, ttl: 60000 } })
|
||||
async login(@Body() loginDto: LoginDto) {
|
||||
switch (loginDto.type) {
|
||||
case 'password':
|
||||
return this.authService.loginWithPassword(loginDto);
|
||||
case 'phone':
|
||||
return this.authService.loginWithPhone(loginDto);
|
||||
case 'email':
|
||||
return this.authService.loginWithEmail(loginDto);
|
||||
default:
|
||||
throw new BadRequestException('服务器错误');
|
||||
}
|
||||
}
|
||||
|
||||
@UseGuards(AuthGuard('jwt'))
|
||||
@Post('logout')
|
||||
async logout(@Request() req) {
|
||||
const { userId, sessionId } = req.user;
|
||||
await this.userSessionService.invalidateSession(userId, sessionId);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
36
apps/backend/src/auth/auth.module.ts
Normal file
36
apps/backend/src/auth/auth.module.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UserModule } from 'src/user/user.module';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { UserSession } from 'src/user/entities/user-session.entity';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { VerificationModule } from 'src/verification/verification.module';
|
||||
import { OptionalAuthGuard } from './strategies/OptionalAuthGuard';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule,
|
||||
forwardRef(() => UserModule),
|
||||
TypeOrmModule.forFeature([UserSession]),
|
||||
PassportModule.register({ defaultStrategy: 'jwt' }),
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => ({
|
||||
secret: configService.get<string>('JWT_SECRET', 'tone-page'),
|
||||
signOptions: {
|
||||
expiresIn: configService.get<string>('JWT_EXPIRES_IN', '1d'),
|
||||
},
|
||||
}),
|
||||
}),
|
||||
VerificationModule,
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtStrategy, OptionalAuthGuard],
|
||||
exports: [PassportModule, JwtStrategy, AuthService, OptionalAuthGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
18
apps/backend/src/auth/auth.service.spec.ts
Normal file
18
apps/backend/src/auth/auth.service.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [AuthService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AuthService>(AuthService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
155
apps/backend/src/auth/auth.service.ts
Normal file
155
apps/backend/src/auth/auth.service.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import { createHash } from 'crypto';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { UserService } from 'src/user/user.service';
|
||||
import { User } from 'src/user/entities/user.entity';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { UserSessionService } from 'src/user/services/user-session.service';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { VerificationService } from 'src/verification/verification.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly userService: UserService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly userSessionService: UserSessionService,
|
||||
private readonly verificationService: VerificationService,
|
||||
) {}
|
||||
|
||||
async loginWithPassword(loginDto: LoginDto) {
|
||||
const { account, password } = loginDto;
|
||||
// 依次使用邮箱登录、手机号、账号
|
||||
const user = await this.userService.findOne(
|
||||
[{ email: account }, { phone: account }, { username: account }],
|
||||
{
|
||||
withDeleted: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (user && user.deletedAt !== null) {
|
||||
throw new BadRequestException('该账号注销中');
|
||||
}
|
||||
|
||||
if (user === null || !user.password_hash || !user.salt) {
|
||||
throw new BadRequestException('账户或密码错误');
|
||||
}
|
||||
|
||||
// 判断密码是否正确
|
||||
const hashedPassword = this.hashPassword(password, user.salt);
|
||||
if (hashedPassword !== user.password_hash) {
|
||||
throw new BadRequestException('账户或密码错误');
|
||||
}
|
||||
|
||||
// 登录成功,颁发token
|
||||
return {
|
||||
token: await this.generateToken(user),
|
||||
};
|
||||
}
|
||||
|
||||
async loginWithPhone(loginDto: LoginDto) {
|
||||
const { phone, code } = loginDto;
|
||||
// 先判断验证码是否正确
|
||||
const isValid = this.verificationService.verifyPhoneCode(
|
||||
phone,
|
||||
code,
|
||||
'login',
|
||||
);
|
||||
switch (isValid) {
|
||||
case 0:
|
||||
break;
|
||||
case -1:
|
||||
throw new BadRequestException('验证码已过期');
|
||||
case -2:
|
||||
throw new BadRequestException('验证码错误');
|
||||
case -3:
|
||||
throw new BadRequestException('验证码已失效');
|
||||
default:
|
||||
throw new BadRequestException('验证码错误');
|
||||
}
|
||||
|
||||
// 判断用户是否存在,若不存在则进行注册
|
||||
let user = await this.userService.findOne({ phone }, { withDeleted: true });
|
||||
if (user && user.deletedAt !== null) {
|
||||
throw new BadRequestException('该账号注销中,请使用其他手机号');
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
// 执行注册操作
|
||||
user = await this.userService.create({ phone: phone });
|
||||
}
|
||||
|
||||
if (!user || !user.userId) {
|
||||
// 注册失败或用户信息错误
|
||||
throw new BadRequestException('请求失败,请稍后再试');
|
||||
}
|
||||
|
||||
// 登录,颁发token
|
||||
return {
|
||||
token: await this.generateToken(user),
|
||||
};
|
||||
}
|
||||
|
||||
async loginWithEmail(loginDto: LoginDto) {
|
||||
const { email, code } = loginDto;
|
||||
// 先判断验证码是否正确
|
||||
const isValid = this.verificationService.verifyEmailCode(
|
||||
email,
|
||||
code,
|
||||
'login',
|
||||
);
|
||||
switch (isValid) {
|
||||
case 0:
|
||||
break;
|
||||
case -1:
|
||||
throw new BadRequestException('验证码已过期,请重新获取');
|
||||
case -2:
|
||||
throw new BadRequestException('验证码错误');
|
||||
case -3:
|
||||
throw new BadRequestException('验证码已失效,请重新获取');
|
||||
default:
|
||||
throw new BadRequestException('验证码错误,请稍后再试');
|
||||
}
|
||||
|
||||
// 判断用户是否存在,若不存在则进行注册
|
||||
let user = await this.userService.findOne({ email }, { withDeleted: true });
|
||||
if (user && user.deletedAt !== null) {
|
||||
throw new BadRequestException('该账号注销中,请使用其他邮箱');
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
// 执行注册操作
|
||||
user = await this.userService.create({ email: email });
|
||||
}
|
||||
|
||||
if (!user || !user.userId) {
|
||||
// 注册失败或用户信息错误
|
||||
throw new BadRequestException('请求失败,请稍后再试');
|
||||
}
|
||||
|
||||
// 登录,颁发token
|
||||
return {
|
||||
token: await this.generateToken(user),
|
||||
};
|
||||
}
|
||||
|
||||
private hashPassword(password: string, salt: string): string {
|
||||
return createHash('sha256').update(`${password}${salt}`).digest('hex');
|
||||
}
|
||||
|
||||
private async generateToken(user: User) {
|
||||
const payload = {
|
||||
userId: user.userId,
|
||||
sessionId: uuidv4(),
|
||||
};
|
||||
|
||||
// 存储
|
||||
await this.userSessionService.createSession(
|
||||
payload.userId,
|
||||
payload.sessionId,
|
||||
);
|
||||
|
||||
// 颁发token
|
||||
return this.jwtService.sign(payload);
|
||||
}
|
||||
}
|
||||
31
apps/backend/src/auth/dto/login.dto.ts
Normal file
31
apps/backend/src/auth/dto/login.dto.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { IsEnum, IsString, Length, ValidateIf } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@IsEnum(['password', 'phone', 'email'], { message: '请求类型错误' })
|
||||
type: 'password' | 'phone' | 'email';
|
||||
|
||||
@ValidateIf((o) => o.type === 'password')
|
||||
@IsString({ message: '账户必须输入' })
|
||||
@Length(1, 254, { message: '账户异常' }) // 用户名、邮箱、手机号
|
||||
account?: string;
|
||||
|
||||
@ValidateIf((o) => o.type === 'password')
|
||||
@IsString({ message: '密码必须输入' })
|
||||
@Length(6, 32, { message: '密码异常' }) // 6-32位
|
||||
password?: string;
|
||||
|
||||
@ValidateIf((o) => o.type === 'phone')
|
||||
@IsString({ message: '手机号必须输入' })
|
||||
@Length(11, 11, { message: '手机号异常' }) // 中国大陆,11位数字
|
||||
phone?: string;
|
||||
|
||||
@ValidateIf((o) => o.type === 'email')
|
||||
@IsString({ message: '邮箱必须输入' })
|
||||
@Length(6, 254, { message: '邮箱异常' }) // RFC 5321
|
||||
email?: string;
|
||||
|
||||
@ValidateIf((o) => o.type === 'phone' || o.type === 'email')
|
||||
@IsString({ message: '验证码必须输入' })
|
||||
@Length(6, 6, { message: '验证码异常' }) // 6位数字
|
||||
code?: string;
|
||||
}
|
||||
3
apps/backend/src/auth/role.enum.ts
Normal file
3
apps/backend/src/auth/role.enum.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export enum Role {
|
||||
Admin = 'admin',
|
||||
}
|
||||
28
apps/backend/src/auth/strategies/OptionalAuthGuard.ts
Normal file
28
apps/backend/src/auth/strategies/OptionalAuthGuard.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class OptionalAuthGuard extends AuthGuard('jwt') implements CanActivate {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
try {
|
||||
await super.canActivate(context);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('OptionalAuthGuard error:', error);
|
||||
return true; // 如果验证失败,仍然允许访问
|
||||
}
|
||||
}
|
||||
|
||||
handleRequest<TUser = any>(
|
||||
err: any,
|
||||
user: any,
|
||||
// info: any,
|
||||
// context: ExecutionContext,
|
||||
// status?: any,
|
||||
): TUser {
|
||||
if (err || !user) {
|
||||
return null; // 如果没有用户信息,返回null
|
||||
}
|
||||
return user; // 如果有用户信息,返回用户对象
|
||||
}
|
||||
}
|
||||
47
apps/backend/src/auth/strategies/jwt.strategy.ts
Normal file
47
apps/backend/src/auth/strategies/jwt.strategy.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { UserSessionService } from 'src/user/services/user-session.service';
|
||||
import { UserService } from 'src/user/user.service';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
constructor(
|
||||
private readonly userService: UserService,
|
||||
private readonly userSessionService: UserSessionService,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: configService.get<string>('JWT_SECRET', 'tone-page'),
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: any) {
|
||||
const { userId, sessionId } = payload ?? {};
|
||||
|
||||
const isValidSession = await this.userSessionService.isSessionValid(
|
||||
userId,
|
||||
sessionId,
|
||||
);
|
||||
if (!isValidSession) {
|
||||
throw new UnauthorizedException('登录凭证已过期,请重新登录');
|
||||
}
|
||||
|
||||
const user = await this.userService.findById(userId);
|
||||
if (!user) {
|
||||
throw new BadRequestException('用户不存在');
|
||||
}
|
||||
|
||||
return {
|
||||
...user,
|
||||
sessionId,
|
||||
};
|
||||
}
|
||||
}
|
||||
18
apps/backend/src/blog/blog.controller.spec.ts
Normal file
18
apps/backend/src/blog/blog.controller.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { BlogController } from './blog.controller';
|
||||
|
||||
describe('BlogController', () => {
|
||||
let controller: BlogController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [BlogController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<BlogController>(BlogController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
137
apps/backend/src/blog/blog.controller.ts
Normal file
137
apps/backend/src/blog/blog.controller.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { BlogService } from './blog.service';
|
||||
import { OptionalAuthGuard } from 'src/auth/strategies/OptionalAuthGuard';
|
||||
import { UserService } from 'src/user/user.service';
|
||||
import { createBlogCommentDto } from './dto/create.blogcomment.dto';
|
||||
import { Throttle, ThrottlerGuard } from '@nestjs/throttler';
|
||||
import { BlogPermission } from './blog.permission.enum';
|
||||
|
||||
@Controller('blog')
|
||||
export class BlogController {
|
||||
constructor(
|
||||
private readonly blogService: BlogService,
|
||||
private readonly userService: UserService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
getBlogs() {
|
||||
return this.blogService.list();
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async getBlog(
|
||||
@Param('id', new ParseUUIDPipe({ version: '4' })) id: string,
|
||||
@Query('p') password?: string,
|
||||
) {
|
||||
const blog = await this.blogService.findById(id);
|
||||
if (!blog) throw new BadRequestException('文章不存在或无权限访问');
|
||||
|
||||
if (!blog.permissions.includes(BlogPermission.Public)) {
|
||||
// 无公开权限,则进一步检查是否有密码保护
|
||||
if (!blog.permissions.includes(BlogPermission.ByPassword)) {
|
||||
throw new BadRequestException('文章不存在或无权限访问');
|
||||
} else {
|
||||
// 判断密码是否正确
|
||||
if (
|
||||
!password ||
|
||||
this.blogService.hashPassword(password) !== blog.password_hash
|
||||
) {
|
||||
throw new BadRequestException('文章不存在或无权限访问');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const blogDataRes = await fetch(`${blog.contentUrl}`);
|
||||
const blogContent = await blogDataRes.text();
|
||||
|
||||
await this.blogService.incrementViewCount(id);
|
||||
return {
|
||||
id: blog.id,
|
||||
title: blog.title,
|
||||
createdAt: blog.createdAt,
|
||||
content: blogContent,
|
||||
};
|
||||
}
|
||||
|
||||
@Get(':id/comments')
|
||||
async getBlogComments(
|
||||
@Param('id', new ParseUUIDPipe({ version: '4' })) id: string,
|
||||
) {
|
||||
const blog = await this.blogService.findById(id);
|
||||
if (!blog) throw new BadRequestException('文章不存在');
|
||||
|
||||
/** @todo 对文章可读性进行更详细的判定 */
|
||||
|
||||
if (
|
||||
!blog.permissions.includes(BlogPermission.Public) &&
|
||||
!blog.permissions.includes(BlogPermission.ByPassword)
|
||||
) {
|
||||
throw new BadRequestException('文章不存在或未公开');
|
||||
}
|
||||
|
||||
return await this.blogService.getComments(blog);
|
||||
}
|
||||
|
||||
// 该接口允许匿名评论,但仍需验证userId合法性
|
||||
@UseGuards(ThrottlerGuard, OptionalAuthGuard)
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
@Post(':id/comment')
|
||||
async createBlogComment(
|
||||
@Param('id', new ParseUUIDPipe({ version: '4' })) id: string,
|
||||
@Body() commentData: createBlogCommentDto,
|
||||
@Req() req,
|
||||
) {
|
||||
const { userId } = req.user || {};
|
||||
const blog = await this.blogService.findById(id);
|
||||
if (!blog) throw new BadRequestException('文章不存在');
|
||||
|
||||
if (!blog.permissions.includes(BlogPermission.AllowComments)) {
|
||||
throw new BadRequestException('作者关闭了该文章的评论功能');
|
||||
}
|
||||
|
||||
const user = userId ? await this.userService.findById(userId) : null;
|
||||
|
||||
const ip = req.headers['x-forwarded-for'] || req.ip;
|
||||
// 获取IP归属地
|
||||
let address = '未知';
|
||||
if (!['::1'].includes(ip)) {
|
||||
const addressRes = await (
|
||||
await fetch(
|
||||
`https://mesh.if.iqiyi.com/aid/ip/info?version=1.1.1&ip=${ip}`,
|
||||
)
|
||||
).json();
|
||||
if (addressRes?.code == 0) {
|
||||
const country: string = addressRes?.data?.countryCN || '未知';
|
||||
const province: string = addressRes?.data?.provinceCN || '中国';
|
||||
if (country !== '中国') {
|
||||
// 非中国,显示国家
|
||||
address = country;
|
||||
} else {
|
||||
// 中国,显示省份
|
||||
address = province;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const comment = {
|
||||
...commentData,
|
||||
blog,
|
||||
user,
|
||||
ip,
|
||||
address,
|
||||
};
|
||||
|
||||
return await this.blogService.createComment(comment);
|
||||
}
|
||||
}
|
||||
20
apps/backend/src/blog/blog.module.ts
Normal file
20
apps/backend/src/blog/blog.module.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { BlogController } from './blog.controller';
|
||||
import { BlogService } from './blog.service';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Blog } from './entity/Blog.entity';
|
||||
import { BlogComment } from './entity/BlogComment.entity';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
import { UserModule } from 'src/user/user.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Blog, BlogComment]),
|
||||
AuthModule,
|
||||
UserModule,
|
||||
],
|
||||
controllers: [BlogController],
|
||||
providers: [BlogService],
|
||||
exports: [BlogService],
|
||||
})
|
||||
export class BlogModule {}
|
||||
6
apps/backend/src/blog/blog.permission.enum.ts
Normal file
6
apps/backend/src/blog/blog.permission.enum.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export enum BlogPermission {
|
||||
Public = 'Public',
|
||||
ByPassword = 'ByPassword',
|
||||
List = 'List',
|
||||
AllowComments = 'AllowComments',
|
||||
}
|
||||
18
apps/backend/src/blog/blog.service.spec.ts
Normal file
18
apps/backend/src/blog/blog.service.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { BlogService } from './blog.service';
|
||||
|
||||
describe('BlogService', () => {
|
||||
let service: BlogService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [BlogService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<BlogService>(BlogService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
143
apps/backend/src/blog/blog.service.ts
Normal file
143
apps/backend/src/blog/blog.service.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Blog } from './entity/Blog.entity';
|
||||
import { Repository } from 'typeorm';
|
||||
import { BlogComment } from './entity/BlogComment.entity';
|
||||
import { BlogPermission } from './blog.permission.enum';
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
@Injectable()
|
||||
export class BlogService {
|
||||
constructor(
|
||||
@InjectRepository(Blog)
|
||||
private readonly blogRepository: Repository<Blog>,
|
||||
@InjectRepository(BlogComment)
|
||||
private readonly blogCommentRepository: Repository<BlogComment>,
|
||||
) {}
|
||||
|
||||
async list(
|
||||
option: {
|
||||
withAll?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
return (
|
||||
await this.blogRepository.find({
|
||||
order: {
|
||||
createdAt: 'DESC',
|
||||
},
|
||||
})
|
||||
)
|
||||
.filter(
|
||||
(i) => option.withAll || i.permissions.includes(BlogPermission.List),
|
||||
)
|
||||
.map((i) => {
|
||||
if (option.withAll) {
|
||||
return i;
|
||||
}
|
||||
|
||||
const { createdAt, deletedAt, id, title, viewCount } = i;
|
||||
return {
|
||||
createdAt,
|
||||
deletedAt,
|
||||
id,
|
||||
title,
|
||||
viewCount,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async create(dto: Partial<Blog> & { password: string }) {
|
||||
const { password, ...blog } = dto;
|
||||
if (blog.permissions.includes(BlogPermission.ByPassword)) {
|
||||
if (password) {
|
||||
blog.password_hash = createHash('sha256')
|
||||
.update(`${password}`)
|
||||
.digest('hex');
|
||||
}
|
||||
}
|
||||
|
||||
const newBlog = this.blogRepository.create(blog);
|
||||
return this.blogRepository.save(newBlog);
|
||||
}
|
||||
|
||||
async setPassword(id: string, password: string) {
|
||||
const blog = await this.findById(id);
|
||||
if (!blog) {
|
||||
throw new Error('博客不存在');
|
||||
}
|
||||
|
||||
return (
|
||||
(
|
||||
await this.blogRepository.update(id, {
|
||||
...blog,
|
||||
password_hash: this.hashPassword(password),
|
||||
})
|
||||
).affected > 0
|
||||
);
|
||||
}
|
||||
|
||||
async update(id: string, blog: Partial<Blog>) {
|
||||
await this.blogRepository.update(id, blog);
|
||||
return this.blogRepository.findOneBy({ id });
|
||||
}
|
||||
|
||||
async remove(id: string) {
|
||||
const blog = await this.blogRepository.findOneBy({ id });
|
||||
if (!blog) return null;
|
||||
return this.blogRepository.softRemove(blog);
|
||||
}
|
||||
|
||||
async findById(id: string) {
|
||||
return await this.blogRepository.findOneBy({ id });
|
||||
}
|
||||
|
||||
async incrementViewCount(id: string) {
|
||||
await this.blogRepository.increment({ id }, 'viewCount', 1);
|
||||
}
|
||||
|
||||
async getComments(blog: Blog) {
|
||||
const comments = await this.blogCommentRepository.find({
|
||||
where: { blog: { id: blog.id } },
|
||||
relations: ['user'],
|
||||
order: {
|
||||
createdAt: 'DESC',
|
||||
},
|
||||
});
|
||||
|
||||
return comments.map((comment) => {
|
||||
const { user, ...rest } = comment;
|
||||
delete rest.blog;
|
||||
return {
|
||||
...rest,
|
||||
user: user
|
||||
? {
|
||||
userId: user.userId,
|
||||
username: user.username,
|
||||
nickname: user.nickname,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async createComment(comment: Partial<BlogComment>) {
|
||||
const newComment = this.blogCommentRepository.create(comment);
|
||||
const savedComment = await this.blogCommentRepository.save(newComment, {});
|
||||
const { user, ...commentWithoutBlog } = savedComment;
|
||||
delete commentWithoutBlog.blog;
|
||||
return {
|
||||
...commentWithoutBlog,
|
||||
user: user
|
||||
? {
|
||||
userId: user.userId,
|
||||
username: user.username,
|
||||
nickname: user.nickname,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
hashPassword(password: string) {
|
||||
return createHash('sha256').update(`${password}`).digest('hex');
|
||||
}
|
||||
}
|
||||
10
apps/backend/src/blog/dto/create.blogcomment.dto.ts
Normal file
10
apps/backend/src/blog/dto/create.blogcomment.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
|
||||
export class createBlogCommentDto {
|
||||
@IsString({ message: '评论内容不能为空' })
|
||||
content: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID('4', { message: '父评论ID格式错误' })
|
||||
parentId?: string;
|
||||
}
|
||||
50
apps/backend/src/blog/entity/Blog.entity.ts
Normal file
50
apps/backend/src/blog/entity/Blog.entity.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
DeleteDateColumn,
|
||||
Entity,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { BlogComment } from './BlogComment.entity';
|
||||
import { BlogPermission } from '../blog.permission.enum';
|
||||
|
||||
/** @todo 考虑后续将权限的数据类型替换为json,以提高查询效率 */
|
||||
@Entity()
|
||||
export class Blog {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
title: string;
|
||||
|
||||
@Column()
|
||||
description: string;
|
||||
|
||||
@Column()
|
||||
contentUrl: string;
|
||||
|
||||
@Column({ default: 0 })
|
||||
viewCount: number;
|
||||
|
||||
@CreateDateColumn({ precision: 3 })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ precision: 3 })
|
||||
updatedAt: Date;
|
||||
|
||||
@DeleteDateColumn({ precision: 3, nullable: true })
|
||||
deletedAt: Date;
|
||||
|
||||
// 权限
|
||||
@Column('simple-array', { default: '' })
|
||||
permissions: BlogPermission[];
|
||||
|
||||
@Column({ nullable: true })
|
||||
password_hash: string | null;
|
||||
|
||||
// 关系
|
||||
@OneToMany(() => BlogComment, (comment) => comment.blog)
|
||||
comments: BlogComment[];
|
||||
}
|
||||
43
apps/backend/src/blog/entity/BlogComment.entity.ts
Normal file
43
apps/backend/src/blog/entity/BlogComment.entity.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { User } from 'src/user/entities/user.entity';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
DeleteDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
} from 'typeorm';
|
||||
import { Blog } from './Blog.entity';
|
||||
|
||||
@Entity()
|
||||
export class BlogComment {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
content: string;
|
||||
|
||||
@Column()
|
||||
ip: string;
|
||||
|
||||
@Column()
|
||||
address: string;
|
||||
|
||||
@CreateDateColumn({ precision: 3 })
|
||||
createdAt: Date;
|
||||
|
||||
@DeleteDateColumn({ precision: 3, nullable: true })
|
||||
deletedAt: Date;
|
||||
|
||||
@ManyToOne(() => User, { nullable: true })
|
||||
@JoinColumn({ name: 'userId' })
|
||||
user: User | null;
|
||||
|
||||
@ManyToOne(() => Blog)
|
||||
@JoinColumn({ name: 'blogId' })
|
||||
blog: Blog | null;
|
||||
|
||||
@Column({ type: 'uuid', nullable: true })
|
||||
parentId: string | null;
|
||||
}
|
||||
4
apps/backend/src/common/decorators/role.decorator.ts
Normal file
4
apps/backend/src/common/decorators/role.decorator.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
|
||||
export const Roles = (...roles: Role[]) => SetMetadata('roles', roles);
|
||||
37
apps/backend/src/common/guard/roles.guard.ts
Normal file
37
apps/backend/src/common/guard/roles.guard.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
import { User } from 'src/user/entities/user.entity';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<Role[] | undefined>(
|
||||
'roles',
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
|
||||
if (!requiredRoles) return true;
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const user = request.user as User | void;
|
||||
|
||||
if (!user) {
|
||||
throw new BadRequestException('服务器内部错误');
|
||||
}
|
||||
|
||||
if (!requiredRoles.some((role) => user.roles.includes(role))) {
|
||||
throw new ForbiddenException('权限不足');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
24
apps/backend/src/common/interceptors/response.interceptor.ts
Normal file
24
apps/backend/src/common/interceptors/response.interceptor.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
@Injectable()
|
||||
export class ResponseInterceptor implements NestInterceptor {
|
||||
intercept(
|
||||
context: ExecutionContext,
|
||||
next: CallHandler<any>,
|
||||
): Observable<any> | Promise<Observable<any>> {
|
||||
return next.handle().pipe(
|
||||
map((data) => ({
|
||||
statusCode: 200,
|
||||
message: '请求成功',
|
||||
data,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
31
apps/backend/src/main.ts
Normal file
31
apps/backend/src/main.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { BadRequestException, ValidationPipe } from '@nestjs/common';
|
||||
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
transform: true,
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
stopAtFirstError: true,
|
||||
exceptionFactory: (errors) => {
|
||||
const error = errors[0];
|
||||
const firstConstraint = error.constraints
|
||||
? Object.values(error.constraints)[0]
|
||||
: '验证失败';
|
||||
|
||||
throw new BadRequestException({
|
||||
message: firstConstraint,
|
||||
error: 'Bad Request',
|
||||
statusCode: 400,
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.useGlobalInterceptors(new ResponseInterceptor());
|
||||
await app.listen(process.env.PORT ?? 3001);
|
||||
}
|
||||
bootstrap();
|
||||
8
apps/backend/src/notification/notification.module.ts
Normal file
8
apps/backend/src/notification/notification.module.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { NotificationService } from './notification.service';
|
||||
|
||||
@Module({
|
||||
providers: [NotificationService],
|
||||
exports: [NotificationService],
|
||||
})
|
||||
export class NotificationModule {}
|
||||
18
apps/backend/src/notification/notification.service.spec.ts
Normal file
18
apps/backend/src/notification/notification.service.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { NotificationService } from './notification.service';
|
||||
|
||||
describe('NotificationService', () => {
|
||||
let service: NotificationService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [NotificationService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<NotificationService>(NotificationService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
142
apps/backend/src/notification/notification.service.ts
Normal file
142
apps/backend/src/notification/notification.service.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
|
||||
import Dm20151123, * as $Dm20151123 from '@alicloud/dm20151123';
|
||||
import * as $OpenApi from '@alicloud/openapi-client';
|
||||
// import Client, * as $dm from '@alicloud/dm20151123';
|
||||
import * as $Util from '@alicloud/tea-util';
|
||||
import Credential, { Config } from '@alicloud/credentials';
|
||||
|
||||
@Injectable()
|
||||
export class NotificationService {
|
||||
private dm: Dm20151123;
|
||||
|
||||
constructor() {
|
||||
const credentialsConfig = new Config({
|
||||
type: 'access_key',
|
||||
accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
|
||||
accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET,
|
||||
});
|
||||
const credential = new Credential(credentialsConfig);
|
||||
const config = new $OpenApi.Config({ credential });
|
||||
config.endpoint = 'dm.aliyuncs.com';
|
||||
this.dm = new Dm20151123(config);
|
||||
}
|
||||
|
||||
private getMailHtmlBody(option: { type: 'login-verify'; code: string }) {
|
||||
if (option.type === 'login-verify') {
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>特恩的日志 - 登录验证码</title>
|
||||
<style>
|
||||
body { font-family: 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; }
|
||||
.container { max-width: 600px; margin: 0px auto; padding: 20px; }
|
||||
.content { padding: 20px 0; }
|
||||
.code-box {
|
||||
background: #f8f9fa;
|
||||
border: 1px dashed #ccc;
|
||||
padding: 15px;
|
||||
text-align: center;
|
||||
margin: 20px 0;
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
letter-spacing: 5px;
|
||||
color: #e74c3c;
|
||||
}
|
||||
.footer {
|
||||
color: #777;
|
||||
font-size: 12px;
|
||||
border-top: 1px solid #eee;
|
||||
padding-top: 15px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="content">
|
||||
<p>您好!您正在尝试登录【特恩的日志】控制台,验证码如下:</p>
|
||||
|
||||
<div class="code-box">
|
||||
<span id="verificationCode">${option.code}</span>
|
||||
</div>
|
||||
|
||||
<p>请注意:</p>
|
||||
<ul>
|
||||
<li>此验证码 <strong>10分钟内</strong> 有效</li>
|
||||
<li>请勿向任何人透露此验证码</li>
|
||||
<li>如非本人操作,请忽略本邮件</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p>© 2025 TONE(个人) 版权所有</p>
|
||||
<a href="https://beian.miit.gov.cn/">网站备案号:渝ICP备2023009516号-1</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
} else {
|
||||
throw new Error('未配置的模版');
|
||||
}
|
||||
}
|
||||
|
||||
async sendMail(option: {
|
||||
type: 'login-verify';
|
||||
targetMail: string;
|
||||
code: string;
|
||||
}) {
|
||||
const runtime = new $Util.RuntimeOptions({});
|
||||
|
||||
const singleSendMailRequest = new $Dm20151123.SingleSendMailRequest({
|
||||
accountName: 'security@tonesc.cn',
|
||||
addressType: 1,
|
||||
replyToAddress: false,
|
||||
toAddress: `${option.targetMail}`,
|
||||
subject: '【特恩的日志】登陆验证码',
|
||||
htmlBody: this.getMailHtmlBody({
|
||||
type: 'login-verify',
|
||||
code: option.code,
|
||||
}),
|
||||
textBody: '',
|
||||
});
|
||||
|
||||
try {
|
||||
await this.dm.singleSendMailWithOptions(singleSendMailRequest, runtime);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new BadRequestException('邮件发送失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated 短信签名暂未通过
|
||||
*/
|
||||
async sendSMS(phone: string, type: 'login', code: string) {
|
||||
throw new Error(
|
||||
`SMS sending is not implemented yet. Phone: ${phone}, Type: ${type}, Code: ${code}`,
|
||||
);
|
||||
// const config = new $OpenApi.Config({
|
||||
// accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
|
||||
// accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET,
|
||||
// })
|
||||
// config.endpoint = 'dysmsapi.aliyuncs.com';
|
||||
// const client = new Client(config);
|
||||
// const request = new $dysmsapi.SendSmsRequest({});
|
||||
// request.phoneNumbers = phone;
|
||||
// request.signName = (() => {
|
||||
// switch (type) {
|
||||
// case 'login':
|
||||
// return process.env.ALIYUN_SMS_LOGIN_SIGN_NAME;
|
||||
// default:
|
||||
// throw new Error('Unknown SMS type');
|
||||
// }
|
||||
// })();
|
||||
// request.templateCode = code;
|
||||
// await client.sendSms(request).then(a => {
|
||||
// console.log(a)
|
||||
// }).catch(err => {
|
||||
// console.error(err);
|
||||
// })
|
||||
}
|
||||
}
|
||||
18
apps/backend/src/oss/oss.controller.spec.ts
Normal file
18
apps/backend/src/oss/oss.controller.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { OssController } from './oss.controller';
|
||||
|
||||
describe('OssController', () => {
|
||||
let controller: OssController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [OssController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<OssController>(OssController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
18
apps/backend/src/oss/oss.controller.ts
Normal file
18
apps/backend/src/oss/oss.controller.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Controller, Get, Request, UseGuards } from '@nestjs/common';
|
||||
import { OssService } from './oss.service';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Controller('oss')
|
||||
export class OssController {
|
||||
constructor(private readonly ossService: OssService) {}
|
||||
|
||||
@UseGuards(AuthGuard('jwt'))
|
||||
@Get('sts')
|
||||
async getStsToken(@Request() req) {
|
||||
const { userId } = req.user;
|
||||
return {
|
||||
...(await this.ossService.getStsToken(`${userId}`)),
|
||||
userId,
|
||||
};
|
||||
}
|
||||
}
|
||||
9
apps/backend/src/oss/oss.module.ts
Normal file
9
apps/backend/src/oss/oss.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { OssService } from './oss.service';
|
||||
import { OssController } from './oss.controller';
|
||||
|
||||
@Module({
|
||||
providers: [OssService],
|
||||
controllers: [OssController],
|
||||
})
|
||||
export class OssModule {}
|
||||
18
apps/backend/src/oss/oss.service.spec.ts
Normal file
18
apps/backend/src/oss/oss.service.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { OssService } from './oss.service';
|
||||
|
||||
describe('OssService', () => {
|
||||
let service: OssService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [OssService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<OssService>(OssService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
53
apps/backend/src/oss/oss.service.ts
Normal file
53
apps/backend/src/oss/oss.service.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { STS } from 'ali-oss';
|
||||
|
||||
@Injectable()
|
||||
export class OssService {
|
||||
private sts = new STS({
|
||||
accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
|
||||
accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET,
|
||||
});
|
||||
|
||||
private stsCache: {
|
||||
[session: string]: {
|
||||
credentials: {
|
||||
AccessKeyId: string;
|
||||
AccessKeySecret: string;
|
||||
SecurityToken: string;
|
||||
Expiration: string;
|
||||
};
|
||||
expireTime: number; // 时间戳,单位为毫秒
|
||||
};
|
||||
} = {};
|
||||
|
||||
/** @todo 该方法存在缓存穿透问题,待优化 */
|
||||
async getStsToken(session: string) {
|
||||
if (this.stsCache[session]) {
|
||||
const cached = this.stsCache[session];
|
||||
// 检查缓存是否过期
|
||||
if (cached.expireTime > Date.now()) {
|
||||
return cached.credentials;
|
||||
} else {
|
||||
// 如果过期,删除缓存
|
||||
delete this.stsCache[session];
|
||||
}
|
||||
}
|
||||
|
||||
return this.sts
|
||||
.assumeRole(process.env.ALIYUN_OSS_STS_ROLE_ARN, ``, 3600, `${session}`)
|
||||
.then((res) => {
|
||||
// 缓存
|
||||
this.stsCache[session] = {
|
||||
credentials: res.credentials,
|
||||
expireTime:
|
||||
new Date(res.credentials.Expiration).getTime() - 5 * 60 * 1000, // 提前5分钟过期,
|
||||
};
|
||||
|
||||
return res.credentials;
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('获取STS Token失败:', err);
|
||||
throw new Error('获取STS Token失败');
|
||||
});
|
||||
}
|
||||
}
|
||||
41
apps/backend/src/resource/entity/resource.entity.ts
Normal file
41
apps/backend/src/resource/entity/resource.entity.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
type ResourceTag = {
|
||||
name: string;
|
||||
type: string;
|
||||
};
|
||||
|
||||
@Entity()
|
||||
export class Resource {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
@Index()
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
title: string;
|
||||
|
||||
@Column()
|
||||
description: string;
|
||||
|
||||
@Column()
|
||||
imageUrl: string;
|
||||
|
||||
@Column()
|
||||
link: string;
|
||||
|
||||
@Column('jsonb')
|
||||
tags: ResourceTag[];
|
||||
|
||||
@CreateDateColumn({ precision: 3 })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ precision: 3 })
|
||||
updatedAt: Date;
|
||||
}
|
||||
18
apps/backend/src/resource/resource.controller.spec.ts
Normal file
18
apps/backend/src/resource/resource.controller.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ResourceController } from './resource.controller';
|
||||
|
||||
describe('ResourceController', () => {
|
||||
let controller: ResourceController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [ResourceController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<ResourceController>(ResourceController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
12
apps/backend/src/resource/resource.controller.ts
Normal file
12
apps/backend/src/resource/resource.controller.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { ResourceService } from './resource.service';
|
||||
|
||||
@Controller('resource')
|
||||
export class ResourceController {
|
||||
constructor(private readonly resourceService: ResourceService) {}
|
||||
|
||||
@Get()
|
||||
async getResource() {
|
||||
return this.resourceService.findAll();
|
||||
}
|
||||
}
|
||||
13
apps/backend/src/resource/resource.module.ts
Normal file
13
apps/backend/src/resource/resource.module.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ResourceController } from './resource.controller';
|
||||
import { ResourceService } from './resource.service';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Resource } from './entity/resource.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Resource])],
|
||||
controllers: [ResourceController],
|
||||
providers: [ResourceService],
|
||||
exports: [ResourceService],
|
||||
})
|
||||
export class ResourceModule {}
|
||||
18
apps/backend/src/resource/resource.service.spec.ts
Normal file
18
apps/backend/src/resource/resource.service.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ResourceService } from './resource.service';
|
||||
|
||||
describe('ResourceService', () => {
|
||||
let service: ResourceService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [ResourceService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<ResourceService>(ResourceService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
38
apps/backend/src/resource/resource.service.ts
Normal file
38
apps/backend/src/resource/resource.service.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Resource } from './entity/resource.entity';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class ResourceService {
|
||||
constructor(
|
||||
@InjectRepository(Resource)
|
||||
private readonly resourceRepository: Repository<Resource>,
|
||||
) {}
|
||||
|
||||
async findAll(): Promise<Resource[]> {
|
||||
return this.resourceRepository.find({
|
||||
order: {
|
||||
createdAt: 'DESC',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<Resource> {
|
||||
return this.resourceRepository.findOne({ where: { id } });
|
||||
}
|
||||
|
||||
async create(data: Partial<Resource>): Promise<Resource> {
|
||||
const resource = this.resourceRepository.create(data);
|
||||
return this.resourceRepository.save(resource);
|
||||
}
|
||||
|
||||
async update(id: string, data: Partial<Resource>): Promise<Resource> {
|
||||
await this.resourceRepository.update(id, data);
|
||||
return this.resourceRepository.findOne({ where: { id } });
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<void> {
|
||||
await this.resourceRepository.delete(id);
|
||||
}
|
||||
}
|
||||
11
apps/backend/src/user/dto/update-user-password.dto.ts
Normal file
11
apps/backend/src/user/dto/update-user-password.dto.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { IsString, Length, Matches } from 'class-validator';
|
||||
|
||||
export class UpdateUserPasswordDto {
|
||||
@IsString({ message: '密码不得为空' })
|
||||
@Length(6, 32, { message: '密码长度只能为6~32' })
|
||||
@Matches(
|
||||
/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d!@#$%^&*()_+\-=\[\]{};:'",.<>/?]{6,32}$/,
|
||||
{ message: '密码必须包含字母和数字,且长度在6~32之间' },
|
||||
)
|
||||
password: string;
|
||||
}
|
||||
31
apps/backend/src/user/entities/user-session.entity.ts
Normal file
31
apps/backend/src/user/entities/user-session.entity.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
DeleteDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity()
|
||||
@Index(['sessionId', 'userId'])
|
||||
export class UserSession {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ length: 36 })
|
||||
sessionId: string;
|
||||
|
||||
@Column({ length: 36 })
|
||||
userId: string;
|
||||
|
||||
@CreateDateColumn({ precision: 3 })
|
||||
createdAt: Date;
|
||||
|
||||
@DeleteDateColumn({ nullable: true, precision: 3 })
|
||||
deletedAt: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 考虑是否使用sessionId代替id,以节省存储空间
|
||||
*/
|
||||
91
apps/backend/src/user/entities/user.entity.ts
Normal file
91
apps/backend/src/user/entities/user.entity.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
import {
|
||||
BeforeInsert,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
DeleteDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
@Entity()
|
||||
@Index('IDX_user_userid', ['userId'], { unique: true })
|
||||
@Index('IDX_user_username', ['username'], { unique: true })
|
||||
@Index('IDX_user_email', ['email'], {
|
||||
unique: true,
|
||||
where: 'email IS NOT NULL',
|
||||
})
|
||||
@Index('IDX_user_phone', ['phone'], {
|
||||
unique: true,
|
||||
where: 'phone IS NOT NULL',
|
||||
})
|
||||
export class User {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
userId: string;
|
||||
|
||||
@Column({ length: 32 })
|
||||
username: string;
|
||||
|
||||
@Column({ length: 30 })
|
||||
nickname: string;
|
||||
|
||||
@BeforeInsert()
|
||||
generateDefaults() {
|
||||
if (!this.username) {
|
||||
this.username = `user_${uuidv4().replace(/-/g, '').slice(0, 27)}`;
|
||||
}
|
||||
if (!this.nickname) {
|
||||
this.nickname = `用户_${uuidv4().replace(/-/g, '').slice(0, 8)}`;
|
||||
}
|
||||
}
|
||||
|
||||
@Column({ nullable: true, type: 'char', length: 32 })
|
||||
salt: string;
|
||||
|
||||
@Column({ nullable: true, type: 'char', length: 64 })
|
||||
password_hash: string;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
length: 254,
|
||||
transformer: {
|
||||
to: (value: string | null) => value?.trim() || null,
|
||||
from: (value: string | null) => value,
|
||||
},
|
||||
}) // RFC 5321
|
||||
email: string | null;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
length: 20,
|
||||
transformer: {
|
||||
to: (value: string | null) => value?.trim() || null,
|
||||
from: (value: string | null) => value,
|
||||
},
|
||||
}) // China Mainland
|
||||
phone: string | null;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
transformer: {
|
||||
to: (value: string | null) => value?.trim() || null,
|
||||
from: (value: string | null) => value,
|
||||
},
|
||||
})
|
||||
avatar: string;
|
||||
|
||||
@CreateDateColumn({ precision: 3 })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ precision: 3 })
|
||||
updatedAt: Date;
|
||||
|
||||
@DeleteDateColumn({ nullable: true, precision: 3 })
|
||||
deletedAt: Date;
|
||||
|
||||
@Column('simple-array', { default: '' })
|
||||
roles: Role[];
|
||||
}
|
||||
46
apps/backend/src/user/services/user-session.service.ts
Normal file
46
apps/backend/src/user/services/user-session.service.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { UserSession } from '../entities/user-session.entity';
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class UserSessionService {
|
||||
constructor(
|
||||
@InjectRepository(UserSession)
|
||||
private readonly userSessionRepository: Repository<UserSession>,
|
||||
) {}
|
||||
|
||||
async createSession(userId: string, sessionId: string): Promise<UserSession> {
|
||||
const session = this.userSessionRepository.create({
|
||||
userId,
|
||||
sessionId,
|
||||
});
|
||||
return await this.userSessionRepository.save(session);
|
||||
}
|
||||
|
||||
async isSessionValid(userId: string, sessionId: string): Promise<boolean> {
|
||||
const session = await this.userSessionRepository.findOne({
|
||||
where: {
|
||||
userId,
|
||||
sessionId,
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
return !!session;
|
||||
}
|
||||
|
||||
async invalidateSession(userId: string, sessionId: string): Promise<void> {
|
||||
const session = await this.userSessionRepository.findOne({
|
||||
where: {
|
||||
userId,
|
||||
sessionId,
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
if (session) {
|
||||
await this.userSessionRepository.softDelete(session.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
18
apps/backend/src/user/user.controller.spec.ts
Normal file
18
apps/backend/src/user/user.controller.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UserController } from './user.controller';
|
||||
|
||||
describe('UserController', () => {
|
||||
let controller: UserController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [UserController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<UserController>(UserController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
26
apps/backend/src/user/user.controller.ts
Normal file
26
apps/backend/src/user/user.controller.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Body, Controller, Get, Put, Request, UseGuards } from '@nestjs/common';
|
||||
import { UserService } from './user.service';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { UpdateUserPasswordDto } from './dto/update-user-password.dto';
|
||||
import { AuthService } from 'src/auth/auth.service';
|
||||
|
||||
@Controller('user')
|
||||
export class UserController {
|
||||
constructor(
|
||||
private readonly userService: UserService,
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
@UseGuards(AuthGuard('jwt'))
|
||||
@Get('me')
|
||||
async getMe(@Request() req) {
|
||||
const { user } = req;
|
||||
return this.userService.findOne({ userId: user.userId });
|
||||
}
|
||||
|
||||
@UseGuards(AuthGuard('jwt'))
|
||||
@Put('password')
|
||||
async update(@Request() req, @Body() dto: UpdateUserPasswordDto) {
|
||||
return this.userService.setPassword(req.user.userId, dto.password);
|
||||
}
|
||||
}
|
||||
19
apps/backend/src/user/user.module.ts
Normal file
19
apps/backend/src/user/user.module.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { User } from './entities/user.entity';
|
||||
import { UserController } from './user.controller';
|
||||
import { UserService } from './user.service';
|
||||
import { UserSession } from './entities/user-session.entity';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
import { UserSessionService } from './services/user-session.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([User, UserSession]),
|
||||
forwardRef(() => AuthModule), // 解决循环依赖问题
|
||||
],
|
||||
controllers: [UserController],
|
||||
providers: [UserService, UserSessionService],
|
||||
exports: [UserService, UserSessionService],
|
||||
})
|
||||
export class UserModule {}
|
||||
18
apps/backend/src/user/user.service.spec.ts
Normal file
18
apps/backend/src/user/user.service.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UserService } from './user.service';
|
||||
|
||||
describe('UserService', () => {
|
||||
let service: UserService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [UserService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<UserService>(UserService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
149
apps/backend/src/user/user.service.ts
Normal file
149
apps/backend/src/user/user.service.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { User } from './entities/user.entity';
|
||||
import { QueryFailedError, Repository } from 'typeorm';
|
||||
import { createHash } from 'crypto';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
type UserFindOptions = Partial<
|
||||
Pick<User, 'userId' | 'username' | 'phone' | 'email'>
|
||||
>;
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
constructor(
|
||||
@InjectRepository(User)
|
||||
private readonly userRepository: Repository<User>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @deprecated 尽量不使用该方法
|
||||
*/
|
||||
async findOne(
|
||||
options: UserFindOptions | UserFindOptions[],
|
||||
additionalOptions?: { withDeleted?: boolean },
|
||||
): Promise<User | null> {
|
||||
if (Object.keys(options).length === 0) {
|
||||
throw new BadRequestException('查询条件不能为空');
|
||||
}
|
||||
return this.userRepository.findOne({
|
||||
where: options,
|
||||
withDeleted: additionalOptions?.withDeleted || false,
|
||||
});
|
||||
}
|
||||
|
||||
async findById(userId: string): Promise<User | null> {
|
||||
return this.userRepository.findOne({
|
||||
where: {
|
||||
userId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async create(user: Partial<User>): Promise<User> {
|
||||
try {
|
||||
const newUser = this.userRepository.create(user);
|
||||
return await this.userRepository.save(newUser);
|
||||
} catch (error) {
|
||||
if (error instanceof QueryFailedError) {
|
||||
throw new ConflictException(this.getDuplicateErrorMessage(error));
|
||||
}
|
||||
throw new BadRequestException('创建用户失败');
|
||||
}
|
||||
}
|
||||
|
||||
async update(userId: string, user: Partial<User>): Promise<User> {
|
||||
const existingUser = await this.userRepository.findOne({
|
||||
where: { userId },
|
||||
});
|
||||
if (!existingUser) {
|
||||
throw new BadRequestException('User not found');
|
||||
}
|
||||
try {
|
||||
Object.assign(existingUser, user);
|
||||
return await this.userRepository.save(existingUser);
|
||||
} catch (error) {
|
||||
if (error instanceof QueryFailedError) {
|
||||
throw new ConflictException(this.getDuplicateErrorMessage(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async delete(userId: string, soft: boolean) {
|
||||
const existingUser = await this.userRepository.findOne({
|
||||
where: { userId },
|
||||
withDeleted: true,
|
||||
});
|
||||
if (!existingUser) {
|
||||
throw new BadRequestException('用户不存在');
|
||||
}
|
||||
|
||||
if (existingUser.deletedAt && soft) {
|
||||
throw new BadRequestException('账户已注销,不得重复操作');
|
||||
}
|
||||
|
||||
if (!existingUser.deletedAt && !soft) {
|
||||
throw new BadRequestException('账号未注销,请先注销再执行删除操作');
|
||||
}
|
||||
|
||||
return soft
|
||||
? await this.userRepository.softDelete(existingUser.userId)
|
||||
: await this.userRepository.delete(existingUser.userId);
|
||||
}
|
||||
|
||||
hashPassword(password: string, salt: string): string {
|
||||
return createHash('sha256').update(`${password}${salt}`).digest('hex');
|
||||
}
|
||||
|
||||
generateSalt(): string {
|
||||
return uuid().replace(/-/g, '');
|
||||
}
|
||||
|
||||
async setPassword(userId: string, password: string): Promise<User> {
|
||||
const user = await this.userRepository.findOne({ where: { userId } });
|
||||
if (!user) {
|
||||
throw new BadRequestException('User not found');
|
||||
}
|
||||
const salt = this.generateSalt();
|
||||
user.password_hash = this.hashPassword(password, salt);
|
||||
user.salt = salt;
|
||||
return this.userRepository.save(user);
|
||||
}
|
||||
|
||||
private getDuplicateErrorMessage(error: QueryFailedError): string {
|
||||
// 根据具体的错误信息返回友好的提示
|
||||
if (error.message.includes('IDX_user_username')) {
|
||||
return '账户名已被使用';
|
||||
}
|
||||
if (error.message.includes('IDX_user_email')) {
|
||||
return '邮箱已被使用';
|
||||
}
|
||||
if (error.message.includes('IDX_user_phone')) {
|
||||
return '手机号已被使用';
|
||||
}
|
||||
return '该登陆方式异常,请更换其他登陆方式或联系管理员';
|
||||
}
|
||||
|
||||
async list(page = 1, pageSize = 20) {
|
||||
const queryBuilder = this.userRepository.createQueryBuilder('user');
|
||||
|
||||
queryBuilder.withDeleted();
|
||||
|
||||
queryBuilder.orderBy('user.createdAt', 'DESC');
|
||||
|
||||
queryBuilder.skip((page - 1) * pageSize);
|
||||
queryBuilder.take(pageSize);
|
||||
|
||||
const [items, total] = await queryBuilder.getManyAndCount();
|
||||
return {
|
||||
items,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { IsEnum, IsString, Length, ValidateIf } from 'class-validator';
|
||||
|
||||
export class SendVerificationCodeDto {
|
||||
@IsEnum(['phone', 'email'], { message: '请求类型错误' })
|
||||
targetType: 'phone' | 'email';
|
||||
|
||||
@IsEnum(['login'], { message: '请求类型错误' })
|
||||
type: 'login';
|
||||
|
||||
@ValidateIf((o) => o.targetType === 'phone')
|
||||
@IsString({ message: '手机号必须输入' })
|
||||
@Length(11, 11, { message: '手机号异常' }) // 中国大陆,11位数字
|
||||
phone?: string;
|
||||
|
||||
@ValidateIf((o) => o.targetType === 'email')
|
||||
@IsString({ message: '邮箱必须输入' })
|
||||
@Length(6, 254, { message: '邮箱异常' }) // RFC 5321
|
||||
email?: string;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { VerificationController } from './verification.controller';
|
||||
|
||||
describe('VerificationController', () => {
|
||||
let controller: VerificationController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [VerificationController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<VerificationController>(VerificationController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
34
apps/backend/src/verification/verification.controller.ts
Normal file
34
apps/backend/src/verification/verification.controller.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { SendVerificationCodeDto } from './dto/send-verification-code.dto';
|
||||
import { VerificationService } from './verification.service';
|
||||
import { Throttle, ThrottlerGuard } from '@nestjs/throttler';
|
||||
|
||||
@Controller('verification')
|
||||
export class VerificationController {
|
||||
constructor(private readonly verificationService: VerificationService) {}
|
||||
|
||||
@Post('send')
|
||||
@UseGuards(ThrottlerGuard)
|
||||
@Throttle({ default: { limit: 20, ttl: 60000 } })
|
||||
async sendVerificationCode(@Body() dto: SendVerificationCodeDto) {
|
||||
switch (dto.type) {
|
||||
case 'login':
|
||||
switch (dto.targetType) {
|
||||
case 'phone':
|
||||
return this.verificationService.sendPhoneCode(dto.phone, dto.type);
|
||||
case 'email':
|
||||
return this.verificationService.sendEmailCode(dto.email, dto.type);
|
||||
default:
|
||||
throw new BadRequestException('不支持的目标类型');
|
||||
}
|
||||
default:
|
||||
throw new BadRequestException('不支持的验证码类型');
|
||||
}
|
||||
}
|
||||
}
|
||||
12
apps/backend/src/verification/verification.module.ts
Normal file
12
apps/backend/src/verification/verification.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { VerificationController } from './verification.controller';
|
||||
import { VerificationService } from './verification.service';
|
||||
import { NotificationModule } from 'src/notification/notification.module';
|
||||
|
||||
@Module({
|
||||
controllers: [VerificationController],
|
||||
providers: [VerificationService],
|
||||
exports: [VerificationService],
|
||||
imports: [NotificationModule],
|
||||
})
|
||||
export class VerificationModule {}
|
||||
18
apps/backend/src/verification/verification.service.spec.ts
Normal file
18
apps/backend/src/verification/verification.service.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { VerificationService } from './verification.service';
|
||||
|
||||
describe('VerificationService', () => {
|
||||
let service: VerificationService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [VerificationService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<VerificationService>(VerificationService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
127
apps/backend/src/verification/verification.service.ts
Normal file
127
apps/backend/src/verification/verification.service.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
||||
import { NotificationService } from 'src/notification/notification.service';
|
||||
|
||||
@Injectable()
|
||||
export class VerificationService {
|
||||
private readonly logger = new Logger(VerificationService.name);
|
||||
|
||||
constructor(private readonly notificationService: NotificationService) {}
|
||||
|
||||
private pool: Map<
|
||||
string,
|
||||
{
|
||||
code: string;
|
||||
createdAt: number;
|
||||
expiredAt: number;
|
||||
tryCount: number;
|
||||
maxTryCount: number;
|
||||
}
|
||||
> = new Map();
|
||||
|
||||
/**
|
||||
* @deprecated 该方法暂时弃用,因为没有申请到签名
|
||||
*/
|
||||
async sendPhoneCode(phone: string, type: 'login') {
|
||||
const key = `phone:${phone}:${type}`;
|
||||
// 检测是否在冷却时间内
|
||||
// TODO
|
||||
|
||||
// 生成验证码
|
||||
const code = this.generateCode();
|
||||
this.logger.log(`Phone[${phone}] code: ${code}`);
|
||||
|
||||
// 发送验证码
|
||||
// await this.notificationService.sendSMS(phone, type, code);
|
||||
// 存储验证码
|
||||
this.saveCode(key, code);
|
||||
throw new Error('不允许的登陆方式');
|
||||
return true;
|
||||
}
|
||||
|
||||
async sendEmailCode(email: string, type: 'login') {
|
||||
const key = `email:${email}:${type}`;
|
||||
// 检测是否在冷却时间内
|
||||
if (this.isInCooldownPeriod(key)) {
|
||||
throw new BadRequestException('发送过于频繁,请稍后再试');
|
||||
}
|
||||
|
||||
// 生成验证码
|
||||
const code = this.generateCode();
|
||||
// 存储验证码
|
||||
this.saveCode(key, code);
|
||||
this.logger.log(`Email[${email}] code: ${code}`);
|
||||
// 发送验证码
|
||||
await this.notificationService
|
||||
.sendMail({ type: 'login-verify', targetMail: email, code })
|
||||
.catch(() => {
|
||||
this.clearCode(key);
|
||||
throw new BadRequestException('发送失败,请稍后再试');
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private isInCooldownPeriod(key: string) {
|
||||
const item = this.pool.get(key);
|
||||
if (!item) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 冷却60秒
|
||||
if (Date.now() - item.createdAt > 60 * 1000) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private saveCode(key: string, code: string) {
|
||||
this.pool.set(key, {
|
||||
code: code,
|
||||
createdAt: Date.now(),
|
||||
expiredAt: Date.now() + 10 * 60 * 1000, // 10分钟过期
|
||||
tryCount: 0,
|
||||
maxTryCount: 5,
|
||||
});
|
||||
}
|
||||
|
||||
private clearCode(key: string) {
|
||||
this.pool.delete(key);
|
||||
}
|
||||
|
||||
verifyPhoneCode(phone: string, code: string, type: 'login') {
|
||||
const key = `phone:${phone}:${type}`;
|
||||
return this.verifyCode(key, code);
|
||||
}
|
||||
|
||||
verifyEmailCode(email: string, code: string, type: 'login') {
|
||||
const key = `email:${email}:${type}`;
|
||||
return this.verifyCode(key, code);
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns 0: 验证码正确, -1: 验证码不存在或已过期, -2: 验证码错误, -3: 超过最大尝试次数
|
||||
*/
|
||||
private verifyCode(key: string, code: string) {
|
||||
const data = this.pool.get(key);
|
||||
if (!data) {
|
||||
return -1;
|
||||
}
|
||||
if (data.tryCount >= data.maxTryCount) {
|
||||
return -3;
|
||||
}
|
||||
if (data.expiredAt < Date.now()) {
|
||||
return -1;
|
||||
}
|
||||
if (data.code !== code) {
|
||||
data.tryCount++;
|
||||
return -2;
|
||||
}
|
||||
this.pool.delete(key);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private generateCode() {
|
||||
return Math.floor(100000 + Math.random() * 900000).toString();
|
||||
}
|
||||
}
|
||||
24
apps/backend/test/app.e2e-spec.ts
Normal file
24
apps/backend/test/app.e2e-spec.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import * as request from 'supertest';
|
||||
import { AppModule } from './../src/app.module';
|
||||
|
||||
describe('AppController (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
|
||||
beforeEach(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
|
||||
it('/ (GET)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.get('/')
|
||||
.expect(200)
|
||||
.expect('Hello World!');
|
||||
});
|
||||
});
|
||||
9
apps/backend/test/jest-e2e.json
Normal file
9
apps/backend/test/jest-e2e.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
||||
4
apps/backend/tsconfig.build.json
Normal file
4
apps/backend/tsconfig.build.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
||||
21
apps/backend/tsconfig.json
Normal file
21
apps/backend/tsconfig.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2021",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": false,
|
||||
"noImplicitAny": false,
|
||||
"strictBindCallApply": false,
|
||||
"forceConsistentCasingInFileNames": false,
|
||||
"noFallthroughCasesInSwitch": false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user