feat: 优化项目目录结构

This commit is contained in:
2025-12-12 17:25:26 +08:00
parent ae627d0496
commit b89f83291e
235 changed files with 0 additions and 0 deletions

25
apps/backend/.eslintrc.js Normal file
View 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
View 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
View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

99
apps/backend/README.md Normal file
View 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>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](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).

View 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
View 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

File diff suppressed because it is too large Load Diff

View 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();
});
});

View File

@@ -0,0 +1,4 @@
import { Controller } from '@nestjs/common';
@Controller('admin')
export class AdminController {}

View 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 {}

View 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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,9 @@
import { IsString } from 'class-validator';
export class CreatePermissionDto {
@IsString()
name: string;
@IsString()
description: string;
}

View File

@@ -0,0 +1,8 @@
import { ArrayMinSize, IsArray, IsUUID } from 'class-validator';
export class DeleteRolePermissionsDto {
@IsArray()
@ArrayMinSize(1)
@IsUUID('4', { each: true })
permissionIds: string[];
}

View File

@@ -0,0 +1,8 @@
import { ArrayMinSize, IsArray, IsUUID } from 'class-validator';
export class SetRolePermissionsDto {
@IsArray()
@ArrayMinSize(1)
@IsUUID('4', { each: true })
permissionIds: string[];
}

View File

@@ -0,0 +1,9 @@
import { IsString } from 'class-validator';
export class CreateRoleDto {
@IsString()
name: string;
@IsString()
localName: string;
}

View File

@@ -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;
}

View File

@@ -0,0 +1,6 @@
import { IsUUID } from 'class-validator';
export class DeleteUserRoleDto {
@IsUUID('4')
roleId: string;
}

View 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;
}

View File

@@ -0,0 +1,3 @@
import { PaginationDto } from '../common/pagination.dto';
export class ListDto extends PaginationDto {}

View 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;
}

View 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;
}

View 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;
}

View 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; // 允许空串
}

View 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[];
}

View File

@@ -0,0 +1,6 @@
import { IsString } from 'class-validator';
export class SetBlogPasswordDto {
@IsString()
password: string;
}

View 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[];
}

View 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;
}

View 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!');
});
});
});

View 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();
}
}

View 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 {}

View File

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

View 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();
});
});

View 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;
}
}

View 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 {}

View 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();
});
});

View 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);
}
}

View 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;
}

View File

@@ -0,0 +1,3 @@
export enum Role {
Admin = 'admin',
}

View 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; // 如果有用户信息,返回用户对象
}
}

View 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,
};
}
}

View 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();
});
});

View 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);
}
}

View 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 {}

View File

@@ -0,0 +1,6 @@
export enum BlogPermission {
Public = 'Public',
ByPassword = 'ByPassword',
List = 'List',
AllowComments = 'AllowComments',
}

View 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();
});
});

View 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');
}
}

View 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;
}

View 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[];
}

View 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;
}

View 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);

View 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;
}
}

View 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
View 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();

View File

@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { NotificationService } from './notification.service';
@Module({
providers: [NotificationService],
exports: [NotificationService],
})
export class NotificationModule {}

View 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();
});
});

View 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);
// })
}
}

View 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();
});
});

View 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,
};
}
}

View 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 {}

View 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();
});
});

View 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失败');
});
}
}

View 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;
}

View 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();
});
});

View 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();
}
}

View 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 {}

View 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();
});
});

View 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);
}
}

View 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;
}

View 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以节省存储空间
*/

View 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[];
}

View 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);
}
}
}

View 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();
});
});

View 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);
}
}

View 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 {}

View 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();
});
});

View 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,
};
}
}

View File

@@ -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;
}

View File

@@ -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();
});
});

View 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('不支持的验证码类型');
}
}
}

View 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 {}

View 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();
});
});

View 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();
}
}

View 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!');
});
});

View File

@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

View File

@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

View 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
}
}

41
apps/frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

36
apps/frontend/README.md Normal file
View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

View File

