How best to handle m2m relationships within an API - django

I'm busy creating an API using django with tastypie. I'm at a bit of a loss on how I should manage the foreign key relationship updates. I have User and Group objects related in a many-to-many fashion. Tastypie offers functionality for me to update the related set within each update, ie when I update a group I must supply the whole corresponding user set.
Ideally I'd like to have separate functionality to add and remove relationships. Consider the fact that 1 group has 1000 users, and I simply want to remove 2 users. I would love to access a url and give the 2 users that need to be deleted instead of loading the group object with its 1000 users, removing 2, then sending 998 users back along with the group details.
What is the correct design method to handle this case? Considering my use of tastypie, how can I best implement this practically?

Related

Django Graphene/GraphQL best design for model field-level permissions

I am using Django as back-end with graphene-django serving the front-end. I am new to both django and graphene so I am not sure what is the best approach to achieve field-level permissions with no code repetition in this set-up. For example, if my model is:
class MyModel(models.Model):
field1 = models.CharField()
field2 = models.CharField()
I want to be able to specify that user1 can read field1 but not field2; when the user1 queries GraphQL for all MyModels it would be only allow to retrieve field1 from rows (nodes) and not field2.
I did a bit of research and found 2 possible alternative solutions but I fear they may not be in the spirit of Django framework and/or conflicting with each other and there may be a better way to achieve this in Django. Ultimately I don't want to be repeating the permissions code in multiple parts of the Django and Graphene back-end so want this to be centralised at the lowest possible level, ideally at the Django model. I need to be able to control full CRUD per field depending on user_id and maybe even have some additional logic. The options I found were:
overriding get_node resolver in graphene-django DjangoObjectType to check for permissions there. Personally I see this as a very bad and last-resort solution as the checks are done only on graphql query/mutation layer and not elsewhere in Django. I could easily write a Django form or view that would not benefit from the permission check unless this is coded again in that form/view.
I could extend the Django model to perform arbitrary per-field checks and this seems the right level where to enforce permission checks but ideally I would prefer to use built-in features or a 'popular' library for this type of stuff. I tried searching for a library but I couldn't find anything that is even remotely production ready or gaining any traction - which leads me to the consider that there may be a better approach to address this problem. Django-field-permissions package seemed on the right path though.
I was wondering if anyone has a view on the best approach to solving this problem that fits Django and Graphene frameworks and without repeating the permissions code everywhere?
You're not going to find a stable/popular package for this, as it's not a design that a database can support well.
You cannot link (Foreign Key) a field and a table, you can only link two tables using a field. Therefore, any work to determine whether a row in a table has access to a field in another table, will be costly and error prone.
The best you could do, is to write a service layer that sits in between a resolver and a model that nullifies fields a user has no access to. You pass it the user (info.context.user) and a model, and it does a separate query to a field permissions model, fetches the record and nullifies each field according to permissions.
This inherently means each field needs to be nullable in order to support the permissions, complicating the frontend - it's a lot of work...
A better approach if your business logic allows it, is to group those fields into models, that can then be tied to "roles" or groups. So if this were medical data in a hospital:
- name ----- \
- address | -> Person model => all personnel, except custodial
- birth date -/
- medication -------\
- patient history | => PatientStatus model => all medically trained personnel
- current physician /
- ...
That way you use standard built-in permissions to deny access to entire tables (as illustrated above) and object level permissions (Guardian, Authority) to deny access to all but the current physician for the really classified things.
Hope this helps and good luck!

Accessing a distant relation using $owner in loopback

I just started using loopback, and I am stuck with ACL. My database has a relation like so:
User has many tests and tests have many users ( many to many, in loopback I am using hasmanythrough).
Each test has several sections (one to many)
Each section has several question(one to many)
Now, I want to get all sections that a user has , or all questions that a user has. I know that using $owner needs a belongsTo in the respective model, but in my case that is not possible.
Is there any way to achieve this without having to completely write my own queries ?
Unfortunately the $owner role doesn't work as a filter, but as security access to end-points when an instance ID is specified; basically it only works when you perform a findById, but not when you perform a find.
Example:
GET /api/tests/ does nothing. The current user sees ALL The tests. No filtering is performed
GET /api/tests/{id} checks that the currently logged in userId corresponds to the userId in the test you are trying to retrieve. If the userIds match, then the user can view this particular test. if they do not match then you get an AUTHORIZATION_REQUIRED or ACCESS_DENIED error (I can't remember which).
as I just wrote in this question, you might want to look at creating a Mixin.

How to restrict certain rows in a Django model to a department?

This looks like it should be easy but I just can't find it.
I'm creating an application where I want to give admin site access to people from different departments. Those people will read and write the same tables, BUT they must only access rows belonging to their department! I.e. they must not see any records produced by the other departments and should be able to modify only the records from their own department. If they create a record, it should automatically "belong" to the department of the user which created it (they will create records only from the admin site).
I've found django-guardian, but it looks like an overkill - I don't really want to have arbitrary per-record permissions.
Also, the number of records will potentially be large, so any kind of front-end permission checking on a per-record basis is not suitable - it must be done by DB-side filtering. Other than that, I'm not really particular how it will be done. E.g. I'm perfectly fine with mapping departments to auth groups.

User specific database entries

I am trying to do user and group specific database entries in my Django-REST-Framework backend. I am conceptually lost. Here's the idea I have so far:
On the database objects I want to retrieve, add a group attribute as well as a creator attribute. When I query the database, depending on the situation, I will filter by creator=request.user or group=request.user.groups.all().
However I do know that the above group part doesn't work. And I imagine I could loop through every group the user belongs to and check the group against each one. However this (to me) seems like a conceptually terrible idea. Lets say the user belongs to 20 groups and the database has 100000 entries - that's up to 2 million checks for one retrieval. That can't be okay. So my question is - how should I do this type of by group retrieval?

Filtering of data according to user logged in Django app

I have a Django app that works well for me, but currently has no notion of user: I am the only one using it, and I would like to change this...
Except for the admin views, the logged-in user should not have access to the data created by other users. There is no shared data between users.
I suppose I have to add a user foreign key to all the models I created. Correct?
Is there a simple way to implement the filtering based on request.user? Can this be done more or less automatically, or do I have to go through all the code to check each and every query done on the database?
I have written the code using TDD, and I intend to follow up... What are the best strategies to ensure that user-filtering is implemented correctly, e.g. that I did not forget to filter an existing query? I suppose I can write tests that show that a particular query is not yet filtered, and implement the filter. But what about the queries that I will write later? Is there a way I can assert that all existing and future queries return objects that only belong to the current user?
Thanks.
Yes, you'll need to add a User FK. Don't forget you'll have to migrate your database tables - either manually, or via a tool like South.
One way of implementing the filter would be to define custom Managers for your models, with a for_user method that takes the User as an argument: something like:
class ForUserManager(models.Manager):
def for_user(self, user):
return self.filter(user=user)
Now you can use this manager - subclassed and/or with a mixin as necessary - on all your models, and remember to use objects.for_user(request.user) everywhere.
This will make testing easier too - your test could monkeypatch that for_user method so that it sets a flag or a counter in a global variable somewhere, and then test that it has incremented as expected.
Edit in response to comment No, as you suspect, that won't work. It's not even that everyone will necessarily get the last-logged-in user: it's that Managers are class-level attributes, and as such are reused throughout a process, so any request served by that server process will use the same one.