Chapter 9. User Roles

Not all users of web applications are created equal. In most applications, a small percentage of users are trusted with extra powers to help keep the application running smoothly. Administrators are the best example, but in many cases middle-level power users such as content moderators exist as well. To implement this, all users are assigned a role.

There are several ways to implement roles in an application. The appropriate method largely depends on how many roles need to be supported and how elaborate they are. For example, a simple application may need just two roles, one for regular users and one for administrators. In this case, having an is_administrator Boolean field in the User model may be all that is necessary. A more complex application may need additional roles with varying levels of power in between regular users and administrators. In some applications it may not even make sense to talk about discrete roles, and instead giving users a set of individual permissions may be the right approach.

The user role implementation presented in this chapter is a hybrid between discrete roles and permissions. Users are assigned a discrete role, but each role defines what actions it allows its users to perform through a list of permissions.

Database Representation of Roles

A simple roles table was created in Chapter 5 as a vehicle to demonstrate one-to-many relationships. Example 9-1 shows an improved Role model with some additions.

Example 9-1. app/models.py ...

Get Flask Web Development, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.