@@ -0,0 +1,80 @@
'use client';
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { BlogApi } from "@/lib/api";
import { BlogComment } from "@/lib/types/blogComment";
import { Send, Undo2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
interface BlogCommentToolProps {
blogId: string;
onInsertComment: (b: BlogComment) => void;
replayTarget: BlogComment | null;
handleClearReplayTarget: () => void;
}
export function BlogCommentTool({ blogId, onInsertComment, replayTarget, handleClearReplayTarget }: BlogCommentToolProps) {
const [comment, setComment] = useState('');
const textareaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (replayTarget && textareaRef.current) {
textareaRef.current.focus();
textareaRef.current.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'start'
})
}
}, [replayTarget]);
const submit = async () => {
if (comment.trim().length === 0) return;
try {
const res = await BlogApi.createComment(blogId, comment, replayTarget ? replayTarget.id : undefined);
if (res) {
toast.success('发布成功');
setComment('');
onInsertComment(res);
handleClearReplayTarget();
}
} catch (error) {
if ((error as { statusCode: number }).statusCode === 429) {
return toast.error('操作太频繁了,稍后再试吧')
}
toast.error(`${(error as Error).message || '发布失败'}`)
}
}
const getPlaceHolderText = () => {
if (!replayTarget) return '评论';
let replayComment = replayTarget.content.trim();
if (replayComment.length > 8) {
replayComment = replayComment.slice(0, 8) + '...';
}
const replayUser = replayTarget.user ? replayTarget.user.nickname : '匿名';
return `回复 ${replayUser}${replayComment}`;
}
return (
<div className="my-3 flex items-end gap-2">
<Textarea
ref={textareaRef}
placeholder={getPlaceHolderText()}
onChange={v => setComment(v.target.value)}
value={comment} />
<Button variant='outline' size='icon' onClick={() => submit()} disabled={comment.trim().length === 0}>
<Send />
</Button>
{replayTarget && <Button variant='outline' size='icon' onClick={() => handleClearReplayTarget()}>
<Undo2 />
</Button>}
</div>
)
}

View File

@@ -0,0 +1,81 @@
import useSWR from "swr";
import { BlogCommentTool } from "./BlogCommentTool";
import { BlogApi } from "@/lib/api";
import { BlogComment } from "@/lib/types/blogComment";
import { useState } from "react";
import { useUserMe } from "@/hooks/user/use-user-me";
export function BlogComments({ blogId }: { blogId: string }) {
const { data, mutate } = useSWR(
`/api/blog/${blogId}/comments`,
() => BlogApi.getComments(blogId),
)
const { user } = useUserMe();
const insertComment = async (newOne: BlogComment) => {
await mutate(
(comments) => {
if (!comments) return [newOne];
return [newOne, ...comments]
},
{ revalidate: false }
)
}
const [replayTarget, setReplayTarget] = useState<BlogComment | null>(null);
return (
data && <div className="" >
<h1 className="px-2 border-l-4 border-zinc-300"> {data.length}</h1>
<BlogCommentTool
blogId={blogId}
onInsertComment={insertComment}
replayTarget={replayTarget}
handleClearReplayTarget={() => setReplayTarget(null)}
/>
<div className="text-sm text-zinc-600">
{
user ? (<span>{user.nickname}</span>) : (<span></span>)
}
</div>
<div className="flex flex-col">
{
data.filter(d => !d.parentId)
.map((d) => (
<div key={d.id} className="border-b border-zinc-300 py-2 last:border-none">
<h1 className="text-zinc-500">{d.user ? d.user.nickname : '匿名'}</h1>
<div className="whitespace-pre-wrap break-all">{d.content}</div>
<div className="text-xs text-zinc-500 flex gap-2">
<p>{new Date(d.createdAt).toLocaleString()}</p>
<p>{d.address}</p>
<p className="text-zinc-900 cursor-pointer" onClick={() => setReplayTarget(d)}></p>
</div>
{
data.filter(c => c.parentId === d.id).length > 0 && (
<div className="flex flex-col ml-5 my-1">
{
data.filter(c => c.parentId === d.id).map(c => (
<div key={c.id} className="border-b border-zinc-300 py-1 last:border-none">
<h1 className="text-zinc-500">{c.user ? c.user.nickname : '匿名'}</h1>
<div className="whitespace-pre-wrap break-all">{c.content}</div>
<div className="text-xs text-zinc-500 flex gap-2">
<p>{new Date().toLocaleString()}</p>
<p>{c.address}</p>
</div>
</div>
))
}
</div>
)
}
</div>
))
}
</div >
</div>
)
}

View File

@@ -0,0 +1,95 @@
'use client';
import { BlogApi } from "@/lib/api";
import { base62 } from "@/lib/utils";
import { useParams, useSearchParams } from "next/navigation";
import useSWR from "swr";
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import rehypeHighlight from 'rehype-highlight'
import 'highlight.js/styles/github.css'
import { PhotoProvider, PhotoView } from 'react-photo-view';
import 'react-photo-view/dist/react-photo-view.css';
import rehypeRaw from 'rehype-raw'
import { Skeleton } from "@/components/ui/skeleton";
import { BlogComments } from "./components/BlogComments";
import Image from "next/image";
export default function Blog() {
const params = useParams();
const searchParams = useSearchParams();
const hex = Array.from(base62.decode(params.id as string)).map(b => b.toString(16).padStart(2, '0')).join('');
const id = [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20, 32)
].join('-');
const password = searchParams.get('p');
const { data, error, isLoading } = useSWR(
`/api/blog/${id}`,
() => BlogApi.get(id, {
password: password || undefined,
}),
)
return (
<div className="w-full overflow-x-hidden">
<div className="max-w-200 mx-auto px-5 overflow-x-hidden mb-10">
{error && <div className="my-20 text-center text-zinc-600">{error.message}</div>}
{isLoading && (
<div className="flex flex-col gap-2 mt-10">
<Skeleton className="w-full h-10" />
<Skeleton className="w-full h-20" />
<Skeleton className="w-full h-10" />
<Skeleton className="w-full h-20" />
<Skeleton className="w-full h-30" />
</div>
)}
{data && (
<>
<h1 className="text-center text-3xl font-bold mt-10">{data.title}</h1>
<p className="text-sm text-zinc-500 text-center my-5">{new Date(data.createdAt).toLocaleString()}</p>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw, rehypeHighlight]}
components={{
h1: ({ ...props }) => <h1 className="text-3xl font-bold py-2" {...props} />,
h2: ({ ...props }) => <h2 className="text-2xl font-bold py-1" {...props} />,
h3: ({ ...props }) => <h3 className="text-xl font-bold py-0.5" {...props} />,
h4: ({ ...props }) => <h4 className="text-lg font-bold" {...props} />,
h5: ({ ...props }) => <h5 className="text-md font-bold" {...props} />,
p: ({ ...props }) => <p className="py-1 text-zinc-700" {...props} />,
img: ({ src }) => (
<PhotoProvider className="w-full">
<PhotoView src={src as string}>
<div style={{ width: '100%' }}>
<Image src={src as string} width={0} height={0} style={{ width: '100%', height: 'auto' }} unoptimized alt="加载失败" />
</div>
</PhotoView>
</PhotoProvider>
),
th: ({ ...props }) => <th className="text-ellipsis text-nowrap border border-zinc-300 p-2" {...props} />,
td: ({ ...props }) => <td className="border border-zinc-300 p-1" {...props} />,
table: ({ ...props }) => <div className="overflow-x-auto"><table {...props} /></div>,
pre: ({ ...props }) => <pre className="rounded-sm overflow-hidden shadow" {...props} />,
blockquote: ({ ...props }) => <blockquote className="pl-3 border-l-5" {...props} />,
a: ({ ...props }) => <a className="hover:underline" {...props} />,
}}
>{data.content}</ReactMarkdown>
</>
)}
{data && (
<>
<div className="border my-5"></div>
<BlogComments blogId={data.id} />
</>
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,63 @@
"use client"
import { Skeleton } from "@/components/ui/skeleton";
import { BlogApi } from "@/lib/api";
import { useCallback } from "react"
import useSWR from "swr";
import {
Alert,
AlertDescription,
AlertTitle,
} from "@/components/ui/alert";
import { AlertCircle } from "lucide-react";
import { base62 } from "@/lib/utils";
export default function Blog() {
const formatNumber = useCallback((num: number) => {
if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
} else if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
}
return num.toString();
}, []);
const { data: blogs, error, isLoading } = useSWR(
'/api/blogs',
() => BlogApi.list(),
)
return (
<div className="max-w-120 w-auto mx-auto my-10 flex flex-col gap-8">
{
isLoading && (
<div className="w-full">
<Skeleton className="w-full h-5" />
<Skeleton className="w-full h-10 mt-1" />
<Skeleton className="w-full h-5 mt-5" />
</div>
)
}
{
error && (
<Alert variant="destructive" className="w-full">
<AlertCircle className="h-4 w-4" />
<AlertTitle></AlertTitle>
<AlertDescription>
{error.message}
</AlertDescription>
</Alert>
)
}
{
blogs && blogs.map((blog) => (
<div className="w-full px-5 cursor-default" key={blog.id}>
<a className="text-2xl font-medium cursor-pointer hover:underline" target="_blank" href={`/blog/${base62.encode(Buffer.from(blog.id.replace(/-/g, ''), 'hex'))}`}>{blog.title}</a>
<p className="text-sm font-medium text-zinc-400">{blog.description}</p>
<p className="text-sm font-medium text-zinc-400 mt-3">{new Date(blog.createdAt).toLocaleString()} · {formatNumber(blog.viewCount)} 访</p>
</div>
))
}
</div>
)
}

View File

@@ -0,0 +1,18 @@
import Header from "../../components/Header";
import Footer from "../../components/Footer";
export default function LayoutWithHeaderFooter({
children,
}: {
children: React.ReactNode;
}) {
return (
<>
<Header />
<main className="flex-1 flex flex-col bg-zinc-50">
{children}
</main>
<Footer />
</>
)
}

View File

@@ -0,0 +1,25 @@
'use client';
import favicon from '../favicon.ico';
import Image from 'next/image';
export default function Home() {
return (
<div className="w-full flex-1 flex flex-col items-center justify-center">
<Image
src={favicon.src}
alt="TONE's avatar"
width={180}
height={180}
className="rounded-full duration-400 size-35 md:size-45 select-none"
priority
quality={100}
/>
<h1 className='text-4xl md:text-5xl font-bold mt-5 md:mt-8 gradient-title duration-400 select-none'>(TONE)</h1>
<h2 className='text-lg sm:text-xl md:text-2xl mt-3 font-medium text-zinc-400 duration-400 select-none'></h2>
<div className='flex sm:flex-row flex-col gap-2 sm:gap-10 mt-5 md:mt-8 duration-400'>
<a href='https://space.bilibili.com/474156211' target='_black' className='bg-[#488fe9] hover:bg-[#3972ba] text-center text-white w-45 sm:w-32 px-6 py-2 text-lg rounded-full cursor-pointer'></a>
<a href='https://github.com/tonecn' className='bg-[#da843f] hover:bg-[#c87d3e] text-center text-white w-45 sm:w-32 px-6 py-2 text-lg rounded-full cursor-pointer'>GitHub</a>
</div>
</div>
);
}

View File

