简体   繁体   English

设计帮助:多个用户角色

[英]Design help: Multiple User Roles

I'm currently in the process of designing a web app that requires the use of user permissions and roles. 我目前正在设计一个需要使用用户权限和角色的Web应用程序。 The roles will be stored within the SQL database (using MS SQL but this should be a design independent of the implementation). 角色将存储在SQL数据库中(使用MS SQL,但这应该是独立于实现的设计)。

What is the standard practice for allowing a user to have multiple roles, a "One to Many" relationship if you will. 允许用户具有多个角色的标准做法是什么,如果可以的话,是“一对多”关系。

What I came up with conceptually is the idea of a int field that uses a bit flag to determine if the user has that role: 我从概念上想到的是一个int字段的概念,该字段使用位标志来确定用户是否具有该角色:

User Group | Permission Mask | Value
-------------------------------------
Basic      | 0 0 0 0 1       | 1
Advanced   | 0 0 0 1 0       | 2
...        |    ...          | ...
Admin      | 1 0 0 0 0       | 16

This way, on my PHP side's authentication I can quickly math out if a user belongs to the role or not. 这样,通过我的PHP身份验证,我可以快速算出用户是否属于角色。 The biggest drawback I see with this is readability and understanding. 我看到的最大缺点是可读性和理解性。 For someone not involved with this design decision would they be able to figure out what's going on when maintenance/upgrades (new roles) come along? 对于不参与此设计决策的人员,他们是否能够弄清楚在进行维护/升级(新角色)时会发生什么情况?

Is this appropriate for my needs? 这适合我的需求吗? Is there a more standardized way of allowing users to have multiple roles/groups? 是否存在允许用户具有多个角色/组的更标准的方式?

User
------------
Id
Name


Roles
-----------
Id
Name


UserRoles - the UserID,RoleID combination has to be unique
-----------
UserId,
RoleId


Groups
------------
Id
GroupName


UserGroups - UserID, GroupID combination has to be unique
--------------
UserId
GroupId

Sample Data 样本数据

UserRoles
----------------------------------------------
UserID  | RoleID
--------------------------
123       ADMIN
123       EDITOR
124       SITE-USER

Queries 查询

-- if no rows returned, then user does not belong to role
Select 1 From UserRoles Where UserID=123 AND RoleID='ADMIN'

-- get user roles
Select ur.ID, ur.Name From UserRoles ur
JOIN Role r ON ur.RoleID = r.RoleID
JOIN Users u ON ur.UserID = u.UserID
WHERE u.UserID = 123

You should do something simple. 您应该做一些简单的事情。 It's a *-* relationship, why not implement it that way in the database? 这是一个*-*关系,为什么不以这种方式在数据库中实现它呢? You would only need 2 more tables to map these roles to individual users, you could easily add new roles, and this would make sense for potential newcomers. 您仅需要2个表即可将这些角色映射到各个用户,可以轻松添加新角色,这对潜在的新手来说很有意义。 Of course you would have to hardcode role access to functionalities initially, but you would have an easier upgrade path, would you want to have the whole thing configurable. 当然,最初您必须对角色对功能的访问进行硬编码,但是如果要使整个事情可配置,则升级路径会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM