简体   繁体   中英

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. The roles will be stored within the SQL database (using MS SQL but this should be a design independent of the implementation).

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:

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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