@@ -0,0 +1,47 @@
import { ResourceBadge } from "@/components/resource";
import { Card, CardContent } from "@/components/ui/card";
import { Resource } from "@/lib/types/resource";
import Image from "next/image";
import React from "react";
interface ResourceCardProps extends React.HTMLProps<HTMLAnchorElement> {
r: Resource;
}
export function ResourceCard({ r, ...props }: ResourceCardProps) {
const [imageError, setImageError] = React.useState(false);
return (
<a href={r.link} target="_blank" {...props}>
<Card className="w-full md:w-92 lg:w-100 md:rounded-xl rounded-none duration-300">
<CardContent>
<div className="flex gap-6">
<div>
{!imageError && <Image
src={r.imageUrl}
alt="资源图片"
width={90}
height={90}
className="rounded-md shadow"
priority
quality={80}
onError={() => setImageError(true)}
/>}
</div>
<div className="flex-1 overflow-x-hidden">
<div className="font-bold text-2xl">{r.title}</div>
<div className="font-medium text-sm text-zinc-400 mt-1">{r.description}</div>
<div className="flex gap-2 flex-wrap mt-4">
{
r.tags.map((tag) => (
<ResourceBadge key={tag.name} tag={tag} />
))
}
</div>
</div>
</div>
</CardContent>
</Card>
</a>
)
}

View File

@@ -0,0 +1,56 @@
"use client";
import useSWR from "swr";
import { ResourceCard } from "./components/ResourceCard";
import { ResourceApi } from "@/lib/api";
import {
Alert,
AlertDescription,
AlertTitle,
} from "@/components/ui/alert"
import { AlertCircle } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
export default function Resources() {
const { data, isLoading, error } = useSWR(
'/api/resource',
() => ResourceApi.list(),
);
return (
<div className="flex-1 flex flex-col items-center">
<h1 className="mt-6 md:mt-20 text-2xl md:text-5xl font-medium text-zinc-800 text-center duration-300"></h1>
<p className="mt-4 md:mt-8 mx-3 text-zinc-400 text-sm text-center duration-300">
<a className="text-zinc-600">使</a>
使</p>
{
error && (
<div className="mt-10 mx-5">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle></AlertTitle>
<AlertDescription>
{error.message}
</AlertDescription>
</Alert>
</div>
)
}
<div className="mt-6 sm:mt-10 md:mt-15 w-full flex flex-col md:w-auto md:mx-auto md:grid grid-cols-2 2xl:gap-x-35 lg:gap-x-20 gap-x-10 lg:gap-y-10 gap-y-5 sm:mb-10 duration-300">
{isLoading && (
[...Array(3).map((_, i) => (
<Skeleton key={i} className="h-35 w-full md:w-92 lg:w-100 md:rounded-xl rounded-none duration-300" />
))]
)}
{data && data.map((resource) => (
<ResourceCard
key={resource.id}
r={resource}
/>
))}
</div>
</div>
)
}

View File

@@ -0,0 +1,6 @@
import { Metadata } from "next";
export const metadata: Metadata = {
title: "特恩的日志",
description: "一名啥都会一点点的程序员",
};

View File

@@ -0,0 +1,71 @@
'use client';
import { AppSidebar } from "@/components/app-sidebar"
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbList,
BreadcrumbPage,
} from "@/components/ui/breadcrumb"
import {
SidebarInset,
SidebarProvider,
SidebarTrigger,
} from "@/components/ui/sidebar"
import { useUserMe } from "@/hooks/user/use-user-me";
import { UserApi } from "@/lib/api";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
export default function ConsoleMenuLayout({
children,
}: {
children: React.ReactNode
}) {
const router = useRouter();
const { user, isLoading, error } = useUserMe({
onError: (e) => {
if (e.statusCode === 401) {
toast.info('登录凭证已失效,请重新登录');
router.replace('/console/login');
}
}
});
if (!isLoading && !error && !user) {
router.replace('/console/login');
localStorage.removeItem('token');
localStorage.removeItem(UserApi.USER_ME_CACHE_KEY);
toast.error('账户状态异常,请重新登录');
}
return (
<SidebarProvider>
<AppSidebar user={user} isUserLoading={isLoading} />
<SidebarInset>
<header className="flex h-16 shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-12">
<div className="flex items-center gap-2 px-4">
<SidebarTrigger className="-ml-1" />
<div className="w-[1px] h-4 mr-2 bg-zinc-300"></div>
<Breadcrumb>
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbPage>
{new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long'
}).format(new Date())}
</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
</div>
</header>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0">
{children}
</div>
</SidebarInset>
</SidebarProvider>
)
}

Some files were not shown because too many files have changed in this diff Show More