Browse Source

新增权限管理员后台

枫叶秋林 2 years ago
parent
commit
7ce74417a6

+ 36 - 0
prisma/migrations/20221211123401_updata_init/migration 2.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;

+ 51 - 0
prisma/migrations/20221220073355_init_post_comment_pleate/migration 2.sql

@@ -0,0 +1,51 @@
+-- DropForeignKey
+ALTER TABLE `userinfo` DROP FOREIGN KEY `userinfo_authId_fkey`;
+
+-- CreateTable
+CREATE TABLE `post` (
+    `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
+    `title` VARCHAR(191) NOT NULL,
+    `content` VARCHAR(191) NOT NULL,
+    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
+    `updatedAt` DATETIME(3) NOT NULL,
+    `authorId` INTEGER UNSIGNED NOT NULL,
+    `plateId` INTEGER UNSIGNED NOT NULL,
+
+    PRIMARY KEY (`id`)
+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
+
+-- CreateTable
+CREATE TABLE `comment` (
+    `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
+    `content` VARCHAR(191) NOT NULL,
+    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
+    `updatedAt` DATETIME(3) NOT NULL,
+    `authorId` INTEGER UNSIGNED NOT NULL,
+    `postId` INTEGER UNSIGNED NOT NULL,
+
+    PRIMARY KEY (`id`)
+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
+
+-- CreateTable
+CREATE TABLE `plate` (
+    `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
+    `name` VARCHAR(191) NOT NULL,
+
+    UNIQUE INDEX `plate_name_key`(`name`),
+    PRIMARY KEY (`id`)
+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
+
+-- AddForeignKey
+ALTER TABLE `post` ADD CONSTRAINT `post_authorId_fkey` FOREIGN KEY (`authorId`) REFERENCES `auth`(`auth_id`) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE `post` ADD CONSTRAINT `post_plateId_fkey` FOREIGN KEY (`plateId`) REFERENCES `plate`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE `comment` ADD CONSTRAINT `comment_authorId_fkey` FOREIGN KEY (`authorId`) REFERENCES `auth`(`auth_id`) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE `comment` ADD CONSTRAINT `comment_postId_fkey` FOREIGN KEY (`postId`) REFERENCES `post`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE `userinfo` ADD CONSTRAINT `userinfo_authId_fkey` FOREIGN KEY (`authId`) REFERENCES `auth`(`auth_id`) ON DELETE RESTRICT ON UPDATE CASCADE;

+ 5 - 0
prisma/migrations/20230104012911_userinfo_add_nickname_github_qq_signature/migration 2.sql

@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE `userinfo` ADD COLUMN `QQ` VARCHAR(191) NOT NULL DEFAULT '',
+    ADD COLUMN `github` VARCHAR(191) NOT NULL DEFAULT '',
+    ADD COLUMN `nickname` VARCHAR(191) NOT NULL DEFAULT '',
+    ADD COLUMN `signature` VARCHAR(191) NOT NULL DEFAULT '这个家伙很懒,什么都没留下';

+ 2 - 0
prisma/migrations/20230109125426_setup_auth_add_jurisdiction/migration.sql

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

+ 1 - 0
prisma/schema.prisma

@@ -11,6 +11,7 @@ model auth{
   username  String  @unique
   username  String  @unique
   email     String  @unique
   email     String  @unique
   password  String
   password  String
+  jurisdiction Int @default(0) @db.UnsignedInt
   user      userinfo?
   user      userinfo?
   post      post[]
   post      post[]
   comment   comment[]
   comment   comment[]

+ 6 - 0
src/auth/auth.controller.ts

@@ -37,4 +37,10 @@ export class AuthController {
   islogin(@Req() req: Request) {
   islogin(@Req() req: Request) {
     return req.user
     return req.user
   }
   }
+
+  @Get('Permissions')
+  @UseGuards(AuthGuard('jwt'))
+  async Permissions(@Req() req: Request) {
+    return await this.auto.checkPermissions(req.user as number)
+  }
 }
 }

+ 3 - 1
src/auth/auth.module.ts

@@ -1,9 +1,10 @@
-import { Module } from '@nestjs/common'
+import { Global, Module } from '@nestjs/common'
 import { AuthService } from './auth.service'
 import { AuthService } from './auth.service'
 import { AuthController } from './auth.controller'
 import { AuthController } from './auth.controller'
 import { JwtModule } from '@nestjs/jwt'
 import { JwtModule } from '@nestjs/jwt'
 import { ConfigModule, ConfigService } from '@nestjs/config'
 import { ConfigModule, ConfigService } from '@nestjs/config'
 import { JwtStrategy } from './JwtStrategy'
 import { JwtStrategy } from './JwtStrategy'
+@Global()
 @Module({
 @Module({
   imports: [
   imports: [
     JwtModule.registerAsync({
     JwtModule.registerAsync({
@@ -21,5 +22,6 @@ import { JwtStrategy } from './JwtStrategy'
   ],
   ],
   providers: [AuthService, JwtStrategy],
   providers: [AuthService, JwtStrategy],
   controllers: [AuthController],
   controllers: [AuthController],
+  exports: [AuthService],
 })
 })
 export class AuthModule {}
 export class AuthModule {}

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

@@ -40,6 +40,9 @@ export class AuthService {
     if (!(await verify(user.password, dto.paw))) {
     if (!(await verify(user.password, dto.paw))) {
       throw new BadRequestException('密码错误')
       throw new BadRequestException('密码错误')
     }
     }
+    if (user.jurisdiction === 3) {
+      throw new BadRequestException('账号已被封禁')
+    }
     delete user.password
     delete user.password
     const token = await this.token(user)
     const token = await this.token(user)
     return { cod: 200, msg: '登陆成功', token }
     return { cod: 200, msg: '登陆成功', token }
@@ -75,4 +78,26 @@ export class AuthService {
     })
     })
     return token
     return token
   }
   }
+  //验证权限
+  async checkPermissions(id: number) {
+    const data = await this.prisma.auth.findUnique({
+      where: {
+        auth_id: id,
+      },
+      select: {
+        jurisdiction: true,
+      },
+    })
+    switch (data.jurisdiction) {
+      case 0:
+        return { cod: 200, msg: '普通用户' }
+      case 1:
+        return { cod: 200, msg: '管理员' }
+      case 2:
+        return { cod: 200, msg: '超级管理员' }
+      case 3:
+        return { cod: 200, msg: '封禁' }
+    }
+    return data
+  }
 }
 }

+ 5 - 4
src/comment/comment.module.ts

@@ -1,9 +1,10 @@
-import { Module } from '@nestjs/common';
-import { CommentService } from './comment.service';
-import { CommentController } from './comment.controller';
+import { Module } from '@nestjs/common'
+import { CommentService } from './comment.service'
+import { CommentController } from './comment.controller'
 
 
 @Module({
 @Module({
+  imports: [],
   controllers: [CommentController],
   controllers: [CommentController],
-  providers: [CommentService]
+  providers: [CommentService],
 })
 })
 export class CommentModule {}
 export class CommentModule {}

+ 24 - 18
src/comment/comment.service.ts

@@ -1,9 +1,11 @@
+import { AuthService } from '@/auth/auth.service'
 import { PrismaService } from '@/prisma/prisma.service'
 import { PrismaService } from '@/prisma/prisma.service'
 import { Injectable } from '@nestjs/common'
 import { Injectable } from '@nestjs/common'
+import e from 'express'
 
 
 @Injectable()
 @Injectable()
 export class CommentService {
 export class CommentService {
-  constructor(private readonly prisma: PrismaService) {}
+  constructor(private readonly prisma: PrismaService, private readonly auth: AuthService) {}
   // 发表评论
   // 发表评论
   async createComment(content: string, articleId: number, userId: number) {
   async createComment(content: string, articleId: number, userId: number) {
     const data = await this.prisma.comment.create({
     const data = await this.prisma.comment.create({
@@ -25,15 +27,17 @@ export class CommentService {
     if (!data) {
     if (!data) {
       return { cod: 400, msg: '评论不存在' }
       return { cod: 400, msg: '评论不存在' }
     }
     }
-    if (data.authorId !== userId) {
+    const Permissions = (await this.auth.checkPermissions(userId)) as any
+    if (data.authorId !== userId || Permissions.msg === '管理员' || Permissions.msg === '超级管理员') {
+      await this.prisma.comment.delete({
+        where: {
+          id: Commentid,
+        },
+      })
+      return { cod: 200, msg: '删除评论成功', data }
+    } else {
       return { cod: 400, msg: '无权删除评论' }
       return { cod: 400, msg: '无权删除评论' }
     }
     }
-    await this.prisma.comment.delete({
-      where: {
-        id: Commentid,
-      },
-    })
-    return { cod: 200, msg: '删除评论成功', data }
   }
   }
   async getComment(postId: number, page: number = 1, limit: number = 10) {
   async getComment(postId: number, page: number = 1, limit: number = 10) {
     const data = await this.prisma.comment.findMany({
     const data = await this.prisma.comment.findMany({
@@ -72,18 +76,20 @@ export class CommentService {
     if (!data) {
     if (!data) {
       return { cod: 400, msg: '评论不存在' }
       return { cod: 400, msg: '评论不存在' }
     }
     }
-    if (data.authorId !== userId) {
+    const Permissions = (await this.auth.checkPermissions(userId)) as any
+    if (data.authorId === userId || Permissions.msg === '管理员' || Permissions.msg === '超级管理员') {
+      await this.prisma.comment.update({
+        where: {
+          id: Commentid,
+        },
+        data: {
+          content: content,
+        },
+      })
+      return { cod: 200, msg: '修改评论成功', data }
+    } else {
       return { cod: 400, msg: '无权修改评论' }
       return { cod: 400, msg: '无权修改评论' }
     }
     }
-    await this.prisma.comment.update({
-      where: {
-        id: Commentid,
-      },
-      data: {
-        content: content,
-      },
-    })
-    return { cod: 200, msg: '修改评论成功', data }
   }
   }
   //根据id查看某条评论信息
   //根据id查看某条评论信息
   async getCommentByid(Commentid: number) {
   async getCommentByid(Commentid: number) {

+ 32 - 24
src/post/post.service.ts

@@ -1,10 +1,15 @@
+import { AuthService } from '@/auth/auth.service'
 import { PrismaService } from '@/prisma/prisma.service'
 import { PrismaService } from '@/prisma/prisma.service'
 import { RedisService } from '@/redis/redis.service'
 import { RedisService } from '@/redis/redis.service'
 import { Injectable } from '@nestjs/common'
 import { Injectable } from '@nestjs/common'
 
 
 @Injectable()
 @Injectable()
 export class PostService {
 export class PostService {
-  constructor(private readonly prisma: PrismaService, private readonly redis: RedisService) {}
+  constructor(
+    private readonly prisma: PrismaService,
+    private readonly redis: RedisService,
+    private readonly auth: AuthService,
+  ) {}
   async post(authId: number, plateid: number = 0, { title, content }) {
   async post(authId: number, plateid: number = 0, { title, content }) {
     const res = await this.prisma.post.create({
     const res = await this.prisma.post.create({
       data: {
       data: {
@@ -21,39 +26,42 @@ export class PostService {
     const post = (await this.getpost(postid)) as any
     const post = (await this.getpost(postid)) as any
     if (post.cod !== 400) {
     if (post.cod !== 400) {
       console.log(userId)
       console.log(userId)
-
-      if (userId !== post.author.auth_id) {
+      const Permissions = (await this.auth.checkPermissions(userId)) as any
+      if (userId === post.author.auth_id || Permissions.msg === '管理员' || Permissions.msg === '超级管理员') {
+        const res = await this.prisma.post.update({
+          where: {
+            id: postid,
+          },
+          data: {
+            title,
+            content,
+            plateId,
+          },
+          select: { id: true },
+        })
+        return { code: 200, message: '修改成功', data: res }
+      } else {
         return { code: 400, message: '没有权限' }
         return { code: 400, message: '没有权限' }
       }
       }
-      const res = await this.prisma.post.update({
-        where: {
-          id: postid,
-        },
-        data: {
-          title,
-          content,
-          plateId,
-        },
-        select: { id: true },
-      })
-      return { code: 200, message: '修改成功', data: res }
     }
     }
     return { cod: 400, message: '帖子不存在' }
     return { cod: 400, message: '帖子不存在' }
   }
   }
 
 
   async delete(userId: number, postid: number) {
   async delete(userId: number, postid: number) {
     const post = (await this.getpost(postid)) as any
     const post = (await this.getpost(postid)) as any
-    if (userId !== post.author.auth_id) {
+    const Permissions = (await this.auth.checkPermissions(userId)) as any
+    if (userId === post.author.auth_id || Permissions.msg === '管理员' || Permissions.msg === '超级管理员') {
+      if (post.cod !== 400) {
+        return await this.prisma.post.delete({
+          where: {
+            id: postid,
+          },
+        })
+      }
+      return { cod: 400, message: '帖子不存在' }
+    } else {
       return { code: 400, message: '没有权限' }
       return { code: 400, message: '没有权限' }
     }
     }
-    if (post.cod !== 400) {
-      return await this.prisma.post.delete({
-        where: {
-          id: postid,
-        },
-      })
-    }
-    return { cod: 400, message: '帖子不存在' }
   }
   }
 
 
   async getpost(postid: number) {
   async getpost(postid: number) {

BIN
src/userinfo/dto/.user.dto 2.ts.icloud


BIN
src/userinfo/dto/.userinfo.dto 2.ts.icloud


+ 0 - 37
src/userinfo/userinfo.controller 2.ts

@@ -1,37 +0,0 @@
-import { Body, Controller, Get, Post, Put, Query, Req, UseGuards } from '@nestjs/common'
-import { AuthGuard } from '@nestjs/passport'
-import { UserinfoService } from './userinfo.service'
-import { Request } from 'express'
-import userDateDto from './dto/userinfo.dto'
-import userInfoDto from './dto/user.dto'
-@Controller('userinfo')
-export class UserinfoController {
-  constructor(private readonly userinfoService: UserinfoService) {}
-  @Get()
-  @UseGuards(AuthGuard('jwt'))
-  async getinfo(@Req() req: Request) {
-    return await this.userinfoService.getinfo(req.user as number)
-  }
-  @Get('getuser')
-  async getuser(@Query('id') id: number) {
-    if (id) {
-      return await this.userinfoService.getinfo(+id)
-    } else {
-      return { cod: 400, message: '用户不存在' }
-    }
-  }
-  @Put()
-  @UseGuards(AuthGuard('jwt'))
-  updateinfo(@Req() req: Request, @Body() data: userDateDto) {
-    return this.userinfoService.updateinfo(req.user as number, data)
-  }
-  @Put('updateuserinfo')
-  @UseGuards(AuthGuard('jwt'))
-  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)
-  }
-}

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

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

+ 0 - 82
src/userinfo/userinfo.service 2.ts

@@ -1,82 +0,0 @@
-import { PrismaService } from '@/prisma/prisma.service'
-import { Injectable } from '@nestjs/common'
-import { auth } from '@prisma/client'
-import userDateDto from './dto/userinfo.dto'
-import userInfoDto from './dto/user.dto'
-
-@Injectable()
-export class UserinfoService {
-  constructor(private prisma: PrismaService) {}
-  async getinfo(id: number) {
-    const userinfo = await this.prisma.auth.findUnique({
-      where: {
-        auth_id: id,
-      },
-      include: {
-        user: true,
-      },
-    })
-    if (userinfo === null) {
-      return { cod: 400, msg: '用户不存在' }
-    }
-    delete userinfo.user.authId
-    delete userinfo.password
-    return { cod: 200, msg: '获取成功', data: { ...userinfo } }
-  }
-  async updateinfo(id: number, data: userDateDto) {
-    const userinfo = await this.prisma.auth.findUnique({
-      where: {
-        auth_id: id,
-      },
-      include: {
-        user: true,
-      },
-    })
-    const user = await this.prisma.userinfo.update({
-      where: {
-        authId: userinfo.user.authId,
-      },
-      data: {
-        avatar: data.avatar,
-        exp: data.exp,
-        level: data.level,
-      },
-    })
-    return { cod: 200, msg: '修改成功', data: user }
-  }
-  async updateuserinfo(id: number, dto: userInfoDto) {
-    const data = await this.prisma.userinfo.update({
-      where: {
-        authId: id,
-      },
-      data: {
-        QQ: dto.QQ,
-        nickname: dto.nickname,
-        github: dto.github,
-        signature: dto.signature,
-      },
-    })
-    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 } }
-  }
-}