Jelajahi Sumber

完成发帖后台模块
完善数据库

枫叶秋林 2 tahun lalu
induk
melakukan
44ed36ada1

+ 2 - 0
prisma/migrations/20230107033113_userinfo_add_maple_coin/migration.sql

@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE `userinfo` ADD COLUMN `mapleCoin` INTEGER UNSIGNED NOT NULL DEFAULT 0;

+ 2 - 0
prisma/migrations/20230107075128_post_add_views/migration.sql

@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE `post` ADD COLUMN `views` INTEGER UNSIGNED NOT NULL DEFAULT 0;

+ 3 - 0
prisma/schema.prisma

@@ -21,6 +21,8 @@ model post{
   content   String
   createdAt DateTime  @default(now())
   updatedAt DateTime  @updatedAt
+  // 浏览量
+  views     Int       @default(0) @db.UnsignedInt
   authorId  Int       @db.UnsignedInt
   author    auth      @relation(fields: [authorId], references: [auth_id])
   comment   comment[]
@@ -52,6 +54,7 @@ model userinfo{
   signature String    @default("这个家伙很懒,什么都没留下")
   exp       Int       @default(0) @db.UnsignedInt
   level     Int       @default(0) @db.UnsignedInt
+  mapleCoin Int       @default(0) @db.UnsignedInt
   createdAt DateTime  @default(now())
   authId    Int       @unique @db.UnsignedInt
   user      auth      @relation(fields: [authId], references: [auth_id])

+ 13 - 2
src/auth/auth.controller.ts

@@ -1,10 +1,11 @@
 import { CodService } from '@/cod/cod.service'
-import { Body, Controller, Get, Headers, Post, Req, UseGuards } from '@nestjs/common'
+import { Body, Controller, Get, Headers, Post, Put, Req, UseGuards } from '@nestjs/common'
 import { AuthGuard } from '@nestjs/passport'
 import { Request } from 'express'
 import { AuthService } from './auth.service'
 import LoginDto from './dto/login.dto'
 import registerDto from './dto/register.dto'
+import UpsetpawDto from './dto/upsetpaw.dto'
 
 @Controller('auth')
 export class AuthController {
@@ -21,9 +22,19 @@ export class AuthController {
   login(@Body() dto: LoginDto) {
     return this.auto.login(dto)
   }
+  @Put('paw')
+  @UseGuards(AuthGuard('jwt'))
+  async paw(@Req() req: Request, @Body() dto: UpsetpawDto, @Headers('cod') cod: string) {
+    const rescod = await this.codService.verifyCod(req.ip, cod)
+    if (!rescod.status) {
+      return rescod
+    }
+    return await this.auto.paw(req.user as number, dto)
+  }
+
   @Get('islogin')
   @UseGuards(AuthGuard('jwt'))
   islogin(@Req() req: Request) {
-    return true
+    return req.user
   }
 }

+ 25 - 0
src/auth/auth.service.ts

@@ -5,6 +5,7 @@ import { hash, verify } from 'argon2'
 import { PrismaService } from 'src/prisma/prisma.service'
 import LoginDto from './dto/login.dto'
 import registerDto from './dto/register.dto'
+import UpsetpawDto from './dto/upsetpaw.dto'
 
 @Injectable()
 export class AuthService {
@@ -43,6 +44,30 @@ export class AuthService {
     const token = await this.token(user)
     return { cod: 200, msg: '登陆成功', token }
   }
+  //修改密码
+  async paw(id: number, dto: UpsetpawDto) {
+    const user = await this.prisma.auth.findUnique({
+      where: {
+        auth_id: id,
+      },
+    })
+    if (!user) {
+      throw new BadRequestException('用户名错误')
+    }
+    if (!(await verify(user.password, dto.paw))) {
+      throw new BadRequestException('密码错误')
+    }
+    const paw = await hash(dto.newpaw)
+    await this.prisma.auth.update({
+      where: {
+        auth_id: id,
+      },
+      data: {
+        password: paw,
+      },
+    })
+    return { cod: 200, msg: '修改成功' }
+  }
   async token({ auth_id, username }: auth) {
     const token = await this.jwt.signAsync({
       username,

+ 8 - 0
src/auth/dto/upsetpaw.dto.ts

@@ -0,0 +1,8 @@
+import { IsNotEmpty } from 'class-validator'
+
+export default class UpsetpawDto {
+  @IsNotEmpty({ message: '密码不能为空' })
+  paw: string
+  @IsNotEmpty({ message: '新密码不能为空' })
+  newpaw: string
+}

+ 21 - 8
src/post/post.controller.ts

@@ -1,13 +1,14 @@
-import { Body, Controller, Delete, Get, Post, Put, Query, Req, UseGuards } from '@nestjs/common'
+import { Body, Controller, Delete, Get, Post, Put, Query, Req, UseGuards, Headers } from '@nestjs/common'
 import { PostService } from './post.service'
 import { AuthGuard } from '@nestjs/passport'
 import { Request } from 'express'
 import searchPostDto from './dto/search.post.dto'
 import { link } from 'fs'
+import { CodService } from '@/cod/cod.service'
 
 @Controller('post')
 export class PostController {
-  constructor(private readonly postService: PostService) {}
+  constructor(private readonly postService: PostService, private readonly codService: CodService) {}
   @Get('platelist')
   async getpostlist(@Query() { plateid, page, limit }) {
     if (page === undefined || limit === undefined) {
@@ -19,18 +20,25 @@ export class PostController {
   async getpost(@Query('id') id: number) {
     return await this.postService.getpost(+id)
   }
+
   @Post()
   @UseGuards(AuthGuard('jwt'))
-  async post(@Req() req: Request, @Body() { title, content, plateid }) {
-    return await this.postService.post(req.user as number, plateid, { title, content })
+  async post(@Req() req: Request, @Headers('code') code: string, @Body() { title, content, plateid }) {
+    const rescod = await this.codService.verifyCod(req.ip, code)
+    if (!rescod.status) {
+      return rescod
+    }
+    return await this.postService.post(req.user as number, +plateid, { title, content })
   }
   @Delete()
-  async delete(@Query('postid') postid: number) {
-    return await this.postService.delete(+postid)
+  @UseGuards(AuthGuard('jwt'))
+  async delete(@Req() req, @Query('postid') postid: number) {
+    return await this.postService.delete(req.user, +postid)
   }
   @Put()
-  async updated(@Body() { postid, title, content, plateId }) {
-    return await this.postService.updated(+postid, { title, content, plateId })
+  @UseGuards(AuthGuard('jwt'))
+  async updated(@Req() req, @Body() { postid, title, content, plateId }) {
+    return await this.postService.updated(req.user, +postid, { title, content, plateId })
   }
   @Get('getNewPost')
   async getNewPost(@Query('num') num: number) {
@@ -47,4 +55,9 @@ export class PostController {
   async getpostbyuserid(@Req() req: Request, @Query() { link, page }) {
     return await this.postService.getPostByUserId(req.user as number, page, link)
   }
+  // 增加浏览量
+  @Get('addview')
+  async addview(@Req() req, @Query('id') id: number) {
+    return await this.postService.addView(req.ip, +id)
+  }
 }

+ 51 - 11
src/post/post.service.ts

@@ -1,22 +1,31 @@
 import { PrismaService } from '@/prisma/prisma.service'
+import { RedisService } from '@/redis/redis.service'
 import { Injectable } from '@nestjs/common'
 
 @Injectable()
 export class PostService {
-  constructor(private readonly prisma: PrismaService) {}
+  constructor(private readonly prisma: PrismaService, private readonly redis: RedisService) {}
   async post(authId: number, plateid: number = 0, { title, content }) {
-    return await this.prisma.post.create({
+    const res = await this.prisma.post.create({
       data: {
         title,
         content,
         authorId: authId,
         plateId: plateid,
       },
+      select: { id: true },
     })
+    return { code: 200, message: '发帖成功', data: res }
   }
-  async updated(postid: number, { title, content, plateId }) {
-    if (((await this.getpost(postid)) as any).cod !== 400) {
-      return await this.prisma.post.update({
+  async updated(userId: number, postid: number, { title, content, plateId }) {
+    const post = (await this.getpost(postid)) as any
+    if (post.cod !== 400) {
+      console.log(userId)
+
+      if (userId !== post.author.auth_id) {
+        return { code: 400, message: '没有权限' }
+      }
+      const res = await this.prisma.post.update({
         where: {
           id: postid,
         },
@@ -25,13 +34,19 @@ export class PostService {
           content,
           plateId,
         },
+        select: { id: true },
       })
+      return { code: 200, message: '修改成功', data: res }
     }
     return { cod: 400, message: '帖子不存在' }
   }
 
-  async delete(postid: number) {
-    if (((await this.getpost(postid)) as any).cod !== 400) {
+  async delete(userId: number, postid: number) {
+    const post = (await this.getpost(postid)) as any
+    if (userId !== post.author.auth_id) {
+      return { code: 400, message: '没有权限' }
+    }
+    if (post.cod !== 400) {
       return await this.prisma.post.delete({
         where: {
           id: postid,
@@ -48,20 +63,17 @@ export class PostService {
       },
       include: {
         author: true,
-        plate: true,
         comment: true,
       },
     })
     if (!data) {
       return { cod: 400, message: '帖子不存在' }
     }
+
     delete data.author.password
     delete data.author.username
     delete data.author.email
-    delete data.plate.id
-    delete data.id
     delete data.authorId
-    delete data.plateId
 
     return data
   }
@@ -77,6 +89,7 @@ export class PostService {
           content: true,
           authorId: true,
           updatedAt: true,
+          views: true,
         },
       })
       const total = await this.prisma.post.count()
@@ -166,6 +179,7 @@ export class PostService {
         content: true,
         authorId: true,
         updatedAt: true,
+        views: true,
       },
     })
     const total = await this.prisma.post.count({
@@ -195,6 +209,7 @@ export class PostService {
         content: true,
         authorId: true,
         updatedAt: true,
+        views: true,
       },
     })
     const total = await this.prisma.post.count({
@@ -204,4 +219,29 @@ export class PostService {
     })
     return await this.res(total, data, limit)
   }
+  //增加浏览量
+  async addView(ip: string, postid: number) {
+    const data = await this.prisma.post.findUnique({
+      where: {
+        id: postid,
+      },
+      select: {
+        views: true,
+      },
+    })
+    if ((await this.redis.exists(`${ip}:views:${postid}`)) === 1 || (await this.redis.ttl(`ip:${postid}:views`)) > 0) {
+      return { cod: 200, data: data.views }
+    } else {
+      await this.redis.set(`${ip}:views:${postid}`, '', 'EX', 60 * 60 * 24)
+    }
+    await this.prisma.post.update({
+      where: {
+        id: postid,
+      },
+      data: {
+        views: data.views + 1,
+      },
+    })
+    return { cod: 200, message: '增加浏览量成功', data: data.views + 1 }
+  }
 }

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

@@ -30,4 +30,8 @@ export class UserinfoController {
   updateuserinfo(@Req() req: Request, @Body() dto: userInfoDto) {
     return this.userinfoService.updateuserinfo(req.user as number, dto)
   }
+  @Get('count')
+  async count(@Query('id') id: number) {
+    return await this.userinfoService.count(+id)
+  }
 }

+ 21 - 1
src/userinfo/userinfo.service.ts

@@ -19,7 +19,6 @@ export class UserinfoService {
     if (userinfo === null) {
       return { cod: 400, msg: '用户不存在' }
     }
-    delete userinfo.auth_id
     delete userinfo.user.authId
     delete userinfo.password
     return { cod: 200, msg: '获取成功', data: { ...userinfo } }
@@ -59,4 +58,25 @@ export class UserinfoService {
     })
     return { cod: 200, msg: '修改成功', data }
   }
+  async count(id: number) {
+    const mapleCoin = await this.prisma.userinfo.findUnique({
+      where: {
+        authId: id,
+      },
+      select: {
+        mapleCoin: true,
+      },
+    })
+    const post = await this.prisma.post.count({
+      where: {
+        authorId: id,
+      },
+    })
+    const reply = await this.prisma.comment.count({
+      where: {
+        authorId: id,
+      },
+    })
+    return { cod: 200, msg: '获取成功', data: { ...mapleCoin, post, reply } }
+  }
 }