Skip to content

Commit

Permalink
Merge pull request #1 from coverjs/add-account-login
Browse files Browse the repository at this point in the history
Add account login
  • Loading branch information
hacxy authored Jul 25, 2024
2 parents e2e890d + de10e3f commit 1b5ad5f
Show file tree
Hide file tree
Showing 24 changed files with 241 additions and 89 deletions.
23 changes: 16 additions & 7 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,32 @@ module.exports = {
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
sourceType: 'module'
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
extends: ['plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'],
root: true,
env: {
node: true,
jest: 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',
},
'@typescript-eslint/no-unused-vars': [
'error',
{
args: 'all',
argsIgnorePattern: '^_',
caughtErrors: 'all',
caughtErrorsIgnorePattern: '^_',
destructuredArrayIgnorePattern: '^_',
varsIgnorePattern: '^_',
ignoreRestSiblings: true
}
]
}
};
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,5 @@ pids

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
prisma/migrations
prisma/migrations
prisma/dev.db*
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,29 @@
# Cover Admin Service

Cover Admin 中后台服务端

## 如何运行

- 安装依赖

```bash
npm install
```

- 同步数据库

```bash
pnpm db:pm
```

- 生成Prisma客户端 首次执行需要确保能访问外网

```bash
pnpm db:pg
```

- 启动开发环境服务

