Last active
May 25, 2018 02:13
-
-
Save axetroy/c7e5e2a8989795249b9dfe82a7372000 to your computer and use it in GitHub Desktop.
基于角色的访问控制
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface User { | |
username: string; | |
roles: string[]; | |
} | |
interface Role { | |
name: string; | |
desc: string; | |
permission: Permission[]; | |
} | |
export enum Permission { | |
// 新闻类 | |
NewsCreate, // 创建新闻 | |
NewsUpdate, // 更新新闻 | |
NewsDelete, // 删除新闻 | |
NewsQuery, // 查询新闻 | |
// 商户信息 | |
BusinessInfoUpdate, // 更新商户信息 | |
// 交易类别 | |
Buyable, // 是否可以参与购买 | |
Sellable, // 是否可以参与卖出 | |
// 用户类 | |
UserFreeze, // 冻结用户 (用户不能再使用) | |
// 钱包类别 | |
WalletMutation, // 用户钱包的变动 | |
// 权限类别 | |
PermissionMutation, // 更新权限的变动 | |
// 通用类 | |
Uploadable // 是否可以上传 | |
} | |
const Roles: Role[] = [ | |
{ | |
name: "User", | |
desc: "普通用户", | |
permission: [ | |
Permission.NewsQuery, | |
Permission.Buyable, | |
Permission.Sellable, | |
Permission.Uploadable | |
] | |
}, | |
{ | |
name: "Business", | |
desc: "商户", | |
permission: [ | |
Permission.NewsQuery, | |
Permission.BusinessInfoUpdate, | |
Permission.Uploadable | |
] | |
}, | |
{ | |
name: "Admin", | |
desc: "普通管理员", | |
permission: [ | |
// 新闻类别 | |
Permission.NewsCreate, | |
Permission.NewsUpdate, | |
Permission.NewsDelete, | |
Permission.NewsQuery, | |
// 用户类别 | |
Permission.UserFreeze | |
] | |
}, | |
{ | |
name: "SuperAdmin", | |
desc: "超级管理员", | |
permission: [ | |
// 新闻类别 | |
Permission.NewsCreate, | |
Permission.NewsUpdate, | |
Permission.NewsDelete, | |
Permission.NewsQuery, | |
// 用户类别 | |
Permission.UserFreeze, | |
// 只有超级管理员才有权限更改用户余额 | |
Permission.WalletMutation, | |
// 超级管理员才能更改权限 | |
Permission.PermissionMutation | |
] | |
} | |
]; | |
// 创建一个角色 | |
export function createRole( | |
name: string, | |
desc: string, | |
permission: Permission[] | |
) { | |
// TODO: 校验调用这个函数的权限 | |
if (Roles.findIndex(v => v.name === name) >= 0) { | |
throw new Error(`role ${name} exist!`); | |
} | |
Roles.push({ | |
name, | |
desc, | |
permission | |
}); | |
} | |
// 更新角色的权限 | |
export function updateRole(name: string, permission: Permission[]) { | |
// TODO: 校验调用这个函数的权限 | |
const index = Roles.findIndex(v => v.name === name); | |
if (index < 0) { | |
throw new Error(`role ${name} not exist!`); | |
} | |
Roles[index].name = name; | |
Roles[index].permission = permission; | |
} | |
// 检查一个用户是否有权限 | |
export function hasPermission(user: User, permission: Permission): boolean { | |
for (let role of user.roles) { | |
const Role = Roles.find(v => v.name === role); | |
if (Role) { | |
for (let per of Role.permission) { | |
if (per === permission) { | |
return true; | |
} | |
} | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment