Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: keep each users data separate

Tags:

python

django

I am trying to workout how / the best, most secure way to keep a user's data separate within a django site that I need to write.

Here is an example of what I need to do...

example app ToDoList

Using django contrib.auth to manage users / passwords etc, I will have the following users

tom jim lee

There will be a ToDo model (in my real app there will be additional models)

class ToDo(models.Model):
    user = models.ForeignKey(User)
    description = models.CharField(max_length=20)
    details = models.CharField(max_length=50)
    created = models.DateTimeField('created on')

The issue that I am having - and may be over thinking this: How would this be locked down so tom can only see Tom's todo list, lee can only see his todo list and so on...

I have seen a few posts stating that you could use filter in every query, or use urls, so the url could look like www.domain.com/username/todo

But either way I am not sure if this is the right way / best way, or bonkers in terms of stopping users seeing each others data

cheers

Richard

like image 274
Richard Avatar asked May 14 '12 12:05

Richard


2 Answers

One approach is to filter the ToDo items by the currently logged in user:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

from your_app.models import ToDo

@login_required
def todos_for_user(request):
    todos = ToDo.objects.filter(user=request.user)
    return render(request, 'todos/index.html', {'todos' : todos})

This locks down the view for authenticated users only, and filtering by the logged in user from the request, another user, even if logged in, can't access another user's ToDo records. Hope that helps you out.

like image 121
Brandon Avatar answered Sep 22 '22 20:09

Brandon


Make url like www.domain.com/username/todo is one way to implement it, but it doesn't guarantee you achieve security.

What you should do keep your user's login information in a session data after user login, and every time you check certain view,

  1. check whether that particular user has right to see this view.
  2. using user's login info (ID, or username) when querying user's Todo list.

And I guess this link will help you to do your job.

Sessions, Users, and Registration.

like image 35
Ryan Kim Avatar answered Sep 20 '22 20:09

Ryan Kim