3
votes

I'm reading the Flask Web Development book by Miguel Grinberg and I'm confused by how he's setting the Permissions for the various tasks in the app. Is he just setting random bit values for each of the tasks?

class Permission:
    FOLLOW = 0x01
    COMMENT = 0x02
    WRITE_ARTICLES = 0x04
    MODERATE_COMMENTS = 0x08
    ADMINISTER = 0x80

He goes on to say "each task will be assigned a bit position, and for each role the tasks that are allowed for that role will have their bits set to 1." I'm not really sure what he means.

1

1 Answers

7
votes

Represent each permission flag as an 8-bit binary integer:

class Permission:
    FOLLOW            = 0b00000001
    COMMENT           = 0b00000010
    WRITE_ARTICLES    = 0b00000100
    MODERATE_COMMENTS = 0b00001000
    ADMINISTER        = 0b10000000

Notice how for each flag, the 1 is in its own column. That way, you can bitwise OR together multiple flags to give a user any combination of permissions:

   0b00000001  # FOLLOW
   0b00000010  # COMMENT
|  0b00000100  # WRITE_ARTICLES
=============
   0b00000111  # FOLLOW, COMMENT, and WRITE_ARTICLES

To test if a user has a given permission, you bitwise AND it with a given flag:

   0b10000101  # ???
&  0b10000000  # ADMINISTER
=============
   0b10000000  # The result isn't 0, so the user has the ADMINISTER flag

It's just a space-efficient way to encode a fixed number of permissions in an integer.