8

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

pb2q
  • 58,613
  • 19
  • 146
  • 147
Richard
  • 179
  • 1
  • 6

2 Answers2

15

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.

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
1

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.

Ryan Kim
  • 258
  • 1
  • 6
  • No need for explicitly using session information. The standard django way is just filtering with request.user – Josh Smeaton May 14 '12 at 12:23
  • Well. I just wanted to show'em more basic way. to do the job :) But thanks! – Ryan Kim May 14 '12 at 12:35
  • Just an FYI, request.user is set by the session framework. It is just unusual to have to use the session framework directly. I've not once had to use the session framework (though it does have its places). – Josh Smeaton May 14 '12 at 12:52