Sfoglia il codice sorgente

优化数据机构

枫叶秋林 2 anni fa
parent
commit
8374632c0b

+ 36 - 0
prisma/migrations/20221211123401_updata_init/migration.sql

@@ -0,0 +1,36 @@
+/*
+  Warnings:
+
+  - You are about to drop the `user` table. If the table is not empty, all the data it contains will be lost.
+
+*/
+-- DropTable
+DROP TABLE `user`;
+
+-- CreateTable
+CREATE TABLE `auth` (
+    `auth_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
+    `username` VARCHAR(191) NOT NULL,
+    `email` VARCHAR(191) NOT NULL,
+    `password` VARCHAR(191) NOT NULL,
+
+    UNIQUE INDEX `auth_username_key`(`username`),
+    UNIQUE INDEX `auth_email_key`(`email`),
+    PRIMARY KEY (`auth_id`)
+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
+
+-- CreateTable
+CREATE TABLE `userinfo` (
+    `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
+    `avatar` VARCHAR(191) NOT NULL,
+    `exp` INTEGER UNSIGNED NOT NULL DEFAULT 0,
+    `level` INTEGER UNSIGNED NOT NULL DEFAULT 0,
+    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
+    `authId` INTEGER UNSIGNED NOT NULL,
+
+    UNIQUE INDEX `userinfo_authId_key`(`authId`),
+    PRIMARY KEY (`id`)
+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
+
+-- AddForeignKey
+ALTER TABLE `userinfo` ADD CONSTRAINT `userinfo_authId_fkey` FOREIGN KEY (`authId`) REFERENCES `auth`(`auth_id`) ON DELETE CASCADE ON UPDATE CASCADE;

+ 15 - 5
prisma/schema.prisma

@@ -6,11 +6,21 @@ datasource db {
   provider = "mysql"
   url      = env("DATABASE_URL")
 }
-model user{
-  id        Int   @id @default(autoincrement()) @db.UnsignedInt
-  username  String @unique
+model auth{
+  auth_id        Int   @id @default(autoincrement()) @db.UnsignedInt
+  username  String  @unique
+  email     String  @unique
   password  String
-  email     String
-  createdAt DateTime  @default(now()) @updatedAt
+  user      userinfo?
+}
+model userinfo{
+  id        Int       @id @default(autoincrement()) @db.UnsignedInt
+  avatar    String 
+  exp       Int       @default(0) @db.UnsignedInt
+  level     Int       @default(0) @db.UnsignedInt
+  createdAt DateTime  @default(now())
+  authId    Int       @unique @db.UnsignedInt
+  user      auth      @relation(fields: [authId], references: [auth_id], onDelete: Cascade)
+
 }
 

+ 2 - 0
src/app.module.ts

@@ -4,6 +4,7 @@ import { AuthModule } from '@/auth/auth.module'
 import { PrismaModule } from '@/prisma/prisma.module'
 import { CodModule } from './cod/cod.module';
 import { RedisModule } from './redis/redis.module';
+import { UserinfoModule } from './userinfo/userinfo.module';
 @Module({
   imports: [
     AuthModule,
@@ -13,6 +14,7 @@ import { RedisModule } from './redis/redis.module';
     }),
     CodModule,
     RedisModule,
+    UserinfoModule,
   ],
   controllers: [],
   providers: [],

+ 4 - 2
src/auth/JwtStrategy.ts

@@ -17,8 +17,10 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
 
   //验证通过后获取用户资料
   async validate({ sub: id }) {
-    return this.prisma.user.findUnique({
-      where: { id },
+    return this.prisma.auth.findUnique({
+      where: {
+        auth_id: id,
+      },
     })
   }
 }

+ 12 - 13
src/auth/auth.service.ts

@@ -1,6 +1,6 @@
 import { BadRequestException, Injectable } from '@nestjs/common'
 import { JwtService } from '@nestjs/jwt'
-import { user } from '@prisma/client'
+import { auth } from '@prisma/client'
 import { hash, verify } from 'argon2'
 import { PrismaService } from 'src/prisma/prisma.service'
 import LoginDto from './dto/login.dto'
@@ -11,7 +11,7 @@ export class AuthService {
   constructor(private prisma: PrismaService, private jwt: JwtService) {}
   async register(dto: registerDto) {
     const paw = await hash(dto.paw)
-    const user = await this.prisma.user.create({
+    const user = await this.prisma.auth.create({
       data: {
         username: dto.name,
         password: paw,
@@ -19,10 +19,11 @@ export class AuthService {
       },
     })
     delete user.password
-    return this.token(user)
+    const token = await this.token(user)
+    return { cod: 200, msg: '注册成功', token }
   }
   async login(dto: LoginDto) {
-    const user = await this.prisma.user.findUnique({
+    const user = await this.prisma.auth.findUnique({
       where: {
         username: dto.name,
       },
@@ -30,20 +31,18 @@ export class AuthService {
     if (!user) {
       throw new BadRequestException('用户名错误')
     }
-
     if (!(await verify(user.password, dto.paw))) {
       throw new BadRequestException('密码错误')
     }
     delete user.password
     const token = await this.token(user)
-    return { ...user, ...token }
+    return { cod: 200, msg: '登陆成功', token }
   }
-  async token({ username, id }: user) {
-    return {
-      token: await this.jwt.signAsync({
-        username,
-        sub: id,
-      }),
-    }
+  async token({ auth_id, username }: auth) {
+    const token = await this.jwt.signAsync({
+      username,
+      sub: auth_id,
+    })
+    return token
   }
 }

+ 4 - 0
src/userinfo/userinfo.controller.ts

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

+ 9 - 0
src/userinfo/userinfo.module.ts

@@ -0,0 +1,9 @@
+import { Module } from '@nestjs/common';
+import { UserinfoService } from './userinfo.service';
+import { UserinfoController } from './userinfo.controller';
+
+@Module({
+  providers: [UserinfoService],
+  controllers: [UserinfoController]
+})
+export class UserinfoModule {}

+ 4 - 0
src/userinfo/userinfo.service.ts

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