今天记录一下rbac相关内容-创建role相关内容
一、 什么是RBAC
RBAC
是基于角色的访问控制(Role-Based Access Control )在 RBAC
中,权限与角色相关联,用户通过成为适当角色的成员而得到这些角色的权限。
这就极大地简化了权限的管理。这样管理都是层级相互依赖的,权限赋予给角色,而把角色又赋予用户,这样的权限设计很清楚,管理起来很方便。
RBAC
一般都是公司内部进行使用,如财务部成员拥有查看财务报表的权限,人事部的成员拥有查看近期公司人员入职离职情况的权限等。
例如下图,管理员和普通用户被授予不同的权限,普通用户只能去修改和查看个人信息,而不能创建创建用户和冻结用户,而管理员由于被授 予所有权限,所以可以做所有操作。
二、 接下来记录代码的实现
- 先创建用户表:user
- 创建权限表:role
- 创建权限与角色的关联表:role_access
- 创建角色表: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
}
}
}