```bash
pnpm dev
```
10 changes: 7 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"db:pg": "prisma generate",
"db:pm": "prisma migrate dev --name cover-dev",
"db:pm": "prisma migrate dev --name cover_dev",
"db:seed": "prisma db seed",
"db:ps": "prisma studio",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
Expand All @@ -34,7 +35,7 @@
"prisma": "^5.17.0",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"uni-nest": "^0.4.0"
"uni-nest": "^0.5.0"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
Expand All @@ -57,7 +58,7 @@
"supertest": "^6.3.3",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3"
},
Expand All @@ -77,5 +78,8 @@
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"prisma": {
"seed": "ts-node --transpile-only prisma/seed"
}
}
12 changes: 6 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file removed prisma/dev.db
Binary file not shown.
Binary file removed prisma/dev.db-journal
Binary file not shown.
6 changes: 3 additions & 3 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ generator client {

datasource db {
provider = "sqlite"
// url = env("DATABASE_URL")
url = "file:./dev.db"
url = env("DATABASE_URL")
}

model User {
id Int @id @default(autoincrement())
username String
username String @unique
password String
email String? @unique
nickname String?
salt String @default("")
enable Boolean @default(true)
}
11 changes: 11 additions & 0 deletions prisma/seed-data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { encryptPassword } from 'uni-nest';

export const User = [
{
username: 'admin',
password: encryptPassword('admin', '1118'),
salt: '1118',
nickname: 'hacxy',
email: 'admin@admin.com'
}
];
23 changes: 23 additions & 0 deletions prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { PrismaClient } from '@prisma/client';
import { User } from './seed-data';

export const initDatabase = async () => {
const prisma = new PrismaClient();
// // 创建用户数据
await prisma.user.createMany({ data: User });
// // 创建角色数据
// await prisma.role.createMany({ data: seedData.Role, skipDuplicates: true });
// // 创建菜单数据
// await prisma.user.createMany({ data: seedData.User, skipDuplicates: true });
// initData()
// .then(async () => {
// await prisma.$disconnect();
// })
// .catch(async (e) => {
// console.error(e);
// await prisma.$disconnect();
// process.exit(1);
// });
};

initDatabase();
3 changes: 2 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { UploadModule } from './modules/upload/upload.module';
import { AuthModule } from './modules/auth/auth.module';
import { ConfigModule } from '@nestjs/config';
import { PrismaModule } from './common/prisma/prisma.module';
import { AccountModule } from './modules/account/account.module';

@Module({
imports: [PrismaModule, UserModule, UploadModule, AuthModule, ConfigModule.forRoot({ isGlobal: true })]
imports: [PrismaModule, UserModule, UploadModule, AuthModule, ConfigModule.forRoot({ isGlobal: true }), AccountModule]
})
export class AppModule {}
2 changes: 2 additions & 0 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const JWT_SECRET_ENV_KEY = 'JWT_SECRET';
export const TOKEN_EXPIRES_ENV_KEY = 'TOKEN_EXPIRES';
6 changes: 6 additions & 0 deletions src/exceptions/business.error.code.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const ADMIN_ERROR_CODE = {
USERNAME_OR_PASSWORD_INCORRECT: {
code: 1000,
msg: '用户名或密码不正确'
}
};
9 changes: 9 additions & 0 deletions src/exceptions/business.exceptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { UniBusinessException } from 'uni-nest';
import { ADMIN_ERROR_CODE } from './business.error.code';

// 定义业务异常
export class BusinessException extends UniBusinessException {
static throwUsernameOrPasswordIncorrect(): void {
throw new BusinessException(ADMIN_ERROR_CODE.USERNAME_OR_PASSWORD_INCORRECT);
}
}
7 changes: 5 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import { bootstrap } from 'uni-nest';

bootstrap(AppModule, {
swaggerOptions: {
title: 'nestjs模板接口文档',
description: '这是一个nestjs模板项目的接口文档',
title: 'Cover Admin',
description: 'Cover Admin 接口文档',
version: '1.0.0',
license: ['MIT']
},
appOptions: {
port: 1118
},
beforeAppListen(app) {
app.setGlobalPrefix('api');
},
Expand Down
27 changes: 27 additions & 0 deletions src/modules/account/account.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Body, Controller } from '@nestjs/common';
import { AccountService } from './account.service';
import { AccountDto } from './dto/account.dto';
import { ApiTags, Method, UniDefine } from 'uni-nest';
import { AccountLoginVo } from './dto/account.vo';

@ApiTags('账号管理')
@Controller('account')
export class AccountController {
constructor(private readonly accountService: AccountService) {}

@UniDefine({
path: 'login',
method: Method.Post,
summary: '登录',
isPublic: true,
body: {
type: AccountDto
},
response: {
type: AccountLoginVo
}
})
create(@Body() createAccountDto: AccountDto) {
return this.accountService.login(createAccountDto);
}
}
10 changes: 10 additions & 0 deletions src/modules/account/account.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { AccountService } from './account.service';
import { AccountController } from './account.controller';
import { JwtService } from '@nestjs/jwt';

@Module({
controllers: [AccountController],
providers: [AccountService, JwtService]
})
export class AccountModule {}
35 changes: 35 additions & 0 deletions src/modules/account/account.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Injectable } from '@nestjs/common';
import { AccountDto } from './dto/account.dto';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { JWT_SECRET_ENV_KEY, TOKEN_EXPIRES_ENV_KEY } from '../../constants';
import { PrismaService } from '../../common/prisma/prisma.service';
import { encryptPassword } from 'uni-nest';
import { BusinessException } from '../../exceptions/business.exceptions';

@Injectable()
export class AccountService {
constructor(
private readonly configService: ConfigService,
private readonly jwtService: JwtService,
private readonly prismaService: PrismaService
) {}
async login(account: AccountDto) {
const { username, password } = account;
const userInfo = await this.prismaService.user.findUnique({
where: {
username
}
});

if (userInfo && userInfo.password === encryptPassword(password, userInfo.salt)) {
const { password, ...res } = userInfo;
const token = this.jwtService.sign(res, {
secret: this.configService.get(JWT_SECRET_ENV_KEY),
expiresIn: this.configService.get(TOKEN_EXPIRES_ENV_KEY)
});
return { token };
}
BusinessException.throwUsernameOrPasswordIncorrect();
}
}
22 changes: 22 additions & 0 deletions src/modules/account/dto/account.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ApiProperty } from 'uni-nest';

export class AccountDto {
@ApiProperty({
description: '用户名',
example: 'admin'
})
username: string;

@ApiProperty({
description: '密码',
example: 'admin'
})
password: string;

@ApiProperty({
description: '登录类型',
example: 'account',
enum: ['account', 'mobile']
})
type: 'account' | 'mobile';
}
6 changes: 6 additions & 0 deletions src/modules/account/dto/account.vo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { ApiProperty } from 'uni-nest';

export class AccountLoginVo {
@ApiProperty({ description: 'token' })
token: string;
}
Loading

0 comments on commit 1b5ad5f

Please sign in to comment.