Role Based Access Control is a system in which you give particular permissions to particular users based on their roles. In this article we will try making simple role based access control for your application.
Our RBAC will make use of only 5 tables. I guess this is enough if your making it real simple. The tables will be users, roles, permissions, user_roles and role_permissions.
Users
User table will keep information of the users like username password and others info. You can also save token in this tables in you are making apis.
Roles
This will store all the roles like admin, staff, moderator etc.
Permissions
This table contains all the permissions like permission to create user, permission to access users private info, etc.
User_roles
This is mapping of users to roles. This will tell which user is admin, which user is staff and so on.
Role_permissions
Mapping of role to permissions. It tells which role can access what things. like admin has permission to edit and all.
By using the above two tables we get the mapping from user to permissions and they are simple grouped into different categories also.
This is just to give you basic idea how these systems are made. They use the same architecture just add few more things like expiry time, rate limiting etc which makes the system more sophisticated.
You can now make simple utility functions around these tables and use them again and again. Few functions can be
Function get_role(user){ //gives role of user }
Function get_permission(role){ //gives permission of role }
Function user_has_permission(user, permission){ //checks if user has permission role = get_role(user); user_permission = get_permission(role); if( permission in user_permission ){ return true; } else{ return false; } }
Note:
If you are making an app and thinking of implementing it. Please don’t, you will just end up wasting your time on reinventing something which is already made. Try finding one and use it. This is something recommended by everyone. In this era of micro services making whole module from scratch which is already present is not a good decision.
One of such RBAC app for Django is present at https://github.com/chowmean/DjangoRolePermissionTokenAuthorisation.
If you are interested try making some changes to it and raise Pull Requests.
2 COMMENTS
i need same in flask
https://flask-rbac.readthedocs.io/en/latest/ Check this out