12

I have gone through the question, best way to implement privacy on each field in model django and Its answers doesn't seem solve my problem so I am asking some what related question here,

well, I have a User model. I want the user to make possible to control the privacy of each and every field of their profile (may be gender, education, interests etc . ..).

The privacy options must not to be limited to just private or public, but as descriptive as

  • public
  • friends
  • only me
  • friend List 1 (User.friendlist.one)
  • friend List 2 (User.friendlist.two)
  • friend List 3 (User.friendlist.three)
  • another infinte lists that user may create.

I also don't want these privacy options to be saved on another model, but the same so that with one query I could get the user object along with the privacy options.

so If I have the UserModel,

class User(models.Model):
    name = models.CharField()
    email = models.EmailField()
    phone = models.CharField()

How do I setup a privacy setting here? I am using postgres, can I map a JSON field or Hstore even an ArrayField?

what is the best solution that people used to do with Django with same problem?

update:

I have n model fields. What I really want is to store the privacy settings of each instance on itself or some other convenient way.

5 Answers 5

9

I have worked on my issue, tried solutions with permissions and other relations. I have a Relationship Model and all other relationship lists are derived from the Relationship model, so I don't want to maintain a separate list of Relationships.

So my pick was to go with a Postgres JSONField or HStoreField. Since Django has good support for postgres freatures, I found these points pro for the choice I made.

  • JSON/HashStore can be queried with Django ORM.
  • The configurations are plain JSON/HashStore which are easy to edit and maintain than permissions and relations.
  • I found database query time taken are larger with permissions than with JSON/HStore. (hits are higher with permissions)
  • Adding and validating permissions per field are complex than adding/validating JSON.
  • At some point in future if comes a more simple or hassle free solution, I can migrate to it having whole configuration at a single field.

So My choice was to go with a configuration model.

class UserConfiguration(models.Model):
    user = # link to the user model
    configuration = #either an HStore of JSONFeild

Then wrote a validator to make sure configuration data model is not messed up while saving and updating. I grouped up the fields to minimize the validation fields. Then wrote a simple parser that takes the users and finds the relationship between them, then maps with the configuration to return the allowed field data (logged at 2-4ms in an unoptimized implementation, which is enough for now). (With permission's I would need a separate list of friends to be maintained and should update all the group permissions on updation of privacy configuration, then I still have to validate the permissions and process it, which may take lesser time than this, but for the cost of complex system).

I think this method is scalable as well, as most of the processing is done in Python and database calls are cut down to the least as possible.

Update

I have skinned down database queries further. In the previous implementation the relations between users where iterated, which timed around 1-2ms, changing this implementation to .value_list('relations', flat=True) cut down the query time to 400-520µs.

1
  • 1
    Smart solution! I just want to point out, why I usually like my database to gather stuff and ensure data integrity using constraints etc.: Because it is designed to do exactly that. The main problem with databases and ORM are to many queries. The amount of separate queries slows things down, not the database resolving data. Postgresql will always be faster than python, as it is optimized for very large amounts of data. When storing data in JSON - the database can no longer do its job on this data. This is what I prefer to avoid. But I agree: storing permissions can cause headaches! :)
    – dahrens
    Mar 3, 2017 at 21:17
8

I also don't want these privacy options to be saved on another model, but the same so that with one query I could get the user object along with the privacy options.

I would advice you to decouple the privacy objects from the UserModel, to not mess your users data together with those options. To minimize the amount of database queries, use djangos select_related and prefetch_related.

The requirements you have defined IMO lead to a set of privacy related objects, which are bound to the UserModel. django.contrib.auth is a good point to start with in this case. It is build to be extendable. Read the docs on that topic.

If you expect a large amount of users and therefore also an even larger amount of groups you might want to consider writing the permissions resolved for one user in a redis based session to be able to fetch them quickly on each page load.

UPDATE:

I thought a little more about your requirements and came to the conclusion that you need per object permission as implemented in django-guardian. You should start reading their samples and code first. They build that on top of django.contrib.auth but without depending on it, which makes it also usable with custom implementations that follow the interfaces in django.contrib.auth.

10
  • okay I would try to optimise the database, but for now I am not sure on the data structure to hold the permission settings. What data structure can hold the per field permission?
    – user5170375
    Feb 18, 2017 at 13:54
  • vanilla django groups and the attached permissions fit quite nice. Have a look at the linked documentation on how to customize them.
    – dahrens
    Feb 18, 2017 at 13:56
  • i was referring privacy setting as permission but not the User permission stuff like is_admin, is_staff etc..
    – user5170375
    Feb 18, 2017 at 14:05
  • If you look in your database with an installed django admin (which uses the permissions implemented by contrib auth) you will see several more permission related things there. In detail there will be change, add and delete permissions for each installed model. And you can make use of this for your own custom permissions. Have a look at the table auth_permission or something similar.
    – dahrens
    Feb 18, 2017 at 14:08
  • you can customize it to build your own logic based on this. The approach used there will fit. Think of custom permissions like can_view_users_gender. Nothing stops you from creating those permissions automatically based on your users attributes.
    – dahrens
    Feb 18, 2017 at 14:10
6
+75

What about something like this?

class EditorList(models.Model):
    name = models.CharField(...)
    user = models.ForeignKey(User)
    editor = models.ManyToManyField(User)

