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.
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; instead, giving users a combination of 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 the roles are defined in terms of permissions.
Database Representation of Roles
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.
Get Flask Web Development 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.