表实体图
使用 node express mongoose 代码实现
js
npm init -y
npm install express mongoose
js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// 连接到MongoDB
mongoose
.connect('mongodb://localhost:27017/rbac_example', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('Could not connect to MongoDB', err));
// 定义User模型
const UserSchema = new mongoose.Schema({
username: String,
password: String,
email: String
});
const User = mongoose.model('User', UserSchema);
// 定义Role模型
const RoleSchema = new mongoose.Schema({
name: String
});
const Role = mongoose.model('Role', RoleSchema);
// 定义Permission模型
const PermissionSchema = new mongoose.Schema({
name: String,
resource: String
});
const Permission = mongoose.model('Permission', PermissionSchema);
// 定义User-Role关联模型
const UserRoleAssociationSchema = new mongoose.Schema({
user_id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
role_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Role'}
});
const UserRoleAssociation = mongoose.model('UserRoleAssociation', UserRoleAssociationSchema);
// 定义Role-Permission关联模型
const RolePermissionAssociationSchema = new mongoose.Schema({
role_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Role'},
permission_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Permission'}
});
const RolePermissionAssociation = mongoose.model('RolePermissionAssociation', RolePermissionAssociationSchema);
// 创建API端点(仅用于测试)
// app.post('/seed', async (req, res) => {
// try {
// await User.insertMany([
// { username: 'alice', password: 'hashed_pwd', email: 'alice@xyz.com' },
// { username: 'bob', password: 'hashed_pwd', email: 'bob@xyz.com' },
// ]);
// await Role.insertMany([
// { name: 'admin' },
// { name: 'editor' },
// { name: 'visitor' },
// ]);
// await Permission.insertMany([
// { name: 'create_post', resource: 'posts' },
// { name: 'read_post', resource: 'posts' },
// { name: 'update_post', resource: 'posts' },
// { name: 'delete_post', resource: 'posts' },
// ]);
// res.send('Data seeded successfully');
// } catch (error) {
// console.error(error);
// res.status(500).send('Error seeding data');
// }
// });
// 添加JSON解析中间件
app.use(express.json());
// 创建用户
app.post('/users', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).send(user);
} catch (error) {
res.status(400).send(error.message);
}
});
// 获取所有用户
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.send(users);
} catch (error) {
res.status(500).send(error.message);
}
});
// 获取指定用户
app.get('/users/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).send('User not found');
}
res.send(user);
} catch (error) {
res.status(500).send(error.message);
}
});
// 更新用户
app.put('/users/:id', async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, {new: true});
if (!user) {
return res.status(404).send('User not found');
}
res.send(user);
} catch (error) {
res.status(400).send(error.message);
}
});
// 删除用户
app.delete('/users/:id', async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) {
return res.status(404).send('User not found');
}
res.send(user);
} catch (error) {
res.status(500).send(error.message);
}
});
// 创建角色
app.post('/roles', async (req, res) => {
try {
const role = new Role(req.body);
await role.save();
res.status(201).send(role);
} catch (error) {
res.status(400).send(error.message);
}
});
// 获取所有角色
app.get('/roles', async (req, res) => {
try {
const roles = await Role.find();
res.send(roles);
} catch (error) {
res.status(500).send(error.message);
}
});
// 获取指定角色
app.get('/roles/:id', async (req, res) => {
try {
const role = await Role.findById(req.params.id);
if (!role) {
return res.status(404).send('Role not found');
}
res.send(role);
} catch (error) {
res.status(500).send(error.message);
}
});
// 更新角色
app.put('/roles/:id', async (req, res) => {
try {
const role = await Role.findByIdAndUpdate(req.params.id, req.body, {new: true});
if (!role) {
return res.status(404).send('Role not found');
}
res.send(role);
} catch (error) {
res.status(400).send(error.message);
}
});
// 删除角色
app.delete('/roles/:id', async (req, res) => {
try {
const role = await Role.findByIdAndDelete(req.params.id);
if (!role) {
return res.status(404).send('Role not found');
}
res.send(role);
} catch (error) {
res.status(500).send(error.message);
}
});
// 添加用户角色关联
app.post('/user-role-associations', async (req, res) => {
try {
const userRoleAssociation = new UserRoleAssociation(req.body);
await userRoleAssociation.save();
res.status(201).send(userRoleAssociation);
} catch (error) {
res.status(400).send(error.message);
}
});
// 添加角色权限关联
app.post('/role-permission-associations', async (req, res) => {
try {
const rolePermissionAssociation = new RolePermissionAssociation(req.body);
await rolePermissionAssociation.save();
res.status(201).send(rolePermissionAssociation);
} catch (error) {
res.status(400).send(error.message);
}
});
// 获取用户的角色
app.get('/users/:id/roles', async (req, res) => {
try {
const userRoleAssociations = await UserRoleAssociation.find({user_id: req.params.id}).populate('role_id');
const roles = userRoleAssociations.map((association) => association.role_id);
res.send(roles);
} catch (error) {
res.status(500).send(error.message);
}
});
// 获取角色的权限
app.get('/roles/:id/permissions', async (req, res) => {
try {
const rolePermissionAssociations = await RolePermissionAssociation.find({role_id: req.params.id}).populate(
'permission_id'
);
const permissions = rolePermissionAssociations.map((association) => association.permission_id);
res.send(permissions);
} catch (error) {
res.status(500).send(error.message);
}
});
// 删除用户角色关联
app.delete('/user-role-associations/:id', async (req, res) => {
try {
const userRoleAssociation = await UserRoleAssociation.findByIdAndDelete(req.params.id);
if (!userRoleAssociation) {
return res.status(404).send('User role association not found');
}
res.send(userRoleAssociation);
} catch (error) {
res.status(500).send(error.message);
}
});
// 删除角色权限关联
app.delete('/role-permission-associations/:id', async (req, res) => {
try {
const rolePermissionAssociation = await RolePermissionAssociation.findByIdAndDelete(req.params.id);
if (!rolePermissionAssociation) {
return res.status(404).send('Role permission association not found');
}
res.send(rolePermissionAssociation);
} catch (error) {
res.status(500).send(error.message);
}
});
// 启动服务器
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});