class UserPermission(models.Model):
    user = models.ForeignKey(User)
    name = models.BooleanField(default=False)
    email = models.BooleanField(default=False)
    phone = models.BooleanField(default=False)
    ...
    editor = models.ManyToManyField(User)
    editor_list = models.ManyToManyField(EditorList)

If a user wants to give 'email' permissions to public, then she creates a UserPermission with editor=None and editor_list=None and email=True.

If she wants to allow user 'rivadiz' to edit her email, then she creates a UserPermission with editor='rivadiz' and email=True.

If she wants to create a list of friends that can edit her phone, then she creates and populates an EditorList called 'my_friends', then creates a UserPermission with editor_list='my_friends' and phone=True

You should then be able to query all the users that have permission to edit any field on any user. You could define some properties in the User model for easily checking which fields are editable, given a User and an editor. You would first need to get all the EditorLists an editor belonged to, then do something like

perms = UserPermissions.objects.filter(user=self).filter(Q(editor=editor) | Q(editor_list=editor_list))

4
  • Thank you for the time but this solution is not scalable for n fields. more details is the updated question.
    – user5170375
    Feb 22, 2017 at 7:06
  • 1
    Well, instead of UserPermission having individual fields, you could have a json object that stored 'field': bool pairs.
    – Rob L
    Feb 23, 2017 at 15:44
  • yeah - discussed an solution using json field with a co-worker yesterday. this would work - it violates database concepts and makes django queries not usable for the privacy related data - because you'll need to parse this user related json on each request. But in combination with good caching it might be an option as it quite simple to implement. Depending on the amount of expected users it might fit.
    – dahrens
    Feb 23, 2017 at 19:56
  • I see you want the perms to be stored with the model, but I don't see any way to do that without a json field, which is effectively just imitating a m2m relationship, isn't it?
    – Rob L
    Feb 23, 2017 at 20:53
6

First of all, in my opinion you should go for multiple models and for making the queries faster, as already mentioned in other answers, you can use caching or select_related or prefetch_related as per your usecase.

So here is my proposed solution:

User model

class User(models.Model):
    name = models.CharField()
    email = models.EmailField()
    phone = models.CharField()
    ...
    public_allowed_read_fields = ArrayField(models.IntegerField())
    friends_allowed_read_fields = ArrayField(models.IntegerField())
    me_allowed_read_fields = ArrayField(models.IntegerField())
    friends = models.ManyToManyField(User)
    part_of = models.ManyToManyField(Group, through=GroupPrivacy)

Group(friends list) model

class Group(models.Model):
    name = models.CharField()

Through model

class GroupPrivacy(models.Model):
    user = models.ForeignKey(User)
    group = models.ForeignKey(Group)
    allowed_read_fields = ArrayField(models.IntegerField())

User Model fields mapping to integers

USER_FIELDS_MAPPING = (
    (1, User._meta.get_field('name')),
    (2, User._meta.get_field('email')),
    (3, User._meta.get_field('phone')),
    ...
)

HOW DOES THIS HELPS??

  • for each of public, friends and me, you can have a field in the User model itself as already mentioned above i.e. public_allowed_read_fields, friends_allowed_read_fields and me_allowed_read_fields respectively. Each of this field will contain a list of integers mapped to the ones inside USER_FIELDS_MAPPING(explained in detail below)

  • for friend_list_1, you will have group named friend_list_1. Now the point is the user wants to show or hide a specific set of fields to this friends list. That's where the through model, GroupPrivacy comes into the play. Using this through model you define a M2M relation between a user and a group with some additional properties which are unique to this relation. In this GroupPrivacy model you can see allowed_read_fields field, it is used to store an array of integers corresponding to the ones in the USER_FIELDS_MAPPING. So lets say, for group friend_list_1 and user A, the allowed_read_fields = [1,2]. Now, if you map this to USER_FIELDS_MAPPING, you will know that user A wants to show only name and email to the friends in this list. Similarly different users in friend_list_1 group will have different values in allowed_read_fields for their corresponding GroupPrivacy model instance.

This will be similar for multiple groups.

5

This will be much more cumbersome without a separate permissions model. The fact that you can associate a given field of an individual user's profile with more than one friend list implies a Many to Many table, and you're better off just letting Django handle that for you.

I'm thinking something more like:

class Visibility(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    field = models.CharField(max_length=32)
    public = models.BooleanField(default=False)
    friends = models.BooleanField(default=False)
    lists = models.ManyToManyField(FriendList)

    @staticmethod
    def visible_profile(request_user, profile_user):
        """Get a dictionary of profile_user's profile, as
           should be visible to request_user..."""

(I'll leave the details of such a method as an exercise, but it's not too complex.)

I'll caution that the UI involved for a user to set those permissions is likely to be a challenge because of the many-to-many connection to friend lists. Not impossible, definitely, but a little tedious.

A key advantage of the M2M table here is that it'll be self-maintaining if the user or any friend list is removed -- with one exception. The idea in this scheme is that without any Visibility records, all data is private (to allow everyone to see your name, you'd add a Visibility record with user=(yourself), field="name", and public=True. Since a Visibility record where public=False, friends=False, and lists=[] is pointless, I'd check for that situation after the user edits it and remove that record entirely.

Another valid strategy is to have two special FriendList records: one for "public", and one for "all friends". This simplifies the Visibility model quite a bit at the expense of a little more code elsewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.