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

4

2 回答 2

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.

于 2012-05-14T12:21:57.260 回答
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.

于 2012-05-14T12:22:21.973 回答