nestjs-学习笔记-RBAC权限管理(01)

本文介绍了基于角色的访问控制(RBAC)的概念,以及如何在NestJS应用中实现RBAC。通过创建用户、权限、角色和关联表,实现了对权限的层级管理。详细展示了从创建控制器、服务到数据库模型的全过程,包括增删改查操作,以管理员和普通用户的权限示例说明了RBAC的实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天记录一下rbac相关内容-创建role相关内容

一、 什么是RBAC

RBAC是基于角色的访问控制(Role-Based Access Control )在 RBAC中,权限与角色相关联,用户通过成为适当角色的成员而得到这些角色的权限。

这就极大地简化了权限的管理。这样管理都是层级相互依赖的,权限赋予给角色,而把角色又赋予用户,这样的权限设计很清楚,管理起来很方便。

RBAC一般都是公司内部进行使用,如财务部成员拥有查看财务报表的权限,人事部的成员拥有查看近期公司人员入职离职情况的权限等。

 例如下图,管理员和普通用户被授予不同的权限,普通用户只能去修改和查看个人信息,而不能创建创建用户和冻结用户,而管理员由于被授 予所有权限,所以可以做所有操作。

 二、 接下来记录代码的实现

  1. 先创建用户表:user
  2. 创建权限表:role
  3. 创建权限与角色的关联表:role_access
  4. 创建角色表:access

1. 创建权限表,并在nestjs项目中,实现对权限表的增删改查功能;

执行下面的命名,创建role.controller.ts 控制器(会在对应的module文件中自动引入,如果没有引入,自己手动引入一下)

nest g co module/admin/role

module下的目录结构为:

module

        role

                role.controller.spec.ts

                role.controller.ts

import { Controller, Get, Render, Post, Query, Response, Body } from '@nestjs/common';
import { RoleService } from 'src/service/role/role.service';
import { ToolsService } from 'src/service/tools/tools.service';
import { Config } from 'src/config/config'

@Controller(`${Config.adminPath}/role`)
export class RoleController {
    constructor(private roleService: RoleService, private toolsService: ToolsService){}
    @Get()
    @Render('admin/role/index')
    async index() {
        const result = await this.roleService.find()
        console.log(result);
        
        return {
            roleList: result
        }
    }

    @Get('add')
    @Render('admin/role/add')
    add() {
        return {}
    }

    @Post('doAdd')
    async doAdd(@Body() body, @Response() res) {
        console.log(body, 'body');
        
        if (body.title !== '') {
            const result = await this.roleService.add(body)
            if(result) {
                this.toolsService.success(res, `/${Config.adminPath}/role`)
            }else {
                this.toolsService.error(res, '添加权限失败', `/${Config.adminPath}/role`)
            }
        } else {
            this.toolsService.error(res, '标题不能为空', `/${Config.adminPath}/role`)
        }
    }

    @Get('edit')
    @Render('admin/role/edit')
    async eidt(@Query() query) {
        const result = await this.roleService.find({_id: query.id})
        return {
            roleList: result[0]
        }
    }

    @Post('doEdit')
    async doEdit(@Body() body, @Response() res) {
        if(body.title !== '') {
            const result = await this.roleService.update({_id: body._id}, body)
            if(result) {
                this.toolsService.success(res, `/${Config.adminPath}/role`)
            }else {
                this.toolsService.error(res, '修改权限失败', `/${Config.adminPath}/role`)
            }
        } else {
            this.toolsService.error(res, '标题不能为空', `/${Config.adminPath}/role`)
        }
    }

    @Get('delete')
    async delete(@Query() query, @Response() res) {
        const result = await this.roleService.delete({_id: query.id})
        console.log(result);
        this.toolsService.success(res, `/${Config.adminPath}/role`)
    }

}

2. 创建schema约束数据结构,role.schema.ts

schema下的目录结构为:

schema

        role.schema.ts

import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
const dateTime = new Date()
export const RoleSchema = new mongoose.Schema({
    title: {
        type: String,
    },
    description: {
        type: String,
    },
    status: {
        type: Number,
        default: 1
    },
    add_time: {
        type: Number,
        default: dateTime.getTime()
    },
});

3. 在admin.module.ts文件中使用schema

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { RoleSchema } from 'src/schema/role.schema';

@Module({
    imports: [
        MongooseModule.forFeature([
            {
                name: 'Role',
                schema: RoleSchema,
                collection: "role"
            }
        ]),
    ],
    controllers: [RoleController],
    providers: [RoleService]
})
export class AdminModule { }

4. 执行下面的命令,创建role.service.ts

nest g s service/role

service目录结构为:

service

        role

                role.service.spec.ts

                role.service.ts

 定义数据库操作方法并export导出

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { RoleInterface } from 'src/interface/role.interface';
@Injectable()
export class RoleService {
    constructor(@InjectModel('Role') private readonly roleService) {}
    async find(params: RoleInterface = {}, files?: string) {
        try {
            return await this.roleService.find(params, files)
        } catch (error) {
            return []
        }
    }

    async add(params: RoleInterface) {
        try {
            const role = new this.roleService(params)
            const result = await role.save()
            return result
        } catch (error) {
            return null
        }
    }

    async update(oldParams: RoleInterface, newParams: RoleInterface) {
        try {
            const result = await this.roleService.update(oldParams, newParams)
            return result
        } catch (error) {
            return null
        }
    }

    async delete(params: RoleInterface) {
        try {
            const result = await this.roleService.deleteOne(params)
            return result
        } catch (error) {
            return null
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值